问:
After upgrade to java from 11.0.5 to 11.0.6 Lucene maxDoc failed
Our search system process on java 11.0.2, now we want to upgrade it to 11.0.8 or upper... After upgrading to 11.0.6 or upper versions, Lucene RMI connection between servers failed:

```<code>
java.rmi.RemoteException: Method is not Remote: interface org.apache.lucene.search.Searchable::public abstract int org.apache.lucene.search.Searchable.maxDoc() throws java.io.IOException
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:214)
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:162)
    at com.sun.proxy.$Proxy124.maxDoc(Unknown Source)
    at com.exlibris.jaguar.mng.search.Searcher.reset(Searcher.java:444)
    at com.exlibris.jaguar.mng.search.Searcher.<init>(Searcher.java:279)
    at com.exlibris.jaguar.mng.search.Searcher.getInstance(Searcher.java:344)
    at com.exlibris.jaguar.ejbs.JaguarSearchBean.searchB(JaguarSearchBean.java:212)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:77)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy15.searchB(Unknown Source)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:205)
    at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:38)
    at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:78)
    at org.springframework.remoting.rmi.RmiBasedExporter.invoke(RmiBasedExporter.java:73)
    at org.springframework.remoting.rmi.RmiInvocationWrapper.invoke(RmiInvocationWrapper.java:72)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

</code>```
```<code>                try {
                    sliceRemote = (JaguarSearchable)RmiUtil.lookupRemote(
                            RmiUtil.REMOTE_OBJ_PREFIX + slice.getId(),
                            Integer.parseInt(port), host);
                } catch (Exception ee) {
                    logger.warn("Searcher.reset: Slice " + slice.getId() + " is down. Skipping it");
                }
                    try {
                        int maxDoc=sliceRemote.maxDoc();
                        logger.error("max dox " +maxDoc + " of slice:" +slice.getId() + " of group:" + groupId);
                    } catch (Exception e) {
                        logger.error("Cannot get max dox of slice:" +slice.getId() + " of group:" + groupId,e);
                    }
</code>```

Run with java_home 11.0.6 and upper failed..
Run with java 11.0.5 and lower successfully..

Version of Lucene is 3.6.2
lucene-analyzers-3.6.2.jar
lucene-core-3.6.2.jar
lucene-highlighter-3.6.2.jar
lucene-memory-3.6.2.jar
lucene-queries-3.6.2.jar
lucene-queryparser-3.6.2.jar
lucene-remote-3.6.2.jar
lucene-snowball-3.0.3.jar

答:
Ok. I found problem.
After upgrade java upper to 11.0.5 Lucene RMI finish to found
method maxDoc from interface org.apache.lucene.search.Searchable.

JaguarSearchable extends RMIRemoteSearchable
that
RMIRemoteSearchable extends Searchable, Remote
Searchable contains maxDoc but RMI not found it.

After I was overridden maxDoc in JaguarSearchable all start working fine.

I don't know why it happen when update to 11.0.6 and upper version.

Body:
Our search system process on java 11.0.2, now we want to upgrade it to 11.0.8 or upper... After upgrading to 11.0.6 or upper versions, Lucene RMI connection between servers failed:

java.rmi.RemoteException: Method is not Remote: interface org.apache.lucene.search.Searchable::public abstract int org.apache.lucene.search.Searchable.maxDoc() throws java.io.IOException
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:214)
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:162)
    at com.sun.proxy.$Proxy124.maxDoc(Unknown Source)
    at com.exlibris.jaguar.mng.search.Searcher.reset(Searcher.java:444)
    at com.exlibris.jaguar.mng.search.Searcher.<init>(Searcher.java:279)
    at com.exlibris.jaguar.mng.search.Searcher.getInstance(Searcher.java:344)
    at com.exlibris.jaguar.ejbs.JaguarSearchBean.searchB(JaguarSearchBean.java:212)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:77)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy15.searchB(Unknown Source)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:205)
    at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:38)
    at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:78)
    at org.springframework.remoting.rmi.RmiBasedExporter.invoke(RmiBasedExporter.java:73)
    at org.springframework.remoting.rmi.RmiInvocationWrapper.invoke(RmiInvocationWrapper.java:72)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

                try {
                    sliceRemote = (JaguarSearchable)RmiUtil.lookupRemote(
                            RmiUtil.REMOTE_OBJ_PREFIX + slice.getId(),
                            Integer.parseInt(port), host);
                } catch (Exception ee) {
                    logger.warn("Searcher.reset: Slice " + slice.getId() + " is down. Skipping it");
                }
                    try {
                        int maxDoc=sliceRemote.maxDoc();
                        logger.error("max dox " +maxDoc + " of slice:" +slice.getId() + " of group:" + groupId);
                    } catch (Exception e) {
                        logger.error("Cannot get max dox of slice:" +slice.getId() + " of group:" + groupId,e);
                    }

Run with java_home 11.0.6 and upper failed..
Run with java 11.0.5 and lower successfully..

Version of Lucene is 3.6.2
lucene-analyzers-3.6.2.jar
lucene-core-3.6.2.jar
lucene-highlighter-3.6.2.jar
lucene-memory-3.6.2.jar
lucene-queries-3.6.2.jar
lucene-queryparser-3.6.2.jar
lucene-remote-3.6.2.jar
lucene-snowball-3.0.3.jar


来源: stackexchange

问:
Set Tooltip over line Chartjs
I wanna show tooltips over the line not only on data points.
I also tried the chartjs-plugin-crosshair but it doesn't work in V3 of chartjs.

答:
you can use chartjs-plugin-crosshair

function generateDataset(shift, label, color) {
  var data = [];
  var x = 0;

  while (x < 30) {
    data.push({
      x: x,
      y: Math.sin(shift + x / 3)
    });
    x += Math.random();
  }

  var dataset = {
    backgroundColor: color,
    borderColor: color,
    showLine: true,
    fill: false,
    pointRadius: 2,
    label: label,
    data: data,
    lineTension: 0,
    interpolate: true
  };
  return dataset;
}

var chart1 = new Chart(document.getElementById("chart").getContext("2d"), {
  type: "scatter",
  options: {
    plugins: {
      crosshair: {
        sync: {
          enabled: false
        },
      },

      tooltip: {
        animation: false,
        mode: "interpolate",
        intersect: false,
        callbacks: {
          title: function(a, d) {
            return a[0].element.x.toFixed(2);
          },
          label: function(d) {
            return (
              d.chart.data.datasets[d.datasetIndex].label + ": " + d.element.y.toFixed(2)
            );
          }
        }
      }
    },
    scales: {
      x: {
        min: 2,
        max: 28
      }
    }
  },
  data: {
    datasets: [
      generateDataset(0, "A", "red")
    ]
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/moment@2.27.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.4.0/dist/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-crosshair@1.2.0/dist/chartjs-plugin-crosshair.min.js"></script>

<canvas id="chart" height="100"></canvas></code>```

https://jsfiddle.net/Lb0k2sqx/1/

ContentLicense: CC BY-SA 4.0

Title: Set Tooltip over line Chartjs

Body:
you can use chartjs-plugin-crosshair

function generateDataset(shift, label, color) {
  var data = [];
  var x = 0;

  while (x < 30) {
    data.push({
      x: x,
      y: Math.sin(shift + x / 3)
    });
    x += Math.random();
  }

  var dataset = {
    backgroundColor: color,
    borderColor: color,
    showLine: true,
    fill: false,
    pointRadius: 2,
    label: label,
    data: data,
    lineTension: 0,
    interpolate: true
  };
  return dataset;
}

var chart1 = new Chart(document.getElementById("chart").getContext("2d"), {
  type: "scatter",
  options: {
    plugins: {
      crosshair: {
        sync: {
          enabled: false
        },
      },

      tooltip: {
        animation: false,
        mode: "interpolate",
        intersect: false,
        callbacks: {
          title: function(a, d) {
            return a[0].element.x.toFixed(2);
          },
          label: function(d) {
            return (
              d.chart.data.datasets[d.datasetIndex].label + ": " + d.element.y.toFixed(2)
            );
          }
        }
      }
    },
    scales: {
      x: {
        min: 2,
        max: 28
      }
    }
  },
  data: {
    datasets: [
      generateDataset(0, "A", "red")
    ]
  }
});

<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.4.0/dist/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-crosshair@1.2.0/dist/chartjs-plugin-crosshair.min.js"></script>

<canvas id="chart" height="100"></canvas>

https://jsfiddle.net/Lb0k2sqx/1/


问:
How to get-adgroup members by their Name or SamAccountName
i would like to extract members from an AD Group that contains Members and security group.

```<code>Example, Group_A:
User1
User2
User3
Group_B
</code>```

When I run my script, it shows:

CN=User1,OU=Users,DC=Contoso,DC=com
CN=User2,OU=Users,DC=Contoso,DC=com
CN=User3,OU=Users,DC=Contoso,DC=com
CN=Group_B,OU=Users,DC=Contoso,DC=com

Is there another way to show their Name and/or SamAccountname?

```<code>$Groups =
@"
GroupNames;
Group_A
"@ | ConvertFrom-Csv -Delimiter ';'

$ADGroups =
Foreach ($Group in $Groups){
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }

$ADGroups.Members
</code>```

答:
The easiest way would be to expand the members property and in Get-ADGroup and then pipe it to Get-ADUser

```<code>$adUsers = Foreach ($Group in $Groups) {
    Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members | Select-Object -ExpandProperty Members | Get-aduser
}
</code>```

Body:
i would like to extract members from an AD Group that contains Members and security group.

Example, Group_A:
User1
User2
User3
Group_B

When I run my script, it shows:

CN=User1,OU=Users,DC=Contoso,DC=com
CN=User2,OU=Users,DC=Contoso,DC=com
CN=User3,OU=Users,DC=Contoso,DC=com
CN=Group_B,OU=Users,DC=Contoso,DC=com

Is there another way to show their Name and/or SamAccountname?

$Groups =
@"
GroupNames;
Group_A
"@ | ConvertFrom-Csv -Delimiter ';'

$ADGroups =
Foreach ($Group in $Groups){
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }

$ADGroups.Members

Body:
The easiest way would be to expand the members property and in Get-ADGroup and then pipe it to Get-ADUser

$adUsers = Foreach ($Group in $Groups) {
    Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members | Select-Object -ExpandProperty Members | Get-aduser
}


问:
log4j - Intercept logging created within a class/method
I have an App which has many ejb Timer methods which are fired at various intervals, in an attempt to log the performance of these scheduled tasks I have written two methods which log the start and end of every task and records some info such as name, running duration and log info each time the timer fires

The intention with log info was to intercept all logging statements raised from within these methods, output to a string and save...I am doing this by creating a new WriterAppender, appending to the Logger for all logging levels, then when the timer completes capture the string output and remove the appender

This works well but it seems to have 2 unwanted effects:

1) It is stopping any logging from the timer class appearing in our normal file appender logs, eg. the log messages are being captured but they now don't appear in our normal logs (which are configured to show everything > INFO

2) Logging statements from different timers which overlap are appearing in each other logs, I guess this is the result of the Logger working on a single thread, not sure if theres a way around this?

I am no expert in log4j so I am hoping someone can point out a simple fix for 1, 2 or both

Code below shows the 2 methods which are called at start and end of every job

```<code>private Writer w = new StringWriter();
private WriterAppender wa;
private Logger logOutput = Logger.getLogger(ScheduledActions.class);

private TimerEvent logStartTimerEvent(ScheduledTask task){

    RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
    TimerEvent event = new TimerEvent(task);

    //Initialise a new log appender to intercept all log4j entries
    w = new StringWriter();
    Layout l = new PatternLayout("%m%n");
    wa = new WriterAppender(l, w);
    wa.setEncoding("UTF-8");
    wa.setThreshold(Level.ALL);
    wa.activateOptions();

    // Add it to logger
    logOutput = Logger.getLogger(ScheduledActions.class);
    logOutput.addAppender(wa);

    //Push this timer event to redis
    redisActions.addToFixedLengthList(RedisItem.TIMER_HISTORY.getKey()+"_"+task.getName(), gson.toJson(event), 100L);

    return event;
}

private void logEndTimerEvent(TimerEvent event){

    try{

        RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
        event.setLogInfo(w.toString());
        event.setEndTime(new Date());
        redisActions.editLastMemberInList(RedisItem.TIMER_HISTORY.getKey()+"_"+event.getTask().getName(), gson.toJson(event));
        w.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        //clean up the temp log appender
        logOutput.removeAppender(wa);
        wa.close();

    }

}
</code>```

答:
Another solution that I am considering, is adding an AbstractAppender to the rootLogger, and from there do whatever with the logs.

I will update this answer when I develop it a bit more.

```<code>var layout = PatternLayout.newBuilder()
        .withPattern("%d{ISO8601_OFFSET_DATE_TIME_HHCMM} [%t] %-5level  %c{1.} %X %msg%n%throwable")
        .build();

var rootLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();

var appender = new AbstractAppender("intercept-appender", null, layout, false, null) {
    @Override
    public void append(LogEvent event) {
        System.out.println("INTERCEPTED: " + getLayout().toSerializable(event));
    }
};

appender.start();
rootLogger.addAppender(appender);

log.info("Message after adding intercept appender");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an App which has many ejb Timer methods which are fired at various intervals, in an attempt to log the performance of these scheduled tasks I have written two methods which log the start and end of every task and records some info such as name, running duration and log info each time the timer fires

The intention with log info was to intercept all logging statements raised from within these methods, output to a string and save...I am doing this by creating a new WriterAppender, appending to the Logger for all logging levels, then when the timer completes capture the string output and remove the appender

This works well but it seems to have 2 unwanted effects:

1) It is stopping any logging from the timer class appearing in our normal file appender logs, eg. the log messages are being captured but they now don't appear in our normal logs (which are configured to show everything > INFO

2) Logging statements from different timers which overlap are appearing in each other logs, I guess this is the result of the Logger working on a single thread, not sure if theres a way around this?

I am no expert in log4j so I am hoping someone can point out a simple fix for 1, 2 or both

Code below shows the 2 methods which are called at start and end of every job

private Writer w = new StringWriter();
private WriterAppender wa;
private Logger logOutput = Logger.getLogger(ScheduledActions.class);

private TimerEvent logStartTimerEvent(ScheduledTask task){

    RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
    TimerEvent event = new TimerEvent(task);

    //Initialise a new log appender to intercept all log4j entries
    w = new StringWriter();
    Layout l = new PatternLayout("%m%n");
    wa = new WriterAppender(l, w);
    wa.setEncoding("UTF-8");
    wa.setThreshold(Level.ALL);
    wa.activateOptions();

    // Add it to logger
    logOutput = Logger.getLogger(ScheduledActions.class);
    logOutput.addAppender(wa);

    //Push this timer event to redis
    redisActions.addToFixedLengthList(RedisItem.TIMER_HISTORY.getKey()+"_"+task.getName(), gson.toJson(event), 100L);

    return event;
}

private void logEndTimerEvent(TimerEvent event){

    try{

        RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
        event.setLogInfo(w.toString());
        event.setEndTime(new Date());
        redisActions.editLastMemberInList(RedisItem.TIMER_HISTORY.getKey()+"_"+event.getTask().getName(), gson.toJson(event));
        w.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        //clean up the temp log appender
        logOutput.removeAppender(wa);
        wa.close();

    }

}

Body:
Another solution that I am considering, is adding an AbstractAppender to the rootLogger, and from there do whatever with the logs.

I will update this answer when I develop it a bit more.

var layout = PatternLayout.newBuilder()
        .withPattern("%d{ISO8601_OFFSET_DATE_TIME_HHCMM} [%t] %-5level  %c{1.} %X %msg%n%throwable")
        .build();

var rootLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();

var appender = new AbstractAppender("intercept-appender", null, layout, false, null) {
    @Override
    public void append(LogEvent event) {
        System.out.println("INTERCEPTED: " + getLayout().toSerializable(event));
    }
};

appender.start();
rootLogger.addAppender(appender);

log.info("Message after adding intercept appender");


问:
Clarification on overloading
When the parent class have an add method with 2 parameters, If we add new add method with 3 parameters in child class, shall we call this as over loading?

Thanks in advance.

答: If the method name already exists but the parameters are different, then yes, this is overloading.</p>

Title: Clarification on overloading


问:
Logical equality for two different vector widths
Why does logical equality for two vectors of different widths have an output like below?

```<code>module eq_test;

logic check;
logic [3:0] cmp_0;
logic       cmp_1 = 1'b0;

initial begin
    for (int i = 0; i < 16; i++) begin
        cmp_0 = i;
        check = (cmp_0 == cmp_1);
        $display("%b == %b is %b", cmp_0, cmp_1, check);
    end
end

endmodule
</code>```

With Vivado Simulator

```<code>0000 == 0 is 1
0001 == 0 is 0
0010 == 0 is 0
0011 == 0 is 0
0100 == 0 is 0
0101 == 0 is 0
0110 == 0 is 0
0111 == 0 is 0
1000 == 0 is 0
1001 == 0 is 0
1010 == 0 is 0
1011 == 0 is 0
1100 == 0 is 0
1101 == 0 is 0
1110 == 0 is 0
1111 == 0 is 0
</code>```

I can assume that the variable with smaller width cmp_1 is expanded (unsigned expand) to the larger variable width cmp_0, is that so?

答:
Yes, the variable with smaller width is expanded to the larger variable width.

This is described in IEEE Std 1800-2017, section 11.6.1 Rules for expression bit lengths.

The number of bits of an expression (known as the size of the
expression) shall be determined by the operands involved in the
expression and the context in which the expression is given.

In Table 11-21, the == operator has this comment:

Operands are sized to max(L(i),L(j))

where i and j represent expressions of an operand, and L(i) represents the bit length of the operand represented by i.

This is true for all simulators, not just for Vivado.

Body:
Why does logical equality for two vectors of different widths have an output like below?

module eq_test;

logic check;
logic [3:0] cmp_0;
logic       cmp_1 = 1'b0;

initial begin
    for (int i = 0; i < 16; i++) begin
        cmp_0 = i;
        check = (cmp_0 == cmp_1);
        $display("%b == %b is %b", cmp_0, cmp_1, check);
    end
end

endmodule

With Vivado Simulator

0000 == 0 is 1
0001 == 0 is 0
0010 == 0 is 0
0011 == 0 is 0
0100 == 0 is 0
0101 == 0 is 0
0110 == 0 is 0
0111 == 0 is 0
1000 == 0 is 0
1001 == 0 is 0
1010 == 0 is 0
1011 == 0 is 0
1100 == 0 is 0
1101 == 0 is 0
1110 == 0 is 0
1111 == 0 is 0

I can assume that the variable with smaller width cmp_1 is expanded (unsigned expand) to the larger variable width cmp_0, is that so?


问:
Make Promise wait for a Chrome.runtime.sendMessage
I've always seen Promise work with setTimeout, but I'm trying to make it based on whatever the chrome.runtime.sendMessage returns to the Promise.

I've got a content script that does this function once the script has been done.

```<code>chrome.runtime.sendMessage({complete: true});
</code>```

I've got a background script that loops through every item in an array and uses one of its values to open a URL with chrome.tabs.update.

What I'm trying to do is make the async function wait for the Message the content script is sending and only continue with the next iteration once the message has been received, although I don't know how to implement this since I've only seen examples with setTimeout.

So it should

Open the first item in the array and stop

Execute the content script on that page and do a sendMessage at the end.

Now the background script should be waiting for the sendMessage to be received before going to the next item.

Once the sendMessage has been received with onMessage it should go to the next and item and repeat from step 2

This is the background script.

```<code>    chrome.storage.local.get('userItems', function(result) {
    console.log(result.userItems);

    function delay() {
      // I suppose I should do something with onMessage in the delay function
      return new Promise(resolve => setTimeout(resolve, 500));
    }

    async function delayedLog(item) {
      await delay();

      console.log(item);
      var url = "http://www.example.com/" + item.Category;

      chrome.tabs.update({
        url: url
      });
    }

    async function processArray(array) {
      for (const item of array) {
        await delayedLog(item);
      }
    }

    processArray(result.userItems);

    });
</code>```

答:
Adopting from what is shared above, the following example demonstrates sending the response synchronously and asynchronously. This worked for me where I was able to send the request object to the content script and receive the response object back from the content script.

In your background.js, add the following snippet which wraps the promise around the sendMessage function.

```<code>function sendMessage(tabId, request) {
    return new Promise((resolve, reject) => {
      chrome.tabs.sendMessage(tabId, request, (response) => {
        if (response.success) {
          resolve(response)
        }
        else {
          reject(response)
        }
      });
    })
}
const tabId = 123;
const request = {id: 1, message: "hello"};
const response = await sendMessage(tabId, request);

response.success ? console.info(response.data)
                 : console.error(response.message);
</code>```

In your content script:

```<code>const handleRequest = (request, sender, sendResponse) => {
  console.info("Request received...");

  if (request && request.id > 0) {
    doLogic(request.id, sendResponse);

    // return true to send the response asynchronously
    return true;
  }
  else {
    // send synchronous response object back with an error message
    sendResponse({success: false, message: "Invalid Id received"});
  }
}

chrome.runtime.onMessage.addListener(handleRequest);
</code>```

In your doLogic function:

```<code>const doLogic = async (id, sendResponse) => {
  const value= await asyncOperation(id); // awaiting another async call
  sendResponse({success: true, data: value});
};
</code>```

As shown above, the doLogic() function takes the id and the sendResponse as inputs. Once the doLogic() finishes the await operation inside, then it sends the response.

By sending true in the listener, as mentioned by Denis L, you wish to send the response asynchronously. You can read more on that here where it mentions as shown below:

Executing the example code, you'd receive the following output. Modify the request object to see the change in the output.

Output:
world

Body:
I've always seen Promise work with setTimeout, but I'm trying to make it based on whatever the chrome.runtime.sendMessage returns to the Promise.

I've got a content script that does this function once the script has been done.

chrome.runtime.sendMessage({complete: true});

I've got a background script that loops through every item in an array and uses one of its values to open a URL with chrome.tabs.update.

What I'm trying to do is make the async function wait for the Message the content script is sending and only continue with the next iteration once the message has been received, although I don't know how to implement this since I've only seen examples with setTimeout.

So it should

Open the first item in the array and stop

Execute the content script on that page and do a sendMessage at the end.

Now the background script should be waiting for the sendMessage to be received before going to the next item.

Once the sendMessage has been received with onMessage it should go to the next and item and repeat from step 2

This is the background script.

    chrome.storage.local.get('userItems', function(result) {
    console.log(result.userItems);

    function delay() {
      // I suppose I should do something with onMessage in the delay function
      return new Promise(resolve => setTimeout(resolve, 500));
    }

    async function delayedLog(item) {
      await delay();

      console.log(item);
      var url = "http://www.example.com/" + item.Category;

      chrome.tabs.update({
        url: url
      });
    }

    async function processArray(array) {
      for (const item of array) {
        await delayedLog(item);
      }
    }

    processArray(result.userItems);

    });

Body:
Adopting from what is shared above, the following example demonstrates sending the response synchronously and asynchronously. This worked for me where I was able to send the request object to the content script and receive the response object back from the content script.

In your background.js, add the following snippet which wraps the promise around the sendMessage function.

function sendMessage(tabId, request) {
    return new Promise((resolve, reject) => {
      chrome.tabs.sendMessage(tabId, request, (response) => {
        if (response.success) {
          resolve(response)
        }
        else {
          reject(response)
        }
      });
    })
}
const tabId = 123;
const request = {id: 1, message: "hello"};
const response = await sendMessage(tabId, request);

response.success ? console.info(response.data)
                 : console.error(response.message);

In your content script:

const handleRequest = (request, sender, sendResponse) => {
  console.info("Request received...");

  if (request && request.id > 0) {
    doLogic(request.id, sendResponse);

    // return true to send the response asynchronously
    return true;
  }
  else {
    // send synchronous response object back with an error message
    sendResponse({success: false, message: "Invalid Id received"});
  }
}

chrome.runtime.onMessage.addListener(handleRequest);

In your doLogic function:

const doLogic = async (id, sendResponse) => {
  const value= await asyncOperation(id); // awaiting another async call
  sendResponse({success: true, data: value});
};

As shown above, the doLogic() function takes the id and the sendResponse as inputs. Once the doLogic() finishes the await operation inside, then it sends the response.

By sending true in the listener, as mentioned by Denis L, you wish to send the response asynchronously. You can read more on that here where it mentions as shown below:

Executing the example code, you'd receive the following output. Modify the request object to see the change in the output.

Output:
world


问:
How to represent regex number ranges (e.g. 1 to 12)?
I'm currently using ([1-9]|1[0-2]) to represent inputs from 1 to 12. (Leading zeros not allowed.)

However it seems rather hacky, and on some days it looks outright dirty.

☞ Is there a proper in-built way to do it?

☞ What are some other ways to represent number ranges?

答:
Yes, the correct one:

```<code>[1-9]|1[0-2]
</code>```

Otherwise you don't get the 10.

Body:
Yes, the correct one:

[1-9]|1[0-2]

Otherwise you don't get the 10.


问:
implicit "popd" on batch exit
Is there a way to undo all pushd at the end of script. What I have is:

```<code>pushd somwhere
rem doing stuff
goto end

:end
popd
goto :EOF
</code>```

What I'd like to have is:

```<code>setlocal
pushd somwhere
rem doing stuff
goto :EOF
</code>```

But that doesn't work, the directory stays "pushd". Another try where I can't say how many pushd will occur would be:

```<code>set CurrentDir=%CD%
rem doing a lot of pushd and popd
pushd somwhere

:POPBACK
if /i not "%CD%" == "%CurrentDir%" popd & goto POPBACK
</code>```

But that looks like I can easily get stuck at :POPBACK. Adding a counter to exit that loop is a bit uncertain at which dir I end up.

In that context I'd like to know if a can see the stack of pushd directories. The only thing I found was $+ in prompt $P$+$G which adds a '+' for each pushd directory e.g. D:\CMD++>. But I can't see a way how to make use of that.

EDIT:
I just noticed there is something wrong with the $+ of prompt that confused me.
The setlocal in the example above actually makes the script return to the initial directory, but the prompt shows a '+' indicating a missing popd.

```<code>D:\CMD>test.cmd
D:\CMD>prompt $P$+$g
D:\CMD>setlocal
D:\CMD>pushd e:\DATA
e:\DATA+>goto :EOF
D:\CMD+>popd
D:\CMD>
</code>```

EDIT:
Due to the hint to the difference between local environment and directory stack I expanded the example form above, pushing to C:\DATA before calling the script. the script returns to where it has been called from (C:\DATA). So far so good. The first popd shows no effect as it removes the last pushd from stack but not changing the directory, since the directory change has been undone by the (implicit) endlocal. The second popd returns to initial directory as expected.

```<code>D:\CMD>pushd C:\DATA
C:\DATA+>d:\cmd\test.cmd
C:\DATA+>prompt $P$+$g
C:\DATA+>setlocal
C:\DATA+>pushd e:\DATA
e:\DATA++>goto :EOF
C:\DATA++>popd
C:\DATA+>popd
D:\CMD>
</code>```

答:
After my own reminder of exit codes in a now deleted comment and the answer posted by @Aacini, one more version

```<code>@echo off
pushd "somewhere"
pushd "somewhere else"

:pop
popd && (echo %cd% & goto :pop) || goto :EOF
</code>```

Where echo %cd% will only show the each item in the stack, so can be removed and simply become:

```<code>:pop
popd && goto :pop || goto :EOF
</code>```

Title: implicit "popd" on batch exit

Body:
Is there a way to undo all pushd at the end of script. What I have is:

pushd somwhere
rem doing stuff
goto end

:end
popd
goto :EOF

What I'd like to have is:

setlocal
pushd somwhere
rem doing stuff
goto :EOF

But that doesn't work, the directory stays "pushd". Another try where I can't say how many pushd will occur would be:

set CurrentDir=%CD%
rem doing a lot of pushd and popd
pushd somwhere

:POPBACK
if /i not "%CD%" == "%CurrentDir%" popd & goto POPBACK

But that looks like I can easily get stuck at :POPBACK. Adding a counter to exit that loop is a bit uncertain at which dir I end up.

In that context I'd like to know if a can see the stack of pushd directories. The only thing I found was $+ in prompt $P$+$G which adds a '+' for each pushd directory e.g. D:\CMD++>. But I can't see a way how to make use of that.

EDIT:
I just noticed there is something wrong with the $+ of prompt that confused me.
The setlocal in the example above actually makes the script return to the initial directory, but the prompt shows a '+' indicating a missing popd.

D:\CMD>test.cmd
D:\CMD>prompt $P$+$g
D:\CMD>setlocal
D:\CMD>pushd e:\DATA
e:\DATA+>goto :EOF
D:\CMD+>popd
D:\CMD>

EDIT:
Due to the hint to the difference between local environment and directory stack I expanded the example form above, pushing to C:\DATA before calling the script. the script returns to where it has been called from (C:\DATA). So far so good. The first popd shows no effect as it removes the last pushd from stack but not changing the directory, since the directory change has been undone by the (implicit) endlocal. The second popd returns to initial directory as expected.

D:\CMD>pushd C:\DATA
C:\DATA+>d:\cmd\test.cmd
C:\DATA+>prompt $P$+$g
C:\DATA+>setlocal
C:\DATA+>pushd e:\DATA
e:\DATA++>goto :EOF
C:\DATA++>popd
C:\DATA+>popd
D:\CMD>

Body:
After my own reminder of exit codes in a now deleted comment and the answer posted by @Aacini, one more version

@echo off
pushd "somewhere"
pushd "somewhere else"

:pop
popd && (echo %cd% & goto :pop) || goto :EOF

Where echo %cd% will only show the each item in the stack, so can be removed and simply become:

:pop
popd && goto :pop || goto :EOF


问:
How to recover a .jpg image from a encoded GMail attachment in Python
I'm using the GMail API in Python.
I am succesfully downloading the attachment of an email using

```<code>attachment = service.users().messages().attachments().get(userId='me', messageId = msg_id, id=attachment_id).execute()
</code>```

From this I can recover the data and decode it using

```<code>data = attachement['data']
decoded_data = base64.urlsafe_b64decode(data.encode('utf-8'))
</code>```

However, I do not understand how to recover the .jpg from this string.

答:
The answer is very straightforward.
First two functions from 2 different libraries must be imported:

```<code>from io import BytesIO
from PIL import Image
</code>```

Then the image can be saved using these two functions:

```<code>im = Image.open(BytesIO(decoded_data))
im.save('attachement', 'JPEG')
</code>```

Body:
I'm using the GMail API in Python.
I am succesfully downloading the attachment of an email using

attachment = service.users().messages().attachments().get(userId='me', messageId = msg_id, id=attachment_id).execute()

From this I can recover the data and decode it using

data = attachement['data']
decoded_data = base64.urlsafe_b64decode(data.encode('utf-8'))

However, I do not understand how to recover the .jpg from this string.

Body:
The answer is very straightforward.
First two functions from 2 different libraries must be imported:

from io import BytesIO
from PIL import Image

Then the image can be saved using these two functions:

im = Image.open(BytesIO(decoded_data))
im.save('attachement', 'JPEG')


问:
Flag duplicate relationship in excel
I have data available in excel as given below:

Below is the criteria for the expected column:

Duplicate relationship should be color coded/flagged.

I have added expected result in a column G Is duplicated?.

To achieve that I have tried using Match function of excel, but it doesn't match my requirement.

Please suggest what should be the correct approach to fix this.

答:
You can create a sorted csv of each of the words on each row:

```<code>=TEXTJOIN(",",FALSE,SORT($A3:$D3,1,1,TRUE))
</code>```

name
relation
name
relation
sorted_csv

Milly
Wife
Jack
Husband
Husband,Jack,Milly,Wife

Jack
Husband
Milly
Wife
Husband,Jack,Milly,Wife

Reacher
Son
Jack
Father
Father,Jack,Reacher,Son

Reacher
Son
Jack
Mother
Jack,Mother,Reacher,Son

Then you can count the rows by sorted_csv:

```<code>=COUNTIF($E$3:$E$6,$E3)
</code>```

name
relation
name
relation
sorted_csv
count by sorted_csv

Milly
Wife
Jack
Husband
Husband,Jack,Milly,Wife
2

Jack
Husband
Milly
Wife
Husband,Jack,Milly,Wife
2

Reacher
Son
Jack
Father
Father,Jack,Reacher,Son
1

Reacher
Son
Jack
Mother
Jack,Mother,Reacher,Son
1

Any row that has a count greater than 1 is a duplicate of another row.

Title: Flag duplicate relationship in excel

Body:
You can create a sorted csv of each of the words on each row:

=TEXTJOIN(",",FALSE,SORT($A3:$D3,1,1,TRUE))

name
relation
name
relation
sorted_csv

Milly
Wife
Jack
Husband
Husband,Jack,Milly,Wife

Jack
Husband
Milly
Wife
Husband,Jack,Milly,Wife

Reacher
Son
Jack
Father
Father,Jack,Reacher,Son

Reacher
Son
Jack
Mother
Jack,Mother,Reacher,Son

Then you can count the rows by sorted_csv:

=COUNTIF($E$3:$E$6,$E3)

name
relation
name
relation
sorted_csv
count by sorted_csv

Milly
Wife
Jack
Husband
Husband,Jack,Milly,Wife
2

Jack
Husband
Milly
Wife
Husband,Jack,Milly,Wife
2

Reacher
Son
Jack
Father
Father,Jack,Reacher,Son
1

Reacher
Son
Jack
Mother
Jack,Mother,Reacher,Son
1

Any row that has a count greater than 1 is a duplicate of another row.


问:
vim substitution expand to uppercase
I insert the name of my file into its skeleton when i open it with this command into my ~/.vimrc file :

```<code>function! HPPFile()
    silent! 0r $HOME/.vim/templates/skeleton.hpp
    %s/FileName/\=expand("%:t:r")/g
    %s/FILENAME/\U\=expand("%:t:r")\E/g
endfunction
autocmd BufNewFile *.hpp call HPPFile()
</code>```

the first expansion line works well %s/FileName/\=expand("%:t:r")/g : all instances of FileName get replaced by the file name

but the second expansion line doesn't works %s/FILENAME/\U\=expand("%:t:r")\E/g -> it seems i cannot use both the uppercase substitution and the expand action

I've tried some variations but without chance, how could i do that ?

答:
It seems once you're in evaluation mode you must use it for everything. Try</p>
```<code>%s/FILENAME/\=toupper(expand("%:t:r"))/g
</code>```

Title: vim substitution expand to uppercase

Body:
I insert the name of my file into its skeleton when i open it with this command into my ~/.vimrc file :

function! HPPFile()
    silent! 0r $HOME/.vim/templates/skeleton.hpp
    %s/FileName/\=expand("%:t:r")/g
    %s/FILENAME/\U\=expand("%:t:r")\E/g
endfunction
autocmd BufNewFile *.hpp call HPPFile()

the first expansion line works well %s/FileName/\=expand("%:t:r")/g : all instances of FileName get replaced by the file name

but the second expansion line doesn't works %s/FILENAME/\U\=expand("%:t:r")\E/g -> it seems i cannot use both the uppercase substitution and the expand action

I've tried some variations but without chance, how could i do that ?

Body:
It seems once you're in evaluation mode you must use it for everything. Try

%s/FILENAME/\=toupper(expand("%:t:r"))/g


问:
How can I define a django model's field default value to be another field value?
In my model I have these two fields:

```<code>start_bid = models.IntegerField(default=0)
max_bid =  models.IntegerField(default="the start_bid value")
</code>```

The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not.
So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated.

In brief, I need the initial value of max_bid to be equal to the start_bid!

Any suggestions?

答:
Overwrite save method on model.</p>
```<code>def save(self, force_insert=False, force_update=False, using=None,  update_fields=None):
        if self._state.adding:
            self.max_bid = self.start_bid
        super().save(force_insert, force_update, using, update_fields)
</code>```

Body:
In my model I have these two fields:

start_bid = models.IntegerField(default=0)
max_bid =  models.IntegerField(default="the start_bid value")

The start_bid will be added by the user once through Django ModelForm. And the max_bid may change and may not.
So I need the first value of 'max_bid' to be the start_bid value entered by the user, then if it changes it will be updated.

In brief, I need the initial value of max_bid to be equal to the start_bid!

Any suggestions?

Body:
Overwrite save method on model.

def save(self, force_insert=False, force_update=False, using=None,  update_fields=None):
        if self._state.adding:
            self.max_bid = self.start_bid
        super().save(force_insert, force_update, using, update_fields)


问:
asyncTask and progressDialog : Freeze
please see my code .. and if you can, tell me why my progressDialog stopped when the function is halfway done in the background, the screen hangs (nothing is displayed, the logcat shows all logs i put in the background function).

Then, right before the end, the progressDialog starts animating again and closes after a couple seconds (the function is finished and the result is displayed normally)

```<code>public class changeWall extends AsyncTask<Integer, Integer, Integer> {
        protected Integer doInBackground(Integer... urls) {
            int totalSize=0;
            try {

                 if(s.loadBoolean() == false)
                {
                     log("IF = false");
                     log("tempLogin = "+tempLogin);
                     log("tempPassword = "+tempPassword);
                     getNewResponse(tempLogin,tempPassword);
                if(needSave)
                {
                 s.saveBoolean(true);
                }

                }
                 else
                 {
                if(s.loadLogin()==null)
                {
                   getNewResponse(tempLogin,tempPassword);
                }else
                {
                    getNewResponse(s.loadLogin(),s.loadPassowrd());
                }
                 }
                parser.setLol(0);

                parser.startParse(RESULT_STRING);

             log("end parse");
            } catch (ClientProtocolException e) {
                log("internet connection lost");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log(" connection lost");
            }
            log("count = "+parser.getFacebookId(1));
            publishProgress();
            totalSize=1;
            log("end of start");
            return totalSize;
        }

        protected void onProgressUpdate(Integer... progress) {
            log("wall click ON PROGRESS UPDATE");
            wall.setBackgroundResource(R.drawable.tabbuttonon);
            messages.setBackgroundResource(0);
            activity.setBackgroundResource(0);
            profile.setBackgroundResource(0);
            l1_1.setBackgroundResource(R.drawable.tabbuttononleft);
            l1_2.setBackgroundResource(R.drawable.tabbuttononright);
            l2_1.setBackgroundResource(0);
            l2_2.setBackgroundResource(0);
            l3_1.setBackgroundResource(0);
            l3_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            wall.setTextColor(Color.BLACK);
            messages.setTextColor(Color.WHITE);
            profile.setTextColor(Color.WHITE);
            activity.setTextColor(Color.WHITE);

            try {
                loadWall();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
               wallProgres.dismiss();
        }

        protected void onPostExecute(Long result) {
           if(result==1)
           {
               log("end WallChange");

           }
        }
    }
</code>```

simple map as this showed :

```<code>----start progress(progress.show())
----start function
--- animation (progressDialog)
---animation(---)
---animation(---)
---FREEZ
---FREEZ(Function steel working normal, progressDialog in freeze mode)
---animation
---end function
---progress.dismis();//
</code>```

similar problem i found here..(this problem = my problem but without download) Freezing UI Thread with AsyncTask
Regards,Peter.

答:
It may not be correct but place

```<code>wallProgres.dismiss();
 in  onPostExecute rather than in onProgessUpdate method.
</code>```

beacuse onProgressUpdate calls while running , but onPostExecute calls after execution.

Hope it helps..

Title: asyncTask and progressDialog : Freeze

Body:
please see my code .. and if you can, tell me why my progressDialog stopped when the function is halfway done in the background, the screen hangs (nothing is displayed, the logcat shows all logs i put in the background function).

Then, right before the end, the progressDialog starts animating again and closes after a couple seconds (the function is finished and the result is displayed normally)

public class changeWall extends AsyncTask<Integer, Integer, Integer> {
        protected Integer doInBackground(Integer... urls) {
            int totalSize=0;
            try {

                 if(s.loadBoolean() == false)
                {
                     log("IF = false");
                     log("tempLogin = "+tempLogin);
                     log("tempPassword = "+tempPassword);
                     getNewResponse(tempLogin,tempPassword);
                if(needSave)
                {
                 s.saveBoolean(true);
                }

                }
                 else
                 {
                if(s.loadLogin()==null)
                {
                   getNewResponse(tempLogin,tempPassword);
                }else
                {
                    getNewResponse(s.loadLogin(),s.loadPassowrd());
                }
                 }
                parser.setLol(0);

                parser.startParse(RESULT_STRING);

             log("end parse");
            } catch (ClientProtocolException e) {
                log("internet connection lost");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log(" connection lost");
            }
            log("count = "+parser.getFacebookId(1));
            publishProgress();
            totalSize=1;
            log("end of start");
            return totalSize;
        }

        protected void onProgressUpdate(Integer... progress) {
            log("wall click ON PROGRESS UPDATE");
            wall.setBackgroundResource(R.drawable.tabbuttonon);
            messages.setBackgroundResource(0);
            activity.setBackgroundResource(0);
            profile.setBackgroundResource(0);
            l1_1.setBackgroundResource(R.drawable.tabbuttononleft);
            l1_2.setBackgroundResource(R.drawable.tabbuttononright);
            l2_1.setBackgroundResource(0);
            l2_2.setBackgroundResource(0);
            l3_1.setBackgroundResource(0);
            l3_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            wall.setTextColor(Color.BLACK);
            messages.setTextColor(Color.WHITE);
            profile.setTextColor(Color.WHITE);
            activity.setTextColor(Color.WHITE);

            try {
                loadWall();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
               wallProgres.dismiss();
        }

        protected void onPostExecute(Long result) {
           if(result==1)
           {
               log("end WallChange");

           }
        }
    }

simple map as this showed :

----start progress(progress.show())
----start function
--- animation (progressDialog)
---animation(---)
---animation(---)
---FREEZ
---FREEZ(Function steel working normal, progressDialog in freeze mode)
---animation
---end function
---progress.dismis();//

similar problem i found here..(this problem = my problem but without download) Freezing UI Thread with AsyncTask
Regards,Peter.

Body:
It may not be correct but place

wallProgres.dismiss();
 in  onPostExecute rather than in onProgessUpdate method.

beacuse onProgressUpdate calls while running , but onPostExecute calls after execution.

Hope it helps..


问:
creating a devtools session with selenium 4 using remotewebdriver
trying to run with
webdriver contianer and selenium 4 after creating a devtools session I am getting:

class org.openqa.selenium.remote.RemoteWebDriver cannot be cast to class org.openqa.selenium.chrome.ChromeDriver
when running:

```<code>scenarioContext.setDevTools(((ChromeDriver) scenarioContext.getDriver()).getDevTools());
</code>```

How can I solve this? I need to somehow cast remotewebdriver to chromedriver in order to use devtools.

答:
This is an example of using DevTools with RemoteWebDriver from official documentation: https://www.selenium.dev/documentation/webdriver/bidirectional/chrome_devtools/</p>
```<code>    ChromeOptions chromeOptions = new ChromeOptions();
    WebDriver driver = new RemoteWebDriver(new URL("<grid-url>"), chromeOptions);
    driver = new Augmenter().augment(driver);
    DevTools devTools = ((HasDevTools) driver).getDevTools();
    devTools.createSession();
</code>```

Body:
trying to run with
webdriver contianer and selenium 4 after creating a devtools session I am getting:

class org.openqa.selenium.remote.RemoteWebDriver cannot be cast to class org.openqa.selenium.chrome.ChromeDriver
when running:

scenarioContext.setDevTools(((ChromeDriver) scenarioContext.getDriver()).getDevTools());

How can I solve this? I need to somehow cast remotewebdriver to chromedriver in order to use devtools.

Body:
This is an example of using DevTools with RemoteWebDriver from official documentation: https://www.selenium.dev/documentation/webdriver/bidirectional/chrome_devtools/

    ChromeOptions chromeOptions = new ChromeOptions();
    WebDriver driver = new RemoteWebDriver(new URL("<grid-url>"), chromeOptions);
    driver = new Augmenter().augment(driver);
    DevTools devTools = ((HasDevTools) driver).getDevTools();
    devTools.createSession();


问:
Cannot find module 'semver'
```<code>node:internal/modules/cjs/loader:936
  throw err;
  ^
</code>```

/am finding this error even after remoning installed node/
Error: Cannot find module 'semver'
Require stack:
- /usr/share/nodejs/npm/lib/utils/unsupported.js
- /usr/share/nodejs/npm/lib/cli.js
- /usr/share/nodejs/npm/bin/npm-cli.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object. (/usr/share/nodejs/npm/lib/utils/unsupported.js:1:16)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/usr/share/nodejs/npm/lib/utils/unsupported.js',
'/usr/share/nodejs/npm/lib/cli.js',
'/usr/share/nodejs/npm/bin/npm-cli.js'
]
}

```<code>Node.js v17.4.0
</code>```

答:
did you installed semver module ?

You can try to install semver with command:

```<code>npm install semver --save
</code>```

Title: Cannot find module 'semver'

Body:
node:internal/modules/cjs/loader:936
  throw err;
  ^

/am finding this error even after remoning installed node/
Error: Cannot find module 'semver'
Require stack:
- /usr/share/nodejs/npm/lib/utils/unsupported.js
- /usr/share/nodejs/npm/lib/cli.js
- /usr/share/nodejs/npm/bin/npm-cli.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object. (/usr/share/nodejs/npm/lib/utils/unsupported.js:1:16)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/usr/share/nodejs/npm/lib/utils/unsupported.js',
'/usr/share/nodejs/npm/lib/cli.js',
'/usr/share/nodejs/npm/bin/npm-cli.js'
]
}

Node.js v17.4.0

Body:
did you installed semver module ?

You can try to install semver with command:

npm install semver --save


问:
Error when plotting with geoseries in a shapefile
I´m trying to plot my Kmean clustering in a shapefile from my city, but I keep getting an error with Geoseries my code

```<code>    km = MiniBatchKMeans(n_clusters=i)
km.fit_predict(df_pickup)

# Label cluster centers
centers = km.cluster_centers_

# Calculate sum of squared distances
ssd.append(km.inertia_)

# Get cluster center
df_pickup['cluster'] = km.labels_

geo_df = gpd.GeoDataFrame(df_pickup.drop(['longitud','latitud'],axis=1),
geometry=gpd.points_from_xy(x=df_pickup.longitud, y=df_pickup.latitud))

centers_gseries = GeoSeries(map(Point, zip(centers[:,1], centers[:,0])))
centers_gseries.plot(ax=ax, alpha=1, marker='X', color='red', markersize=100, zorder=3)
</code>```

The error

```<code>---> 41     centers_gseries = GeoSeries(map(Point, zip(centers[:,1], centers[:,0])))
TypeError: __init__() missing 1 required positional argument: 'y'
</code>```

I´m passing my two coordinates so I don´t know why It gives me that error

答:
Use a built-in method to create points instead.

centers_gseries = GeoSeries.from_xy(centers[:,1], centers[:,0])
```

Body:
I´m trying to plot my Kmean clustering in a shapefile from my city, but I keep getting an error with Geoseries my code

    km = MiniBatchKMeans(n_clusters=i)
km.fit_predict(df_pickup)

# Label cluster centers
centers = km.cluster_centers_

# Calculate sum of squared distances
ssd.append(km.inertia_)

# Get cluster center
df_pickup['cluster'] = km.labels_

geo_df = gpd.GeoDataFrame(df_pickup.drop(['longitud','latitud'],axis=1),
geometry=gpd.points_from_xy(x=df_pickup.longitud, y=df_pickup.latitud))

centers_gseries = GeoSeries(map(Point, zip(centers[:,1], centers[:,0])))
centers_gseries.plot(ax=ax, alpha=1, marker='X', color='red', markersize=100, zorder=3)

The error

---> 41     centers_gseries = GeoSeries(map(Point, zip(centers[:,1], centers[:,0])))
TypeError: __init__() missing 1 required positional argument: 'y'

I´m passing my two coordinates so I don´t know why It gives me that error


答:
Yes, since the method with two parameters is inherited by the subclass, the method with three parameters is said to be an overloading method.

```<code>class A
    add(param1, param2)

class B
    add(param1, param2)            <-- inherited
    add(param1, param2, param3)    <-- overloading the above method
</code>```

A quote from the official trail on Overriding and Hiding Methods:

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.

(As you probably already figured out, the method with three classes is not an overriding method.)

Title: Clarification on overloading

Body:
When the parent class have an add method with 2 parameters, If we add new add method with 3 parameters in child class, shall we call this as over loading?

Thanks in advance.

Body:
Yes, since the method with two parameters is inherited by the subclass, the method with three parameters is said to be an overloading method.

class A
    add(param1, param2)

class B
    add(param1, param2)            <-- inherited
    add(param1, param2, param3)    <-- overloading the above method

A quote from the official trail on Overriding and Hiding Methods:

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.

(As you probably already figured out, the method with three classes is not an overriding method.)


问:
The Repository Service marked the session or session instance as impacted
I am new in control-M. I have a work flow that i developed in Informatica....When i run the work flow in informatica workflow manager itz working fine...but when i scheduled it in Control-M Its making an error -

The Repository Service marked the session or session instance as
  impacted, and the Integration Service is not configured to run
  impacted sessions

What will be the reason for this? If any one knows please help me..that will be very greatful for me....

Regards.....

答:
Check 2 things:

Edit Session -> mapping-> source-> connections

Is connection correct? If it isn't, choice the correct connection.

Edit Session -> config object-> error handling-> override tracing

After to get session log, we can forget the settings that taking back to "override tracing = None" from "override tracing = Verbose"


问:
get auth/argument-error with next-firebase-auth

Problems:

I get the error below when I tried to login using firebase auth. Everything is fine when I login using firebase auth emulator, but it presents error when using without using the auth emulator. I have also received a 500 response from login API endpoint: {"error":"Unexpected error."} from browser console, which I presume the error is highly related with next-firebase-auth.

```<code>FirebaseAuthError: `uid` argument must be a non-empty string uid.
at FirebaseAuthError.FirebaseError [as constructor] (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\utils\error.js:44:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\utils\error.js:90:28)
at new FirebaseAuthError (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\utils\error.js:149:16)
at FirebaseTokenGenerator.createCustomToken (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\auth\token-generator.js:101:19)
at Auth.BaseAuth.createCustomToken (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\auth\base-auth.js:87:36)
at D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\next-firebase-auth\build\index.node.js:2:22240
at Generator.next (<anonymous>)
at asyncGeneratorStep (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
 errorInfo: {
   code: 'auth/argument-error',
   message: '`uid` argument must be a non-empty string uid.'
 },
   codePrefix: 'auth'
 }
</code>```

I have set up my /api/login page exactly as the official example. I have tried using signInWithEmailAndPassword and signInWithPopup (which using Google to authenticate), both did success to login as console.log(results) shows the user credentials and I can also find the relevant data in indexed DB too.

Versions of the packages

"next-firebase-auth": "^1.0.0-canary.5"

"firebase-admin": "^10.0.2",

"firebase": "^9.6.1",

The main issues was with login page, and here's the
Github Repo.

答: I finally found the solution on github, remove the FIREBASE_AUTH_EMULATOR_HOST=localhost:9099 in your .env.local file, and everythings is back on track again, what a weird problem.

Body:
Problems:

I get the error below when I tried to login using firebase auth. Everything is fine when I login using firebase auth emulator, but it presents error when using without using the auth emulator. I have also received a 500 response from login API endpoint: {"error":"Unexpected error."} from browser console, which I presume the error is highly related with next-firebase-auth.

FirebaseAuthError: `uid` argument must be a non-empty string uid.
at FirebaseAuthError.FirebaseError [as constructor] (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\utils\error.js:44:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\utils\error.js:90:28)
at new FirebaseAuthError (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\utils\error.js:149:16)
at FirebaseTokenGenerator.createCustomToken (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\auth\token-generator.js:101:19)
at Auth.BaseAuth.createCustomToken (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\firebase-admin\lib\auth\base-auth.js:87:36)
at D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\next-firebase-auth\build\index.node.js:2:22240
at Generator.next (<anonymous>)
at asyncGeneratorStep (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (D:\Alston\Programming\Personal-Project\netflix-clone\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
 errorInfo: {
   code: 'auth/argument-error',
   message: '`uid` argument must be a non-empty string uid.'
 },
   codePrefix: 'auth'
 }

I have set up my /api/login page exactly as the official example. I have tried using signInWithEmailAndPassword and signInWithPopup (which using Google to authenticate), both did success to login as console.log(results) shows the user credentials and I can also find the relevant data in indexed DB too.

Versions of the packages

"next-firebase-auth": "^1.0.0-canary.5"

"firebase-admin": "^10.0.2",

"firebase": "^9.6.1",

The main issues was with login page, and here's the
Github Repo.


问:
firestore the getter 'length' isn't defined for the type 'DocumentSnapshot<Object?>'
I try to count all docs from one user in firestore.
My code:

```<code>  Widget booksWidget(String userData) {
    return
    StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection("bookList")
            .doc(userData)
            .collection(userData)
            .orderBy("timestamp", descending: true)
            .snapshots(),
        builder: (BuildContext context,AsyncSnapshot snapshot)  {
          if (snapshot.hasData) {
            var userDocument = snapshot.data as DocumentSnapshot?;
            String books = userDocument?.length.toString();
            return Text(books);
          }else{
            return Text("none");
          }
        }
    );
  }
</code>```

the error:

```<code>The getter 'length' isn't defined for the type 'DocumentSnapshot<Object?>'.
</code>```

thanks for help, streambuilder after migration to null-safety is quite different :(

答:
You're requesting the snapshots of a query, so the snapshot.data that you get is going to be of type QuerySnapshot (and not a DocumentSnapshot? as you assume now).

```<code>if (snapshot.hasData) {
  var querySnapshot = snapshot.data! as QuerySnapshot;
  String books = querySnapshot.docs.length.toString();
  ...
</code>```

In cases like this I find it easiest to work from the reference documentation, such as the one for Query.snapshots() here.

Body:
I try to count all docs from one user in firestore.
My code:

  Widget booksWidget(String userData) {
    return
    StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection("bookList")
            .doc(userData)
            .collection(userData)
            .orderBy("timestamp", descending: true)
            .snapshots(),
        builder: (BuildContext context,AsyncSnapshot snapshot)  {
          if (snapshot.hasData) {
            var userDocument = snapshot.data as DocumentSnapshot?;
            String books = userDocument?.length.toString();
            return Text(books);
          }else{
            return Text("none");
          }
        }
    );
  }

the error:

The getter 'length' isn't defined for the type 'DocumentSnapshot<Object?>'.

thanks for help, streambuilder after migration to null-safety is quite different :(

Body:
You're requesting the snapshots of a query, so the snapshot.data that you get is going to be of type QuerySnapshot (and not a DocumentSnapshot? as you assume now).

if (snapshot.hasData) {
  var querySnapshot = snapshot.data! as QuerySnapshot;
  String books = querySnapshot.docs.length.toString();
  ...

In cases like this I find it easiest to work from the reference documentation, such as the one for Query.snapshots() here.


问:
How to plot a heat map on spherical surface having azimuth and elevation and a corresponding value for every position
I have three values : azimuth, elevation and an error value at that position. And from that I have a number of such 3 value combinations. So three arrays of azimuths, elevations and correspondng error.

I want to plot a sphere with heat map such that the color of a region would represent the error in that region of the sphere. This would help in figuring out what part of the sphere shows the highest error.

How can I plot this? I tried to create a meshgrid

```<code>
r = 2
u, v = np.mgrid[0:2.01 * np.pi:(1/10)* np.pi, 0:1.01*np.pi:(1/10)* np.pi]
X = r * np.cos(u) * np.sin(v)
Y = r * np.sin(u) * np.sin(v)
Z = r * np.cos(v)

</code>```

This would create a mesh. How can one integrate the azimuth, elevation and error at each position into this subregion classification?

答:
You could do it this way:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [15.00, 6.0]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
r = 2
u, v = np.mgrid[0:2.01 * np.pi:(1/10)* np.pi, 0:1.01*np.pi:(1/10)* np.pi]
X = r * np.cos(u) * np.sin(v)
Y = r * np.sin(u) * np.sin(v)
Z = r * np.cos(v)
ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)
plt.show()
</code>```

Which returns:

UPDATE

Another way, if you want to introduced points like the ones you want (here, I randomize, but you'll need to format your points in the exact same way if you want to use the code unchanged), you can do this:

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

def random_point(r=2):
    ct = 2*np.random.rand() - 1
    st = np.sqrt( 1 - ct**2 )
    phi = 2* np.pi *  np.random.rand()
    x = r * st * np.cos( phi)
    y = r * st * np.sin( phi)
    z = r * ct
    return np.array( [x, y, z ] )

def near( p, pntList, d0 ):
    cnt=0
    for pj in pntList:
        dist=np.linalg.norm( p - pj )
        if dist < d0:
            cnt += 1 - dist/d0
    return cnt

Azimuth_points = np.array([ random_point(2.02) for i in range(23) ] )

fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1, projection='3d')

u = np.linspace( 0, 2 * np.pi, 120)
v = np.linspace( 0, np.pi, 60 )
r = 2
X = r * np.outer( np.cos( u ), np.sin( v ) )
Y = r * np.outer( np.sin( u ), np.sin( v ) )
Z = r * np.outer( np.ones( np.size( u ) ), np.cos( v ) )

W = X.copy()
for i in range( len(X) ):
    for j in range( len(X[0]) ):
        x = X[ i, j ]
        y = Y[ i, j ]
        z = Z[ i, j ]
        W[ i, j ] = near(np.array( [x, y, z ] ), Azimuth_points, 3)
W = W / np.amax( W )
myheatmap = W

ax.plot_surface( X, Y,  Z, cstride=1, rstride=1, facecolors=cm.jet( myheatmap ) )
plt.show()
</code>```

which gives:

Body:
I have three values : azimuth, elevation and an error value at that position. And from that I have a number of such 3 value combinations. So three arrays of azimuths, elevations and correspondng error.

I want to plot a sphere with heat map such that the color of a region would represent the error in that region of the sphere. This would help in figuring out what part of the sphere shows the highest error.

How can I plot this? I tried to create a meshgrid

r = 2
u, v = np.mgrid[0:2.01 * np.pi:(1/10)* np.pi, 0:1.01*np.pi:(1/10)* np.pi]
X = r * np.cos(u) * np.sin(v)
Y = r * np.sin(u) * np.sin(v)
Z = r * np.cos(v)

This would create a mesh. How can one integrate the azimuth, elevation and error at each position into this subregion classification?

Body:
You could do it this way:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [15.00, 6.0]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
r = 2
u, v = np.mgrid[0:2.01 * np.pi:(1/10)* np.pi, 0:1.01*np.pi:(1/10)* np.pi]
X = r * np.cos(u) * np.sin(v)
Y = r * np.sin(u) * np.sin(v)
Z = r * np.cos(v)
ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)
plt.show()

Which returns:

UPDATE

Another way, if you want to introduced points like the ones you want (here, I randomize, but you'll need to format your points in the exact same way if you want to use the code unchanged), you can do this:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

def random_point(r=2):
    ct = 2*np.random.rand() - 1
    st = np.sqrt( 1 - ct**2 )
    phi = 2* np.pi *  np.random.rand()
    x = r * st * np.cos( phi)
    y = r * st * np.sin( phi)
    z = r * ct
    return np.array( [x, y, z ] )

def near( p, pntList, d0 ):
    cnt=0
    for pj in pntList:
        dist=np.linalg.norm( p - pj )
        if dist < d0:
            cnt += 1 - dist/d0
    return cnt

Azimuth_points = np.array([ random_point(2.02) for i in range(23) ] )

fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1, projection='3d')

u = np.linspace( 0, 2 * np.pi, 120)
v = np.linspace( 0, np.pi, 60 )
r = 2
X = r * np.outer( np.cos( u ), np.sin( v ) )
Y = r * np.outer( np.sin( u ), np.sin( v ) )
Z = r * np.outer( np.ones( np.size( u ) ), np.cos( v ) )

W = X.copy()
for i in range( len(X) ):
    for j in range( len(X[0]) ):
        x = X[ i, j ]
        y = Y[ i, j ]
        z = Z[ i, j ]
        W[ i, j ] = near(np.array( [x, y, z ] ), Azimuth_points, 3)
W = W / np.amax( W )
myheatmap = W

ax.plot_surface( X, Y,  Z, cstride=1, rstride=1, facecolors=cm.jet( myheatmap ) )
plt.show()

which gives:


问:
Gemfire region synchronization
I am using gemfire and currently have a client and a server. Now, the server dinamically creates some subregions in a region and puts some objects in there. I am trying to retrieve the objects with the client but I can't see the objects or the subregions. How can I synchronize the regions? Is there anything else I can do?</p>

答:
Dynamic regions behave the same as the other regions in your cache and assumes the attributes of its parent region. You must begin with non-dynamic parent regions. Check if this region is working correctly. Synchronization should work this is most probably the problem with configurations. Use GF monitor to check your regions in distributed system.

Another solution is create remote function wich will create regions. In this case you can create portion regions and root regions. This solution is used in GemFire modules for Hibernate L2 cache.

Title: Gemfire region synchronization


问:
Is there a way to merge two tables and bringing only matching value from the second one?
I' have 2 tables on pandas (Table1,Table2) and I would like to get a third one (Table3) as in the example below (I feel like a visual example is worth 1000 words)

Could you please tell me how would the code work?

Table1

ISIN
Price

A
1

B
2

C
3

D
4

Table2

ISIN
Price2

A
5

D
6

E
7

Table3

ISIN
Price
Price2

A
1
5

B
2

C
3

D
4
6

Thanks for your help!

答:
if you are using pandas dataframes you can use the merge() function

```<code>Table3 = Table1.merge(Table2, on='ISIN', how='left')
</code>```

Body:
if you are using pandas dataframes you can use the merge() function

Table3 = Table1.merge(Table2, on='ISIN', how='left')


问:
Streaming job finish before write incremental data
I'm having a problem with a stream job with trigger.once
When I run it for the first time, it works fine, write all available data on the path and finish. But on the next day, when there is new data available in the original path, the stream doesn't see it and finish the query before write any data.
I'm using autoloader and a sqs queue.
The checkpoint path is right, and has the folders offset, commit..</p>

答:
The behavior you expect should be without trigger like below:

```<code>// Default trigger (runs micro-batch as soon as it can)
df.writeStream
  .format("console")
  .start()
</code>```

The differenct between triggers as below:

```<code>// Default trigger (runs micro-batch as soon as it can)
df.writeStream
  .format("console")
  .start()

// ProcessingTime trigger with two-seconds micro-batch interval
df.writeStream
  .format("console")
  .trigger(Trigger.ProcessingTime("2 seconds"))
  .start()

// One-time trigger
df.writeStream
  .format("console")
  .trigger(Trigger.Once())
  .start()

// Continuous trigger with one-second checkpointing interval
df.writeStream
  .format("console")
  .trigger(Trigger.Continuous("1 second"))
  .start()
</code>```

You can refer https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#triggers

Body:
The behavior you expect should be without trigger like below:

// Default trigger (runs micro-batch as soon as it can)
df.writeStream
  .format("console")
  .start()

The differenct between triggers as below:

// Default trigger (runs micro-batch as soon as it can)
df.writeStream
  .format("console")
  .start()

// ProcessingTime trigger with two-seconds micro-batch interval
df.writeStream
  .format("console")
  .trigger(Trigger.ProcessingTime("2 seconds"))
  .start()

// One-time trigger
df.writeStream
  .format("console")
  .trigger(Trigger.Once())
  .start()

// Continuous trigger with one-second checkpointing interval
df.writeStream
  .format("console")
  .trigger(Trigger.Continuous("1 second"))
  .start()

You can refer https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#triggers


问:
VUE does not load page content when compiling
I have a program made in VUE that works for me locally but stops working when compiling.

The idea is that within the initial VUE App.vue file I load content from other files, in this case the Home.vue file

App.vue

```<code><template>
  <v-app>
    <v-app-bar app color="primary" dark>
      V.4.0
      <v-spacer></v-spacer>
       2022
    </v-app-bar>

    <v-main>
      <router-view/>
    </v-main>
  </v-app>
</template>

<script>

export default {
  name: 'App',
};
</code>```

The index.js of the routes

```<code>import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/Home.vue')
    }
  },
  {
    path: '/llistat',
    name: 'Llistat',
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/Llistat_feina.vue')
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router
</script>
</code>```

the Home.vue

```<code><template>
    <v-container>
      <h1>Bienvenido</h1>
    <router-link to="/Llistat">1. Llistat</router-link><br>
  </v-container>
</template>

<script>

  export default {
    name: 'Home',

    components: {
    },
  }
</script>
</code>```

If I run it locally it works fine. Load the App.vue, find the path and insert the Home.vue

If I compile it and upload it to the server, it does not load the content of Home.vue, it only loads the code of App.vue

Any idea what might be going on? Thanks

答: You must configure your web server to serve index.html for all non-existent filenames instead of returning HTTP status code 404 - or to switch your VueRouter to hash mode instead of history. You must also properly set publicPath in vue.config.js and base in VueRouter - they must be the same and reflect the folder on the web server where your Vue application is being served from.

Body:
I have a program made in VUE that works for me locally but stops working when compiling.

The idea is that within the initial VUE App.vue file I load content from other files, in this case the Home.vue file

App.vue

<template>
  <v-app>
    <v-app-bar app color="primary" dark>
      V.4.0
      <v-spacer></v-spacer>
       2022
    </v-app-bar>

    <v-main>
      <router-view/>
    </v-main>
  </v-app>
</template>

the Home.vue

<template>
    <v-container>

Bienvenido

    <router-link to="/Llistat">1. Llistat</router-link>

  </v-container>
</template>

If I run it locally it works fine. Load the App.vue, find the path and insert the Home.vue

If I compile it and upload it to the server, it does not load the content of Home.vue, it only loads the code of App.vue

Any idea what might be going on? Thanks


问:
CocoaPods on M1 (Apple Silicon) fails with ffi wrong architecture
Running 'pod install' on a M1 MacBook failed for me due to an ffi issue, as described here.

I followed some of the workarounds (I guess I tried all of them in various order), but now I get a slightly different error:

```<code>LoadError - dlopen(/opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle, 9): no suitable image found.  Did find:
    /opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle: mach-o, but wrong architecture
    /opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle: mach-o, but wrong architecture - /opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle
</code>```

So, it seems I now have ffi, but with a wrong architecture? How can I fix this? This happens with/without running the terminal in Rosetta mode.

One of the proposed workarounds did not succeed for me, by the way. When I try:

```<code>sudo arch -x86_64 gem install ffi
</code>```

I get:

```<code>arch: posix_spawnp: gem: Bad CPU type in executable
</code>```

Not sure if this is related.

答:
I tried almost everything and this was the only solution that worked for me:

uninstalling the cocoapods package through gem

```<code>sudo gem uninstall cocoapods
</code>```

and reinstalling it with homebrew

```<code>brew install cocoapods
</code>```

fixed my problem.

The problem was I installed cocoapods through gem install instead of homebrew.

Body:
Running 'pod install' on a M1 MacBook failed for me due to an ffi issue, as described here.

I followed some of the workarounds (I guess I tried all of them in various order), but now I get a slightly different error:

LoadError - dlopen(/opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle, 9): no suitable image found.  Did find:
    /opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle: mach-o, but wrong architecture
    /opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle: mach-o, but wrong architecture - /opt/homebrew/lib/ruby/gems/3.0.0/gems/ffi-1.15.0/lib/ffi_c.bundle

So, it seems I now have ffi, but with a wrong architecture? How can I fix this? This happens with/without running the terminal in Rosetta mode.

One of the proposed workarounds did not succeed for me, by the way. When I try:

sudo arch -x86_64 gem install ffi

I get:

arch: posix_spawnp: gem: Bad CPU type in executable

Not sure if this is related.

Body:
I tried almost everything and this was the only solution that worked for me:

uninstalling the cocoapods package through gem

sudo gem uninstall cocoapods

and reinstalling it with homebrew

brew install cocoapods

fixed my problem.

The problem was I installed cocoapods through gem install instead of homebrew.


问:
Docker repository server gave HTTP response to HTTPS client
I use Docker toolbox for windows and I`m trying run private docker registry refering this documentation https://docs.docker.com/registry/deploying/

But it`s not working for me.

Error after this:

```<code>$ docker pull 192.168.99.100:5000/my-ubuntu
</code>```

Error

```<code>$ docker pull 192.168.99.100:5000/image
Using default tag: latest
Error response from daemon: Get https://192.168.99.100:5000/v2/: http: server gave HTTP response to HTTPS client
</code>```

I`m thinking that error is something in my docker client.

For information this is my docker info

```<code>Containers: 6
 Running: 4
 Paused: 0
 Stopped: 2
Images: 19
Server Version: 17.06.0-ce
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 144
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: cfb82a876ecc11b5ca0977d1733adbe58599088a
runc version: 2d41c047c83e09a6d61d464906feb2a2f3c52aa4
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.4.74-boot2docker
Operating System: Boot2Docker 17.06.0-ce (TCL 7.2); HEAD : 0672754 - Thu Jun 29 00:06:31 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 995.8MiB
Name: default
ID: ZMCX:NXC7:3BSV:ZNWV:MDZO:FW26:6MX5:UWI6:NVRL:XP56:AKGC:Z3TW
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 47
 Goroutines: 56
 System Time: 2018-04-05T13:43:42.856720067Z
 EventsListeners: 0
Username: kacalek
Registry: https://index.docker.io/v1/
Labels:
 provider=virtualbox
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false
</code>```

If I try this on mac everything is working perfectly.

Do you know how this error to solve?

Thank you so much for every answers!

答:
If buildkit is enabled (in newer versions it seems to be enabled by default) and adding the insecurite-registries didn't fix it, you may need to either disable buildkit, or add the http:// to the hostnames in insecure-registries.

Disable Buildkit via environment variable:

```<code>DOCKER_BUILDKIT=0 docker build -t image_name .
</code>```

Disable via docker daemon configuration file:

On Docker Desktop go to Settings > Docker Engine

** Be very careful of typos and missing commas as breaking this file will prevent docker desktop starting up.

```<code>{
  ...
  "features": {
    "buildkit": false << SET THIS TO FALSE
  },
  "insecure-registries": [
    "hostname:18443",
    "hostname:8083"
  ],
  ...
}
</code>```

Configure URL as HTTP:

```<code>{
  ...
  "features": {
    "buildkit": true
  },
  "insecure-registries": [
    "http://hostname:18443",
    "http://hostname:8083"
  ],
  ...
}
</code>```

Documentation of the known issue:

https://github.com/docker/docker.github.io/blob/62adddbb6b1f8d861c72f6ade2c50977fd57f481/registry/insecure.md#known-issue-on-buildkit

Body:
I use Docker toolbox for windows and I`m trying run private docker registry refering this documentation https://docs.docker.com/registry/deploying/

But it`s not working for me.

Error after this:

$ docker pull 192.168.99.100:5000/my-ubuntu

Error

$ docker pull 192.168.99.100:5000/image
Using default tag: latest
Error response from daemon: Get https://192.168.99.100:5000/v2/: http: server gave HTTP response to HTTPS client

I`m thinking that error is something in my docker client.

For information this is my docker info

Containers: 6
 Running: 4
 Paused: 0
 Stopped: 2
Images: 19
Server Version: 17.06.0-ce
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 144
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: cfb82a876ecc11b5ca0977d1733adbe58599088a
runc version: 2d41c047c83e09a6d61d464906feb2a2f3c52aa4
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.4.74-boot2docker
Operating System: Boot2Docker 17.06.0-ce (TCL 7.2); HEAD : 0672754 - Thu Jun 29 00:06:31 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 995.8MiB
Name: default
ID: ZMCX:NXC7:3BSV:ZNWV:MDZO:FW26:6MX5:UWI6:NVRL:XP56:AKGC:Z3TW
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 47
 Goroutines: 56
 System Time: 2018-04-05T13:43:42.856720067Z
 EventsListeners: 0
Username: kacalek
Registry: https://index.docker.io/v1/
Labels:
 provider=virtualbox
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

If I try this on mac everything is working perfectly.

Do you know how this error to solve?

Thank you so much for every answers!

Body:
If buildkit is enabled (in newer versions it seems to be enabled by default) and adding the insecurite-registries didn't fix it, you may need to either disable buildkit, or add the http:// to the hostnames in insecure-registries.

Disable Buildkit via environment variable:

DOCKER_BUILDKIT=0 docker build -t image_name .

Disable via docker daemon configuration file:

On Docker Desktop go to Settings > Docker Engine

** Be very careful of typos and missing commas as breaking this file will prevent docker desktop starting up.

{
  ...
  "features": {
    "buildkit": false << SET THIS TO FALSE
  },
  "insecure-registries": [
    "hostname:18443",
    "hostname:8083"
  ],
  ...
}

Configure URL as HTTP:

{
  ...
  "features": {
    "buildkit": true
  },
  "insecure-registries": [
    "http://hostname:18443",
    "http://hostname:8083"
  ],
  ...
}

Documentation of the known issue:

https://github.com/docker/docker.github.io/blob/62adddbb6b1f8d861c72f6ade2c50977fd57f481/registry/insecure.md#known-issue-on-buildkit


问:
Set navbar fixed on scroll with transition in react.js
I set my navbar fixed on scroll but I want it to reappear with transition instead of bumping right into the screen. I have tried many solutions but the transition effect won't kick in.

I have the following react code:

```<code>const [sticky, setSticky] = useState('');
React.useEffect(() => {
    window.addEventListener('scroll', stickNavbar);
    return () => window.removeEventListener('scroll', stickNavbar);
  }, []);
 const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      windowHeight > 150 ? setSticky({ position: "fixed", top: "0"}) : setSticky({ position: "relative"});
    }
  };

return(
 <Navbar>
     <Container style={sticky} fluid className="menu">

    </Container>
 </Navbar>
)
</code>```

CSS

```<code>.menu {
   max-width: 100%;
   height: 7rem;
   border-bottom: 2px solid rgb(228, 228, 228);
   background-color:#f8f9fa;
   transition: top 1s;
}
</code>```

答:
The postition property has to change in order for the effect to kick in. Therefore I added negative values for the top attribute and the same positive amount for margin. To cancel the effect for backward transition I set the css value to 0s.</p>
```<code> const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      windowHeight > 150 ? setSticky({ position: "fixed", top: "0", marginTop:"0",
 transition: "top 1s"}) : setSticky({});
    }
  };

.menu {
   max-width: 100%;
   height: 7rem;
   border-bottom: 2px solid rgb(228, 228, 228);
   background-color:#f8f9fa;
   position: relative;
   top:-30px;
   margin-top: 30px;
   transition: top 0s;
   z-index: 99999;
}
</code>```

Body:
I set my navbar fixed on scroll but I want it to reappear with transition instead of bumping right into the screen. I have tried many solutions but the transition effect won't kick in.

I have the following react code:

const [sticky, setSticky] = useState('');
React.useEffect(() => {
    window.addEventListener('scroll', stickNavbar);
    return () => window.removeEventListener('scroll', stickNavbar);
  }, []);
 const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      windowHeight > 150 ? setSticky({ position: "fixed", top: "0"}) : setSticky({ position: "relative"});
    }
  };

return(
 <Navbar>
     <Container style={sticky} fluid className="menu">

    </Container>
 </Navbar>
)

CSS

.menu {
   max-width: 100%;
   height: 7rem;
   border-bottom: 2px solid rgb(228, 228, 228);
   background-color:#f8f9fa;
   transition: top 1s;
}

Body:
The postition property has to change in order for the effect to kick in. Therefore I added negative values for the top attribute and the same positive amount for margin. To cancel the effect for backward transition I set the css value to 0s.

 const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      windowHeight > 150 ? setSticky({ position: "fixed", top: "0", marginTop:"0",
 transition: "top 1s"}) : setSticky({});
    }
  };

.menu {
   max-width: 100%;
   height: 7rem;
   border-bottom: 2px solid rgb(228, 228, 228);
   background-color:#f8f9fa;
   position: relative;
   top:-30px;
   margin-top: 30px;
   transition: top 0s;
   z-index: 99999;
}


问:
How to print call stack in Swift?
In Objective-C, you can print the call stack by doing the following:

```<code>NSLog(@"%@", [NSThread callStackSymbols]);
</code>```

How do you do this in Swift without using Foundation class?

答:
```<code> print(Thread.callStackSymbols.joined(separator: "\n"))
</code>```

With this code, one can see the calls in different lines each.

```<code> 1   MyApp                               0x0000000100720780 $s9MyAppModule....
 2   CoreFoundation                      0x0000000181f04c4c EA9C1DF2-94C7-379B-BF8D-970335B1552F + 166988
 3   CoreFoundation                      0x0000000181f99554 EA9C1DF2-94C7-379B-BF8D-970335B1552F + 775508
 4   CoreFoundation                      0x0000000181f6eb34 EA9C1DF2-94C7-379B-BF8D-970335B1552F + 600884
 5   CoreFoundation                      0x0000000181f19754 _CFXNotificationPost + 696
 6   Foundation                          0x0000000183634138 86D8A58D-B71F-34C6-83E0-014B2B835F1D + 106808
</code>```

Title: How to print call stack in Swift?

Body:
In Objective-C, you can print the call stack by doing the following:

NSLog(@"%@", [NSThread callStackSymbols]);

How do you do this in Swift without using Foundation class?

Body:
 print(Thread.callStackSymbols.joined(separator: "\n"))

With this code, one can see the calls in different lines each.

 1   MyApp                               0x0000000100720780 $s9MyAppModule....
 2   CoreFoundation                      0x0000000181f04c4c EA9C1DF2-94C7-379B-BF8D-970335B1552F + 166988
 3   CoreFoundation                      0x0000000181f99554 EA9C1DF2-94C7-379B-BF8D-970335B1552F + 775508
 4   CoreFoundation                      0x0000000181f6eb34 EA9C1DF2-94C7-379B-BF8D-970335B1552F + 600884
 5   CoreFoundation                      0x0000000181f19754 _CFXNotificationPost + 696
 6   Foundation                          0x0000000183634138 86D8A58D-B71F-34C6-83E0-014B2B835F1D + 106808


问:
Is it possible to combine streams?
I have this code, the task of which is to determine the words of the longest, I made through several streams. How to combine them?</p>
```<code>List<String> maxLengthWords = ForkJoinTask.invokeAll(createSubtasks()).stream()
        .flatMap(maxLengthWord -> maxLengthWord.join().stream())
        .collect(Collectors.toList());

int longest = maxLengthWords.stream()
        .mapToInt(String::length)
        .max()
        .orElse(-1);

return maxLengthWords.stream()
        .filter(s -> s.length() == longest)
        .collect(Collectors.toList());
</code>```

答:
You can take all collection and connect them with Stream.of(...) fucntion.

I couldn't understand what do you want to combime from your code but you can combine streams in the following way:

```<code>Stream.of(collectionA.stream(),collectionB.stream())
</code>```

Take a look on:
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#of-T...-

Title: Is it possible to combine streams?

Body:
I have this code, the task of which is to determine the words of the longest, I made through several streams. How to combine them?

List<String> maxLengthWords = ForkJoinTask.invokeAll(createSubtasks()).stream()
        .flatMap(maxLengthWord -> maxLengthWord.join().stream())
        .collect(Collectors.toList());

int longest = maxLengthWords.stream()
        .mapToInt(String::length)
        .max()
        .orElse(-1);

return maxLengthWords.stream()
        .filter(s -> s.length() == longest)
        .collect(Collectors.toList());

Body:
You can take all collection and connect them with Stream.of(...) fucntion.

I couldn't understand what do you want to combime from your code but you can combine streams in the following way:

Stream.of(collectionA.stream(),collectionB.stream())

Take a look on:
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#of-T...-