问:
Why does the variable select strategy of CPLEX influence the user branch decisions? (Python)
I followed the example to branch using make_branch() in the control(branch) callback of the MIP. But I noticed that the solving processes differ surprisingly under different settings of the variable select strategy. How was it possible since I replace all the CPLEX's decisions with my decisions?

答:
CPLEX cannot tell whether you are going to query its branching decisions from the callback or not. So before invoking the callback, CPLEX computes what variables it would branch on, so that this information can be reported to the callback.

Even if you never query this information, it is still computed and computing that information may change the rest of the execution, thus resulting in different search trees.


来源: stackexchange

问:
How to change the app bar title in flutter
```<code>**change the appbar title dynamically**
</code>```

Getting appbar title from the database and then I have to set to appbar. I am new to flutter tried setState as well.

I have tried setState() as but still not working.
how can i change the appbar text based on server response as well as database value

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:parking_app/data/database_helper.dart';
import'package:parking_app/models/user.dart';

class HomeScreen extends StatefulWidget {   @override   State<StatefulWidget> createState() {
    return new HomeScreenState();   } }

class HomeScreenState extends State<HomeScreen> {   @override   Widget build(BuildContext context) {
    var db = new DatabaseHelper();
    Future<User> user = db.getUser();
    String appBarTitle = "eClerx Parking";
    var appBarTitleText = new Text(appBarTitle);
</code>```

```<code>if (user != null) {
  user.then((val) {
    if (val == null) {
      return;
    }
    print(TAG+ "  user data : " + val.emailId);
    setState(() {
      build(context);
      appBarTitle = val.emailId;
    });
  });
}
</code>```

```<code>return new MaterialApp(
  home: new Scaffold(
    appBar: new AppBar(
      title: appBarTitleText,
      actions: <Widget>[
        // action button
        new IconButton(
          icon: new Icon(Icons.settings_power),
          onPressed: () {
            _logout();
          },
        ),
        // action button
      ],
    ),
    body: new Padding(
      padding: const EdgeInsets.all(16.0),
      child: new ChoiceCard(choice: choices[0]),
    ),
  ),
);   } }
</code>```

答:
create global variable name it appBar Title inside statefulwidget state class

```<code>var appBarTitle ="some text";
</code>```

and assign appBar title to it

then change its value with setState method

ContentLicense: CC BY-SA 4.0

Body:
**change the appbar title dynamically**

Getting appbar title from the database and then I have to set to appbar. I am new to flutter tried setState as well.

I have tried setState() as but still not working.
how can i change the appbar text based on server response as well as database value

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:parking_app/data/database_helper.dart';
import'package:parking_app/models/user.dart';

class HomeScreen extends StatefulWidget {   @override   State<StatefulWidget> createState() {
    return new HomeScreenState();   } }

class HomeScreenState extends State<HomeScreen> {   @override   Widget build(BuildContext context) {
    var db = new DatabaseHelper();
    Future<User> user = db.getUser();
    String appBarTitle = "eClerx Parking";
    var appBarTitleText = new Text(appBarTitle);

if (user != null) {
  user.then((val) {
    if (val == null) {
      return;
    }
    print(TAG+ "  user data : " + val.emailId);
    setState(() {
      build(context);
      appBarTitle = val.emailId;
    });
  });
}

return new MaterialApp(
  home: new Scaffold(
    appBar: new AppBar(
      title: appBarTitleText,
      actions: <Widget>[
        // action button
        new IconButton(
          icon: new Icon(Icons.settings_power),
          onPressed: () {
            _logout();
          },
        ),
        // action button
      ],
    ),
    body: new Padding(
      padding: const EdgeInsets.all(16.0),
      child: new ChoiceCard(choice: choices[0]),
    ),
  ),
);   } }

Body:
create global variable name it appBar Title inside statefulwidget state class

var appBarTitle ="some text";

and assign appBar title to it

then change its value with setState method


问:
Store representations in SQL rather than whole strings?
I want to mark my users with one out of four static strings: indestructible, unstoppable, superefficient and megafantastic.

Would it be faster and more efficient to store a one char representation of the string rather than the whole string? Sort of like a key<->value mapping. The DB would only need to match one letter instead of a whole string when I do a search.

In the DB these words would only be represented as i,u,s and m. On the users profile I print indesctuctible if I get an i, unstoppable if I get a u etc.

Do I actually speed up anything by doing like this or is it just unnecessary work?

What if I have 10 more of these representations?

答:
If you're looking to maximize your performance and don't care about normalizing this data (which is almost always the best option), you could store those 4 attributes as bits:

```<code>CREATE TABLE <name> (
    <other fields>
    isIndestructible bit,
    isUnstoppable bit
    isSuperefficient bit
    isMegafantastic bit
)
</code>```

It's bad practice in that you'll be SOL if you decide to add "isMagnificent" or change "isIndestructable" to "isResilient", but if you've really just got 4 attributes you're tracking, 4 bits are hard to beat.

ContentLicense: CC BY-SA 3.0

Body:
If you're looking to maximize your performance and don't care about normalizing this data (which is almost always the best option), you could store those 4 attributes as bits:

CREATE TABLE <name> (
    <other fields>
    isIndestructible bit,
    isUnstoppable bit
    isSuperefficient bit
    isMegafantastic bit
)

It's bad practice in that you'll be SOL if you decide to add "isMagnificent" or change "isIndestructable" to "isResilient", but if you've really just got 4 attributes you're tracking, 4 bits are hard to beat.


问:
Build loop to use increasing part of dataframe in R as input to function
I'm using the first principal component from a PCA analysis as an explanatory variable in a forecasting model that forecasts recursively using Kalman filtering. In other words, at each point in time, the model updates and produces a new forecast based on the new observation included into the model. Since PCA uses data from all observations included in the model for its calculations, I need to run also the PCAs recursively, using only the observations prior to the point in time that I am forecasting (otherwise, the PCA-result could reveal information about the future, and help the model produce a more accurate answer than it would have otherwise). I think a loop might be the solution, but I am struggling with how to formulate the code.

As a more specific example, consider if I have the following data.frame

```<code>data <- as.data.frame(rbind(c(6,15,23),c(9,11,22), c(7,13,23), c(6,12,25),c(7,13,23)))
names(data) <- c("V1","V2","V3")

> data
  V1 V2 V3
1  6 15 23
2  9 11 22
3  7 13 23
4  6 12 25
5  7 13 23
</code>```

At each observation date, I wish to run a PCA (function prcomp() from the stats-package) for all observations up to, and including, that observation. So I want to first run PCA for the two first observation

```<code>pca2 <- prcomp(data[1:2,], scale = TRUE)
</code>```

next I want to run PCA with the first, second and third observation as input

```<code>pca3 <- prcomp(data[1:3,], scale = TRUE)
</code>```

next I want to run PCA with the first, second, third and fourth observation as input

```<code>pca4 <- prcomp(data[1:4,], scale = TRUE)
</code>```

and so on, until the last run of the PCA, which includes all observations in the dataframe. For each of these "runs" of the PCA, I wish to extract the last value (though for pca2, I use both the first and second value) of the first principal component (PC1), and merge these into a final dataframe, where each monthly observation is the last value of the first principal component of PCA results for each of the runs.

The principal component outputs are:

```<code>> my_pca2 <- as.data.frame(pca2$x)
> my_pca2
        PC1           PC2
1 -1.224745 -5.551115e-17
2  1.224745  5.551115e-17

> my_pca3 <- as.data.frame(pca3$x)
> my_pca3
         PC1        PC2          PC3
1 -1.4172321 -0.2944338 6.106227e-16
2  1.8732448 -0.1215046 3.330669e-16
3 -0.4560127  0.4159384 4.163336e-16

> my_pca4 <- as.data.frame(pca4$x)
> my_pca4
          PC1         PC2          PC3
1 -1.03030993 -1.10154914  0.015457199
2  2.00769890  0.07649216  0.011670433
3  0.03301806 -0.24226508 -0.033461874
4 -1.01040702  1.26732205  0.006334242
</code>```

So I want my final output to be a dataframe to look like

```<code>>final.output
         PC1
1  -1.224745
2   1.224745
3 -0.4560127
4 -1.01040702
</code>```

Comment: yes, it looks a bit weird with the two first values, but please don't pay too much attention to that. My point is that I wish to build a dataframe that consists of the last calculated value for the first principal component for each of the PCA runs.

I am thinking that a for.loop might be the best solution here, but I have not been successful in finding any threads that might guide me closer to a coding solution. How can I make the loop use an increasing amount of the dataframe in the calculations? Does anyone have any suggestions/tips/links? Any help on this is much appreciated!

答:
I had a very similar approach.</p>

```<code>PCA <- vector("list", length=nrow(data)-1)
for(i in 1:(nrow(data)-1)) {
  if(i==1) j <- 1:2 else j<-i+1
  PCA[[i]] <- as.data.frame(prcomp(data[1:(1+i),], scale = TRUE)$x)[j, 1]
}

unlist(PCA)
</code>```

Body:
I'm using the first principal component from a PCA analysis as an explanatory variable in a forecasting model that forecasts recursively using Kalman filtering. In other words, at each point in time, the model updates and produces a new forecast based on the new observation included into the model. Since PCA uses data from all observations included in the model for its calculations, I need to run also the PCAs recursively, using only the observations prior to the point in time that I am forecasting (otherwise, the PCA-result could reveal information about the future, and help the model produce a more accurate answer than it would have otherwise). I think a loop might be the solution, but I am struggling with how to formulate the code.

As a more specific example, consider if I have the following data.frame

data <- as.data.frame(rbind(c(6,15,23),c(9,11,22), c(7,13,23), c(6,12,25),c(7,13,23)))
names(data) <- c("V1","V2","V3")

> data
  V1 V2 V3
1  6 15 23
2  9 11 22
3  7 13 23
4  6 12 25
5  7 13 23

At each observation date, I wish to run a PCA (function prcomp() from the stats-package) for all observations up to, and including, that observation. So I want to first run PCA for the two first observation

pca2 <- prcomp(data[1:2,], scale = TRUE)

next I want to run PCA with the first, second and third observation as input

pca3 <- prcomp(data[1:3,], scale = TRUE)

next I want to run PCA with the first, second, third and fourth observation as input

pca4 <- prcomp(data[1:4,], scale = TRUE)

and so on, until the last run of the PCA, which includes all observations in the dataframe. For each of these "runs" of the PCA, I wish to extract the last value (though for pca2, I use both the first and second value) of the first principal component (PC1), and merge these into a final dataframe, where each monthly observation is the last value of the first principal component of PCA results for each of the runs.

The principal component outputs are:

> my_pca2 <- as.data.frame(pca2$x)
> my_pca2
        PC1           PC2
1 -1.224745 -5.551115e-17
2  1.224745  5.551115e-17

> my_pca3 <- as.data.frame(pca3$x)
> my_pca3
         PC1        PC2          PC3
1 -1.4172321 -0.2944338 6.106227e-16
2  1.8732448 -0.1215046 3.330669e-16
3 -0.4560127  0.4159384 4.163336e-16

> my_pca4 <- as.data.frame(pca4$x)
> my_pca4
          PC1         PC2          PC3
1 -1.03030993 -1.10154914  0.015457199
2  2.00769890  0.07649216  0.011670433
3  0.03301806 -0.24226508 -0.033461874
4 -1.01040702  1.26732205  0.006334242

So I want my final output to be a dataframe to look like

>final.output
         PC1
1  -1.224745
2   1.224745
3 -0.4560127
4 -1.01040702

Comment: yes, it looks a bit weird with the two first values, but please don't pay too much attention to that. My point is that I wish to build a dataframe that consists of the last calculated value for the first principal component for each of the PCA runs.

I am thinking that a for.loop might be the best solution here, but I have not been successful in finding any threads that might guide me closer to a coding solution. How can I make the loop use an increasing amount of the dataframe in the calculations? Does anyone have any suggestions/tips/links? Any help on this is much appreciated!

Body:
I had a very similar approach.

PCA <- vector("list", length=nrow(data)-1)
for(i in 1:(nrow(data)-1)) {
  if(i==1) j <- 1:2 else j<-i+1
  PCA[[i]] <- as.data.frame(prcomp(data[1:(1+i),], scale = TRUE)$x)[j, 1]
}

unlist(PCA)


问:
Redis, Jedis connection pool optimizeand monitoring tools
I am new to Redis, Jedis. Today, I saw an error in my log

```<code>Caused by: redis.clients.jedis.exceptions.JedisExhaustedPoolException: redis.clients.jedis.exceptions.JedisExhaustedPoolException: Could not get a resource since the pool is exhausted
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_191]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_191]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_191]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_191]
        at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593) ~[?:1.8.0_191]
        at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677) ~[?:1.8.0_191]
        at java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:735) ~[?:1.8.0_191]
        at java.util.stream.ForEachOps$ForEachOp.evaluateParallel(ForEachOps.java:160) ~[?:1.8.0_191]
        at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateParallel(ForEachOps.java:174) ~[?:1.8.0_191]
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233) ~[?:1.8.0_191]
        at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) ~[?:1.8.0_191]
        at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:583) ~[?:1.8.0_191]
        at com.nokia.snmpapp.VariableDataUtils.processSnmpDataByOP(VariableDataUtils.java:372) ~[snmpapp.jar:?]
       at com.nokia.snmpapp.consumerservice.DocsisQos3MibData.processDocsQos3ParamSetTableObjectEvent(DocsisQos3MibData.java:172) ~[snmpapp.jar:?]
        at com.nokia.snmpapp.KafkaConsumer.onSnmpappDocsQos3ParamSetTableObjectEvent(KafkaConsumer.java:315) ~[snmpapp.jar:?]
        ... 16 more

Caused by: redis.clients.jedis.exceptions.JedisExhaustedPoolException: Could not get a resource since the pool is exhausted
            at redis.clients.jedis.util.Pool.getResource(Pool.java:53) ~[snmpapp.jar:?]
            at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234) ~[snmpapp.jar:?]
            at com.nokia.snmpapp.RedisUtils.add2list(RedisUtils.java:27) ~[snmpapp.jar:?]
            at com.nokia.snmpapp.VariableDataUtils.lambda$processSnmpDataByOP$5(VariableDataUtils.java:379) ~[snmpapp.jar:?]
            at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) ~[?:1.8.0_191]
            at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[?:1.8.0_191]
            at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[?:1.8.0_191]
            at java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:291) ~[?:1.8.0_191]
            at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinPool$WorkQueue.execLocalTasks(ForkJoinPool.java:1040) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1058) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[?:1.8.0_191]

Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
           at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:439) ~[snmpapp.jar:?]
           at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:349) ~[snmpapp.jar:?]
           at redis.clients.jedis.util.Pool.getResource(Pool.java:50) ~[snmpapp.jar:?]
           at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234) ~[snmpapp.jar:?]
           at com.nokia.snmpapp.RedisUtils.add2list(RedisUtils.java:27) ~[snmpapp.jar:?]
           at com.nokia.snmpapp.VariableDataUtils.lambda$processSnmpDataByOP$5(VariableDataUtils.java:379) ~[snmpapp.jar:?]
           at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) ~[?:1.8.0_191]
           at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[?:1.8.0_191]
           at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[?:1.8.0_191]
           at java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:291) ~[?:1.8.0_191]
           at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinPool$WorkQueue.execLocalTasks(ForkJoinPool.java:1040) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1058) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[?:1.8.0_191]
</code>```

My current configuration is

```<code>  maxTotal: 10
  maxIdle: 5
  minIdle: 1
  maxWaitMillis: 2000
</code>```

I know I can increase my connection pool size to resolve the error message. However, I would like to understand the resource usage a bit more before determining a good number for my env. I have been google about this, but I am unable to find much talking about the monitoring tool or how to monitor the performance and pool usage. Does that mean there is no tools to monitor?  If there is no way to monitor connection pool usage, what can I do to get a better idea on what to optimize on Redis connection?

Thanks in advance

答:
Monitoring Jedis Pool with JMX MBeans

Jedis Pool is based on Apache Generic-Pool API, so you can use JMX to monitor the state of your Connection pool.

For example, start your application with JMX enabled:

```<code>-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
</code>```

Then connect with JConsole or any other JMX compliant tool:

Connect to your application/process

Go to MBeans

Go to the org.apache.commons.pool2.GenericObjectPool.pool MBeans

You will be able to monitor what is happening to your application/JedisPool.

You have many monitoring tools that are compliant with JMX allowing you to put alert based on a threshold

Sizing and Configuration

The configuration of your pool is really application-specific, and to configure the maxTotal property, that is the maximum number of connection you have to look at:

how many conccurent connection is needed by your services

how long it take each call to execute the commands you are sending

And you need to be sure you do not overload your system (client-side and server-side.)

JedisPool: Be sure you release the connection ;)

Also, it is not about monitoring but more about best-practice:

does your application release the connection to the pool after each use?

```<code>/// Jedis implements Closeable. Hence, the jedis instance will be auto-closed after the last statement.
try (Jedis jedis = pool.getResource()) {

   // use your jedis
  jedis.set("foo", "bar");

} // the resource will be released back to the pool

</code>```

If not using the try with the resource you have to close the connection (to put it back to the pool)

```<code>Jedis jedis = null;
try {
  jedis = pool.getResource();
  // work with Redis
  jedis.set("foo", "bar");
} finally {
  // you must close the connection to put it back to the pool
  if (jedis != null) {
    jedis.close();
  }
}

</code>```

Also when you close your application:

```<code> pool.close()
</code>```

Body:
I am new to Redis, Jedis. Today, I saw an error in my log

Caused by: redis.clients.jedis.exceptions.JedisExhaustedPoolException: redis.clients.jedis.exceptions.JedisExhaustedPoolException: Could not get a resource since the pool is exhausted
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_191]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_191]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_191]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_191]
        at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593) ~[?:1.8.0_191]
        at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677) ~[?:1.8.0_191]
        at java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:735) ~[?:1.8.0_191]
        at java.util.stream.ForEachOps$ForEachOp.evaluateParallel(ForEachOps.java:160) ~[?:1.8.0_191]
        at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateParallel(ForEachOps.java:174) ~[?:1.8.0_191]
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233) ~[?:1.8.0_191]
        at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) ~[?:1.8.0_191]
        at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:583) ~[?:1.8.0_191]
        at com.nokia.snmpapp.VariableDataUtils.processSnmpDataByOP(VariableDataUtils.java:372) ~[snmpapp.jar:?]
       at com.nokia.snmpapp.consumerservice.DocsisQos3MibData.processDocsQos3ParamSetTableObjectEvent(DocsisQos3MibData.java:172) ~[snmpapp.jar:?]
        at com.nokia.snmpapp.KafkaConsumer.onSnmpappDocsQos3ParamSetTableObjectEvent(KafkaConsumer.java:315) ~[snmpapp.jar:?]
        ... 16 more

Caused by: redis.clients.jedis.exceptions.JedisExhaustedPoolException: Could not get a resource since the pool is exhausted
            at redis.clients.jedis.util.Pool.getResource(Pool.java:53) ~[snmpapp.jar:?]
            at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234) ~[snmpapp.jar:?]
            at com.nokia.snmpapp.RedisUtils.add2list(RedisUtils.java:27) ~[snmpapp.jar:?]
            at com.nokia.snmpapp.VariableDataUtils.lambda$processSnmpDataByOP$5(VariableDataUtils.java:379) ~[snmpapp.jar:?]
            at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) ~[?:1.8.0_191]
            at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[?:1.8.0_191]
            at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[?:1.8.0_191]
            at java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:291) ~[?:1.8.0_191]
            at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinPool$WorkQueue.execLocalTasks(ForkJoinPool.java:1040) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1058) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[?:1.8.0_191]
            at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[?:1.8.0_191]

Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
           at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:439) ~[snmpapp.jar:?]
           at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:349) ~[snmpapp.jar:?]
           at redis.clients.jedis.util.Pool.getResource(Pool.java:50) ~[snmpapp.jar:?]
           at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234) ~[snmpapp.jar:?]
           at com.nokia.snmpapp.RedisUtils.add2list(RedisUtils.java:27) ~[snmpapp.jar:?]
           at com.nokia.snmpapp.VariableDataUtils.lambda$processSnmpDataByOP$5(VariableDataUtils.java:379) ~[snmpapp.jar:?]
           at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) ~[?:1.8.0_191]
           at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[?:1.8.0_191]
           at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[?:1.8.0_191]
           at java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:291) ~[?:1.8.0_191]
           at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinPool$WorkQueue.execLocalTasks(ForkJoinPool.java:1040) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1058) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) ~[?:1.8.0_191]
           at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) ~[?:1.8.0_191]

My current configuration is

  maxTotal: 10
  maxIdle: 5
  minIdle: 1
  maxWaitMillis: 2000

I know I can increase my connection pool size to resolve the error message. However, I would like to understand the resource usage a bit more before determining a good number for my env. I have been google about this, but I am unable to find much talking about the monitoring tool or how to monitor the performance and pool usage. Does that mean there is no tools to monitor?  If there is no way to monitor connection pool usage, what can I do to get a better idea on what to optimize on Redis connection?

Thanks in advance

Body:
Monitoring Jedis Pool with JMX MBeans

Jedis Pool is based on Apache Generic-Pool API, so you can use JMX to monitor the state of your Connection pool.

For example, start your application with JMX enabled:

-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

Then connect with JConsole or any other JMX compliant tool:

Connect to your application/process

Go to MBeans

Go to the org.apache.commons.pool2.GenericObjectPool.pool MBeans

You will be able to monitor what is happening to your application/JedisPool.

You have many monitoring tools that are compliant with JMX allowing you to put alert based on a threshold

Sizing and Configuration

The configuration of your pool is really application-specific, and to configure the maxTotal property, that is the maximum number of connection you have to look at:

how many conccurent connection is needed by your services

how long it take each call to execute the commands you are sending

And you need to be sure you do not overload your system (client-side and server-side.)

JedisPool: Be sure you release the connection ;)

Also, it is not about monitoring but more about best-practice:

does your application release the connection to the pool after each use?

/// Jedis implements Closeable. Hence, the jedis instance will be auto-closed after the last statement.
try (Jedis jedis = pool.getResource()) {

   // use your jedis
  jedis.set("foo", "bar");

} // the resource will be released back to the pool

If not using the try with the resource you have to close the connection (to put it back to the pool)

Jedis jedis = null;
try {
  jedis = pool.getResource();
  // work with Redis
  jedis.set("foo", "bar");
} finally {
  // you must close the connection to put it back to the pool
  if (jedis != null) {
    jedis.close();
  }
}

Also when you close your application:

 pool.close()


问:
Strip a comma and whitespace thats after it from a string
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "

I'm looking to strip them from the string to return a more readable address format

Example Data is JSON :

```<code>{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
    "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}
</code>```

As you can see there's a lot of commas and spaces directly after with no data in.

How do I go about doing this? My current code is :

```<code>$.ajax(
            {
                type: 'POST',
                url: '/address',
                dataType: 'json',
                data: { _token: token, postcode: postcode},
                success: function( data )
                {
                    $('.addresses').html('');

                    $.each(data, function(k, v)
                    {
                        address = v.replace(/\s+/g, ' ');

                        $('.addresses').append('<option value="">'+ address +'</option>');
                    })
                }
            }
        )
</code>```

答:
You can use a regular expression to clean them up.

var str = "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
var cleaned = str.replace(/,(\s,)+/, ',')
console.log(cleaned)```

Body:
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "

I'm looking to strip them from the string to return a more readable address format

Example Data is JSON :

{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
    "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}

As you can see there's a lot of commas and spaces directly after with no data in.

How do I go about doing this? My current code is :

$.ajax(
            {
                type: 'POST',
                url: '/address',
                dataType: 'json',
                data: { _token: token, postcode: postcode},
                success: function( data )
                {
                    $('.addresses').html('');

                    $.each(data, function(k, v)
                    {
                        address = v.replace(/\s+/g, ' ');

                        $('.addresses').append('<option value="">'+ address +'</option>');
                    })
                }
            }
        )


问:
How to collect data and headers for non blank cells in a row in Sheets
I cannot find a solution to my problem:

I have a sheet with ~290 rows and ~80 columns. The first row and column are fixed/header.

I would like to collect non-blank values and their header into column B.

I've tried to search for solutions, but I'm not as good at excel, so I cannot wrap my head around most of the advice that I've found.

答:
use:

```<code>=ARRAYFORMULA(REGEXREPLACE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(
 IF(C2:G<>"", C1:G1&" "&C2:G&",", )),,99^99))), ",$", ))
</code>```

Body:
use:

=ARRAYFORMULA(REGEXREPLACE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(
 IF(C2:G<>"", C1:G1&" "&C2:G&",", )),,99^99))), ",$", ))


问:
Locking a table within a transaction
I would like to be able to lock an entire table to prevent any INSERTs or UPDATEs in it between the "beginTransaction" and the ending "commit" or "rollback".

I know that beginning a transaction results in an implicit UNLOCK TABLES and that a LOCK table results in a implicit COMMIT... so is there any way to do what I want?

答:
Why? Perhaps you have missed the point of transactions.

If you use repeatable-read transaction isolation, inserts, updates etc, can happen during your transaction, BUT YOU WILL NOT SEE THEM. So as far as your process is concerned, the table is locked for inserts/updates. Except they are still happening, they're still durable to disc, and other processes can continue.

After you do your first "select", a snapshot is created, and you are effectively reading that snapshot, not the latest version. If this is what you want, repeatable-read works well for you.

Title: Locking a table within a transaction


问:
merging palettes with colorRampPalette and plotting with leaflet
I'm trying to merge two colorRampPalette schemes to use in leaflet and have been following this nice  example. That example works fine but I can't seem to get it to work for my work, reproducible example below. I'm using RdYlGn palette and I want numbers below the threshold to be dark green and numbers above the threshold to more red (skipping some of the inner colors).

For my example my cut-off is nc$PERIMETER < 1.3 so I want numbers under this value to be green and everything above more red (color #FDAE61 onwards).

```<code>library(sf)
library(leaflet)
library(RColorBrewer)

#palette im using
palette <- rev(brewer.pal(11, "RdYlGn"))
# [1] "#006837" "#1A9850" "#66BD63" "#A6D96A" "#D9EF8B" "#FFFFBF" "#FEE08B" "#FDAE61" "#F46D43" "#D73027" "#A50026"
previewColors(colorNumeric(palette = palette, domain = 0:10), values = 0:10)

# preparing the shapefile
nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>%
  st_transform(st_crs(4326)) %>%
  st_cast('POLYGON')
nc

x <- sum(nc$PERIMETER < 1.3)
x # number of values below threshold = 21

### Create an asymmetric color range
## Make vector of colors for values smaller than 1.3 (21 colors)
rc1 <- colorRampPalette(colors = c("#006837", "#1A9850"), space = "Lab")(x)    #21

## Make vector of colors for values larger than 1.3
rc2 <- colorRampPalette(colors = c("#FDAE61", "#A50026"), space = "Lab")(length(nc$PERIMETER) - x)

## Combine the two color palettes
rampcols <- c(rc1, rc2)

mypal <- colorNumeric(palette = rampcols, domain = nc$PERIMETER)
previewColors(colorNumeric(palette = rampcols, domain = NULL), values = 1:length(nc$PERIMETER))
</code>```

looking at the preview it seems to have worked (21 values under 1.3 should be green):

plotting it:

```<code>leaflet() %>%
  addTiles() %>%
  addPolygons(data = nc,
              fillOpacity = 0.7,
              fillColor = ~mypal(PERIMETER),
              popup = paste("PERIMETER: ", nc$PERIMETER) )
</code>```

plots ok but doesn't give the right color, the one highlighted is above the threshold (1.3) and so shouldn't be green but it is:

I thought the way I was creating the palettes was wrong but the preview seems to suggest I've done it right?

anyone have any ideas? thanks

答:
I somewhat feel responsible for this question since I wrote that answer. I cannot tell how leaflet is assigning colors to polygons. But I think we witnessed that your approach is not working. Based on my previous idea, I did the following for you. I created a new continuous variable (i.e., ranking). This information is the order of values in PERIMETER.  In this way, the minimum value of PERIMETER (i.e., 0.999) is getting the first color for sure. In my previous answer here, I suggested using colorFactor(), but that gave you a hard time to create a legend. So here is additional information. When I created a legend, I used ranking in colorNumeric() and created a palette, which is mypal2. We are using identical information to fill in polygons and add a legend, but we use different functions (either colorFactor or colorNumeric). Once we have the legend, we gotta change the label format. Hence we use labelFormat(). I am using ranking as indices and getting values in PERIMETER.

```<code>library(sf)
library(leaflet)
library(RColorBrewer)

#palette im using
palette <- rev(brewer.pal(11, "RdYlGn"))
# [1] "#006837" "#1A9850" "#66BD63" "#A6D96A" "#D9EF8B" "#FFFFBF" "#FEE08B" "#FDAE61" "#F46D43" "#D73027" "#A50026"
previewColors(colorNumeric(palette = palette, domain = 0:10), values = 0:10)

# preparing the shapefile
nc2 <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>%
       st_transform(st_crs(4326))

# Add sequence information in order to create 108 categories for
# colorFactor(). I sorted the data and added the sequence information.

arrange(nc2, PERIMETER) %>%
mutate(ranking = 1:n()) -> nc2

x <- sum(nc2$PERIMETER < 1.3)
x # number of values below threshold = 21

### Create an asymmetric color range
## Make vector of colors for values smaller than 1.3 (21 colors)
rc1 <- colorRampPalette(colors = c("#006837", "#1A9850"), space = "Lab")(x)    #21

## Make vector of colors for values larger than 1.3
rc2 <- colorRampPalette(colors = c("#FDAE61", "#A50026"), space = "Lab")(length(nc2$PERIMETER) - x)

## Combine the two color palettes
rampcols <- c(rc1, rc2)

# Create a palette to fill in the polygons
mypal <- colorFactor(palette = rampcols, domain = factor(nc2$ranking))
previewColors(colorNumeric(palette = rampcols, domain = NULL), values = 1:length(nc$PERIMETER))

# Create a palette for a legend with ranking again. But this time with
# colorNumeric()

mypal2 <- colorNumeric(palette = rampcols, domain = nc2$ranking)

leaflet() %>%
addTiles() %>%
addPolygons(data = nc2,
            fillOpacity = 0.7,
            fillColor = ~mypal(nc2$ranking),
            popup = paste("PERIMETER: ", nc2$PERIMETER)) %>%
addLegend(position = "bottomright", pal = mypal2, values = nc2$ranking,
          title = "PERIMETER",
          opacity = 0.7,
          labFormat = labelFormat(transform = function(x) nc2$PERIMETER[x]))
</code>```

If I set up the threshold level at 2.3 (less than 2.3), I get this.

Body:
I'm trying to merge two colorRampPalette schemes to use in leaflet and have been following this nice  example. That example works fine but I can't seem to get it to work for my work, reproducible example below. I'm using RdYlGn palette and I want numbers below the threshold to be dark green and numbers above the threshold to more red (skipping some of the inner colors).

For my example my cut-off is nc$PERIMETER < 1.3 so I want numbers under this value to be green and everything above more red (color #FDAE61 onwards).

library(sf)
library(leaflet)
library(RColorBrewer)

#palette im using
palette <- rev(brewer.pal(11, "RdYlGn"))
# [1] "#006837" "#1A9850" "#66BD63" "#A6D96A" "#D9EF8B" "#FFFFBF" "#FEE08B" "#FDAE61" "#F46D43" "#D73027" "#A50026"
previewColors(colorNumeric(palette = palette, domain = 0:10), values = 0:10)

# preparing the shapefile
nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>%
  st_transform(st_crs(4326)) %>%
  st_cast('POLYGON')
nc

x <- sum(nc$PERIMETER < 1.3)
x # number of values below threshold = 21

### Create an asymmetric color range
## Make vector of colors for values smaller than 1.3 (21 colors)
rc1 <- colorRampPalette(colors = c("#006837", "#1A9850"), space = "Lab")(x)    #21

## Make vector of colors for values larger than 1.3
rc2 <- colorRampPalette(colors = c("#FDAE61", "#A50026"), space = "Lab")(length(nc$PERIMETER) - x)

## Combine the two color palettes
rampcols <- c(rc1, rc2)

mypal <- colorNumeric(palette = rampcols, domain = nc$PERIMETER)
previewColors(colorNumeric(palette = rampcols, domain = NULL), values = 1:length(nc$PERIMETER))

looking at the preview it seems to have worked (21 values under 1.3 should be green):

plotting it:

leaflet() %>%
  addTiles() %>%
  addPolygons(data = nc,
              fillOpacity = 0.7,
              fillColor = ~mypal(PERIMETER),
              popup = paste("PERIMETER: ", nc$PERIMETER) )

plots ok but doesn't give the right color, the one highlighted is above the threshold (1.3) and so shouldn't be green but it is:

I thought the way I was creating the palettes was wrong but the preview seems to suggest I've done it right?

anyone have any ideas? thanks

Body:
I somewhat feel responsible for this question since I wrote that answer. I cannot tell how leaflet is assigning colors to polygons. But I think we witnessed that your approach is not working. Based on my previous idea, I did the following for you. I created a new continuous variable (i.e., ranking). This information is the order of values in PERIMETER.  In this way, the minimum value of PERIMETER (i.e., 0.999) is getting the first color for sure. In my previous answer here, I suggested using colorFactor(), but that gave you a hard time to create a legend. So here is additional information. When I created a legend, I used ranking in colorNumeric() and created a palette, which is mypal2. We are using identical information to fill in polygons and add a legend, but we use different functions (either colorFactor or colorNumeric). Once we have the legend, we gotta change the label format. Hence we use labelFormat(). I am using ranking as indices and getting values in PERIMETER.

library(sf)
library(leaflet)
library(RColorBrewer)

#palette im using
palette <- rev(brewer.pal(11, "RdYlGn"))
# [1] "#006837" "#1A9850" "#66BD63" "#A6D96A" "#D9EF8B" "#FFFFBF" "#FEE08B" "#FDAE61" "#F46D43" "#D73027" "#A50026"
previewColors(colorNumeric(palette = palette, domain = 0:10), values = 0:10)

# preparing the shapefile
nc2 <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>%
       st_transform(st_crs(4326))

# Add sequence information in order to create 108 categories for
# colorFactor(). I sorted the data and added the sequence information.

arrange(nc2, PERIMETER) %>%
mutate(ranking = 1:n()) -> nc2

x <- sum(nc2$PERIMETER < 1.3)
x # number of values below threshold = 21

### Create an asymmetric color range
## Make vector of colors for values smaller than 1.3 (21 colors)
rc1 <- colorRampPalette(colors = c("#006837", "#1A9850"), space = "Lab")(x)    #21

## Make vector of colors for values larger than 1.3
rc2 <- colorRampPalette(colors = c("#FDAE61", "#A50026"), space = "Lab")(length(nc2$PERIMETER) - x)

## Combine the two color palettes
rampcols <- c(rc1, rc2)

# Create a palette to fill in the polygons
mypal <- colorFactor(palette = rampcols, domain = factor(nc2$ranking))
previewColors(colorNumeric(palette = rampcols, domain = NULL), values = 1:length(nc$PERIMETER))

# Create a palette for a legend with ranking again. But this time with
# colorNumeric()

mypal2 <- colorNumeric(palette = rampcols, domain = nc2$ranking)

leaflet() %>%
addTiles() %>%
addPolygons(data = nc2,
            fillOpacity = 0.7,
            fillColor = ~mypal(nc2$ranking),
            popup = paste("PERIMETER: ", nc2$PERIMETER)) %>%
addLegend(position = "bottomright", pal = mypal2, values = nc2$ranking,
          title = "PERIMETER",
          opacity = 0.7,
          labFormat = labelFormat(transform = function(x) nc2$PERIMETER[x]))

If I set up the threshold level at 2.3 (less than 2.3), I get this.


问:
What is the fastest way to check for existence and get random element from data structure in python?
I need a data structure (preferably a built in python type) that allows for existence check in O(1) and also random element choosing in O(1). The elements to store in the structure are unique integers. I have considered this options:

list: O(1) random choice with random.choice, but O(n) existence with in operator.

set: O(1) existence check with in operator, but can't use random.choice without casting to tuple (O(n))

tuple: O(1) random choice with random.choice, but O(n) check for existence

dictionary: O(1) existence check , but memory use is at least 2 times as much compared to the other options (keys and values) , and random.choice does not work without casting to list or getting items (assumably O(n) operations).

Do I need to implement a compound data structure? What is the best approach?
PD: I am using Python 3 by the way.

EDIT:

The data structure is created from a list comprehension with a range generator, so the data inside the sequence is always ordered. Something like this:

```<code>data=[x for x in range(n) if condition]
</code>```

答:
There are a few approaches for this. It depends how important it is to minimise memory usage. From the comments you've said it's not necessary to be able to add or remove elements.

Implicit set

For the special case where you know both the range that the numbers are drawn from, and the condition for them to be included in the set, and you also only need to do small number of membership and sampling operations, then you don't need to build any data structure at all. You can use the condition to test membership, and the range to sample from it:

import random

# example usage:
# >>> s = ImplicitSet(range(10), lambda x: x > 4)

class ImplicitSet:
    def __init__(self, range, condition):
        self.range = range
        self.condition = condition
    def contains(self, x):
        return x in self.range and self.condition(x)
    def sample(self):
        # you'll need to change this if the condition might never be true
        while True:
            x = random.choice(range)
            if self.condition(x):
                return x
```

<p>Unfortunately you can't just generate one random number and iterate until you find a member of the set, since that would bias the sampling towards numbers with bigger "gaps" before them.</p>

<p>This takes O(1) memory, because you aren't storing any actual data structure. The <code>contains</code> operation takes whatever time it takes to test the condition, but if you're only testing membership for a small number of elements, it saves time compared to a list comprehension which tests the condition for every element of the range.</p>

<p>The <code>sample</code> operation requires a number of tries inversely proportional to the density of elements satisfying the condition within the range, so e.g. if the condition is true for 25% of the elements then you need four tries on average. So sampling takes constant time, but the size of the constant depends on the distribution of the actual numbers. Again, if you're only sampling a few times then this is much better than a list comprehension having to test the condition for every number in the range.</p>

<h3>List and set</h3>

<p>This way is the simplest to implement, and gives both membership tests (using the set) and random sampling (using the list) in constant time. However, it stores each integer in two containers instead of one, using more memory.</p>

<pre class="lang-py prettyprint-override"><code>import random

class ListAndSet:
    def __init__(self, numbers):
        self.numbers_list = list(numbers)
        self.numbers_set = set(self.numbers_list) # numbers may be a generator
    def contains(self, x):
        return x in self.numbers_set
    def sample(self):
        return random.choice(self.numbers_list)
</code>```

Sorted list

This one is also pretty simple to implement, and it uses the least possible memory unless your numbers are within a fixed size, in which case a sorted array is better. It takes O(n log n) time to sort the numbers in the first place, but after that, membership tests take O(log n) time using a binary search, and sampling takes O(1) time.

import bisect
import random

class SortedList:
    def __init__(self, numbers):
        self.sorted_list = sorted(numbers)
    def contains(self, x):
        index = bisect.bisect_left(self.sorted_list, x)
        return index < len(self.sorted_list) and self.sorted_list[index] == x
    def sample(self):
        return random.choice(self.sorted_list)
```

<h3>Dense set</h3>

<p>If the numbers are densely packed within some range, you could store them in a set, and then sample by generating random numbers in that range until you find one that's in the set. The expected number of tries is inversely proportional to the density of the numbers within the range, so e.g. if you have 1,000 numbers within a range of size 4,000, you will need four tries on average.</p>

<pre class="lang-py prettyprint-override"><code>import random

class DenseSet:
    def __init__(self, numbers):
        self.numbers_set = set(numbers)
        # you'll need to change this if the set might sometimes be empty
        self.low = min(self.numbers_set)
        self.high = max(self.numbers_set)
    def contains(self, x):
        return x in self.numbers_set
    def sample(self):
        # you'll need to change this if the set might sometimes be empty
        while True:
            x = random.randint(self.low, self.high)
            if x in self.numbers_set:
                return x
</code>```

Your own hash-set

If O(log n) time isn't good enough, and the numbers are sparse, but you absolutely can't afford the memory required for both a list and a set, then you could implement your own hash-set; you can find example code by searching online. To sample in O(1) expected time, repeatedly generate random indices in the underlying list until you find a slot that is non-empty. This guarantees a uniform distribution of the samples. The expected number of tries is inversely proportional to the hash-set's load factor, so e.g. with a load factor of 0.8 you would need on average 1.25 tries.

Unfortunately you can't just generate one index and then iterate through until you find a non-empty slot, since the sampling would be biased towards elements with more empty slots behind them.

Body:
I need a data structure (preferably a built in python type) that allows for existence check in O(1) and also random element choosing in O(1). The elements to store in the structure are unique integers. I have considered this options:

list: O(1) random choice with random.choice, but O(n) existence with in operator.

set: O(1) existence check with in operator, but can't use random.choice without casting to tuple (O(n))

tuple: O(1) random choice with random.choice, but O(n) check for existence

dictionary: O(1) existence check , but memory use is at least 2 times as much compared to the other options (keys and values) , and random.choice does not work without casting to list or getting items (assumably O(n) operations).

Do I need to implement a compound data structure? What is the best approach?
PD: I am using Python 3 by the way.

EDIT:

The data structure is created from a list comprehension with a range generator, so the data inside the sequence is always ordered. Something like this:

data=[x for x in range(n) if condition]

Body:
There are a few approaches for this. It depends how important it is to minimise memory usage. From the comments you've said it's not necessary to be able to add or remove elements.

Implicit set

For the special case where you know both the range that the numbers are drawn from, and the condition for them to be included in the set, and you also only need to do small number of membership and sampling operations, then you don't need to build any data structure at all. You can use the condition to test membership, and the range to sample from it:

import random

# example usage:
# >>> s = ImplicitSet(range(10), lambda x: x > 4)

class ImplicitSet:
    def __init__(self, range, condition):
        self.range = range
        self.condition = condition
    def contains(self, x):
        return x in self.range and self.condition(x)
    def sample(self):
        # you'll need to change this if the condition might never be true
        while True:
            x = random.choice(range)
            if self.condition(x):
                return x

Unfortunately you can't just generate one random number and iterate until you find a member of the set, since that would bias the sampling towards numbers with bigger "gaps" before them.

This takes O(1) memory, because you aren't storing any actual data structure. The contains operation takes whatever time it takes to test the condition, but if you're only testing membership for a small number of elements, it saves time compared to a list comprehension which tests the condition for every element of the range.

The sample operation requires a number of tries inversely proportional to the density of elements satisfying the condition within the range, so e.g. if the condition is true for 25% of the elements then you need four tries on average. So sampling takes constant time, but the size of the constant depends on the distribution of the actual numbers. Again, if you're only sampling a few times then this is much better than a list comprehension having to test the condition for every number in the range.

List and set

This way is the simplest to implement, and gives both membership tests (using the set) and random sampling (using the list) in constant time. However, it stores each integer in two containers instead of one, using more memory.

import random

class ListAndSet:
    def __init__(self, numbers):
        self.numbers_list = list(numbers)
        self.numbers_set = set(self.numbers_list) # numbers may be a generator
    def contains(self, x):
        return x in self.numbers_set
    def sample(self):
        return random.choice(self.numbers_list)

Sorted list

This one is also pretty simple to implement, and it uses the least possible memory unless your numbers are within a fixed size, in which case a sorted array is better. It takes O(n log n) time to sort the numbers in the first place, but after that, membership tests take O(log n) time using a binary search, and sampling takes O(1) time.

import bisect
import random

class SortedList:
    def __init__(self, numbers):
        self.sorted_list = sorted(numbers)
    def contains(self, x):
        index = bisect.bisect_left(self.sorted_list, x)
        return index < len(self.sorted_list) and self.sorted_list[index] == x
    def sample(self):
        return random.choice(self.sorted_list)

Dense set

If the numbers are densely packed within some range, you could store them in a set, and then sample by generating random numbers in that range until you find one that's in the set. The expected number of tries is inversely proportional to the density of the numbers within the range, so e.g. if you have 1,000 numbers within a range of size 4,000, you will need four tries on average.

import random

class DenseSet:
    def __init__(self, numbers):
        self.numbers_set = set(numbers)
        # you'll need to change this if the set might sometimes be empty
        self.low = min(self.numbers_set)
        self.high = max(self.numbers_set)
    def contains(self, x):
        return x in self.numbers_set
    def sample(self):
        # you'll need to change this if the set might sometimes be empty
        while True:
            x = random.randint(self.low, self.high)
            if x in self.numbers_set:
                return x

Your own hash-set

If O(log n) time isn't good enough, and the numbers are sparse, but you absolutely can't afford the memory required for both a list and a set, then you could implement your own hash-set; you can find example code by searching online. To sample in O(1) expected time, repeatedly generate random indices in the underlying list until you find a slot that is non-empty. This guarantees a uniform distribution of the samples. The expected number of tries is inversely proportional to the hash-set's load factor, so e.g. with a load factor of 0.8 you would need on average 1.25 tries.

Unfortunately you can't just generate one index and then iterate through until you find a non-empty slot, since the sampling would be biased towards elements with more empty slots behind them.


问:
Spring Data Mongo - Perform Regular Search?
I went through many links like this: How to create full text search query in mongodb with spring-data?, but did not get the correct approach.

I've an Employee collection which holds 1000 documents. I want to give capability to perform search ignorecase where when I search for ra, I should get Ravi,Ram, rasika etc names.

I used below logic which works fine, but I wanted to understand from the perspective of performance. Is there any better solution than this?

```<code>Query query = new Query(Criteria.where("employeeName").regex("^"+employeeName, "i"));
</code>```

答:
You can create an index on the field you are applying the query filter using the regular expression. For example, consider the documents in a person collection:

```<code>{ "name" : "ravi" }
{ "name" : "ram" }
{ "name" : "John" }
{ "name" : "renu" }
{ "name" : "Raj" }
{ "name" : "peter" }
</code>```

The following query (run from Mongo Shell) finds and fetches the four documents with the names starting with the letter "r" or "R":

```<code>db.person.find( { name: { $regex: "^r", $options: "i" } } )
</code>```

But, the query performs a collection scan, without an index on the name field. So, create an index on the field.

```<code>db.person.createIndex( { name: 1 } )
</code>```

Now, run the query and generate a query plan for the same query (using the explain()). The query plan shown that it is an IXSCAN (an indexed scan). And, this will be an efficiently performing query.

Note that prefix searches (as in the above query using the ^) on index fields results in faster performing queries.

From the documentation:

For case sensitive regular expression queries, if an index exists for
  the field, then MongoDB matches the regular expression against the
  values in the index, which can be faster than a collection scan.
  Further optimization can occur if the regular expression is a “prefix
  expression”, which means that all potential matches start with the
  same string. This allows MongoDB to construct a “range” from that
  prefix and only match against those values from the index that fall
  within that range.

Though the documentation says the following (see below paragraph), the query I ran did use the index and the query plan generated using the explain() showed an index scan.

Case insensitive regular expression queries generally cannot use
  indexes effectively. The $regex implementation is not collation-aware
  and is unable to utilize case-insensitive indexes.

Body:
I went through many links like this: How to create full text search query in mongodb with spring-data?, but did not get the correct approach.

I've an Employee collection which holds 1000 documents. I want to give capability to perform search ignorecase where when I search for ra, I should get Ravi,Ram, rasika etc names.

I used below logic which works fine, but I wanted to understand from the perspective of performance. Is there any better solution than this?

Query query = new Query(Criteria.where("employeeName").regex("^"+employeeName, "i"));

Body:
You can create an index on the field you are applying the query filter using the regular expression. For example, consider the documents in a person collection:

{ "name" : "ravi" }
{ "name" : "ram" }
{ "name" : "John" }
{ "name" : "renu" }
{ "name" : "Raj" }
{ "name" : "peter" }

The following query (run from Mongo Shell) finds and fetches the four documents with the names starting with the letter "r" or "R":

db.person.find( { name: { $regex: "^r", $options: "i" } } )

But, the query performs a collection scan, without an index on the name field. So, create an index on the field.

db.person.createIndex( { name: 1 } )

Now, run the query and generate a query plan for the same query (using the explain()). The query plan shown that it is an IXSCAN (an indexed scan). And, this will be an efficiently performing query.

Note that prefix searches (as in the above query using the ^) on index fields results in faster performing queries.

From the documentation:

For case sensitive regular expression queries, if an index exists for
  the field, then MongoDB matches the regular expression against the
  values in the index, which can be faster than a collection scan.
  Further optimization can occur if the regular expression is a “prefix
  expression”, which means that all potential matches start with the
  same string. This allows MongoDB to construct a “range” from that
  prefix and only match against those values from the index that fall
  within that range.

Though the documentation says the following (see below paragraph), the query I ran did use the index and the query plan generated using the explain() showed an index scan.

Case insensitive regular expression queries generally cannot use
  indexes effectively. The $regex implementation is not collation-aware
  and is unable to utilize case-insensitive indexes.


问:
Using WinForm "button.visible" as parameter to method
I'm creating Library app using WinForms.
I have eLibraryClasses where I have all data including each form services, and eLibraryUI where I have all my WinForms.

I have a problem in one form where I would like to change states of button.Visible to false or true.

I tried to extract method from UI to Service like:

```<code>public void ShowDrawnBook(bool clickedButtonVisible, bool toReadButtonVisible, int buttonNumber)
    {
        //Hide button which cover answer
        clickedButtonVisible = false;
        //Add option to add randomized book to "To read" bookshelf
        toReadButtonVisible = true;
        //Return index of clicked button
        buttonClicked = buttonNumber;
    }
</code>```

And UI looks like for example:

```<code>service.ShowDrawnBook(randomBook2Button.Visible, toReadButton.Visible, 2);
</code>```

I tried, but I couldn't use "ref" neither "out" for this properties.
And in this way above it's building properly, but not working because of not changing parameters out of method.
I have such a many of them in this form, so I could do it like

```<code>randomBook2Button.Visible = SomeMethod();
toReadButton.Visible = SomeMethod();
... for every variable
</code>```

But I would like to avoid it.

Is there any way to send there buttons properties (bools) as parameters?

答:
Booleans are passed by value, not reference, thus your "problem".

To solve your problem, just take the Button(s) as parameters instead of the booleans. Button is a class, thus is passed by reference.

Then in your method change the state of the Button(s) properties as you see fit.

public void MyMethod(Button myButton1, Button myButton2)
{
    myButton1.Visible = true;
    myButton2.Visible = false;
}

Body:
I'm creating Library app using WinForms.
I have eLibraryClasses where I have all data including each form services, and eLibraryUI where I have all my WinForms.

I have a problem in one form where I would like to change states of button.Visible to false or true.

I tried to extract method from UI to Service like:

public void ShowDrawnBook(bool clickedButtonVisible, bool toReadButtonVisible, int buttonNumber)
    {
        //Hide button which cover answer
        clickedButtonVisible = false;
        //Add option to add randomized book to "To read" bookshelf
        toReadButtonVisible = true;
        //Return index of clicked button
        buttonClicked = buttonNumber;
    }

And UI looks like for example:

service.ShowDrawnBook(randomBook2Button.Visible, toReadButton.Visible, 2);

I tried, but I couldn't use "ref" neither "out" for this properties.
And in this way above it's building properly, but not working because of not changing parameters out of method.
I have such a many of them in this form, so I could do it like

randomBook2Button.Visible = SomeMethod();
toReadButton.Visible = SomeMethod();
... for every variable

But I would like to avoid it.

Is there any way to send there buttons properties (bools) as parameters?


问:
Div following cursor paints pixels on screen in Safari (bug?)
I've used the following code to make a div that follows the cursor with easing applied to the movement:

CSS

```<code>#cursor {
    position: absolute;
    width: auto;
    height: auto;
    white-space: nowrap;
    pointer-events: none;
    transition: opacity 200ms;
    cursor:none!important;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index:99999999;
    color:white;
    backface-visibility: hidden;
}
</code>```

JavaScript/jQuery:

```<code>$(document).on("mouseover mousemove", function (event) {
    mouseX = event.pageX;
    mouseY = event.pageY - $(window).scrollTop();
    cursorWidth = $cursor.width();
    cursorHeight = $cursor.height();
});
requestAnimationFrame(performAnimation);

var performAnimation = function() {
        var distX = mouseX - cursorX;
        var distY = mouseY - cursorY;
        cursorX = cursorX + (distX * speed);
        cursorY = cursorY + (distY * speed);

        $cursor.css({
            left: cursorX + "px",
            top: cursorY + "px"
        });
    request = requestAnimationFrame(performAnimation)
}
</code>```

It works as intended in Chrome, but on Safari it leaves traces of the text in the div on top of the screen, i. e. the elements underneath the cursor z-index wise. Here's a video showing the behaviour.

Is this a known bug with Safari and can it be avoided somehow? I'm not sure if this has to do with the requestAnimationFrame() function or if it's something else. I tried applying backface-visiblity:none; to the #cursor itself through CSS, as this sometimes solves these type of issues, but in this case it's not doing anything.

答:
The problem had to do with the #cursor being a child of a container that was fixed on top of the whole page. Removing this container and placing #cursor without a container on it's own fixed the issue.

For some reason I thought it was practical to have the cursor wrapped in this container so that I could add classes through JS to the container instead of the cursor itself to manipulate it's style. But I ended up adding the styling classes to a  inside #cursor instead.

Body:
I've used the following code to make a div that follows the cursor with easing applied to the movement:

CSS

#cursor {
    position: absolute;
    width: auto;
    height: auto;
    white-space: nowrap;
    pointer-events: none;
    transition: opacity 200ms;
    cursor:none!important;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index:99999999;
    color:white;
    backface-visibility: hidden;
}

JavaScript/jQuery:

$(document).on("mouseover mousemove", function (event) {
    mouseX = event.pageX;
    mouseY = event.pageY - $(window).scrollTop();
    cursorWidth = $cursor.width();
    cursorHeight = $cursor.height();
});
requestAnimationFrame(performAnimation);

var performAnimation = function() {
        var distX = mouseX - cursorX;
        var distY = mouseY - cursorY;
        cursorX = cursorX + (distX * speed);
        cursorY = cursorY + (distY * speed);

        $cursor.css({
            left: cursorX + "px",
            top: cursorY + "px"
        });
    request = requestAnimationFrame(performAnimation)
}

It works as intended in Chrome, but on Safari it leaves traces of the text in the div on top of the screen, i. e. the elements underneath the cursor z-index wise. Here's a video showing the behaviour.

Is this a known bug with Safari and can it be avoided somehow? I'm not sure if this has to do with the requestAnimationFrame() function or if it's something else. I tried applying backface-visiblity:none; to the #cursor itself through CSS, as this sometimes solves these type of issues, but in this case it's not doing anything.

Body:
The problem had to do with the #cursor being a child of a container that was fixed on top of the whole page. Removing this container and placing #cursor without a container on it's own fixed the issue.

For some reason I thought it was practical to have the cursor wrapped in this container so that I could add classes through JS to the container instead of the cursor itself to manipulate it's style. But I ended up adding the styling classes to a <span> inside #cursor instead.


问:
Powershell command that only works properly for a few files
I have a bunch of files named 001.jpg, 002.jpg and so on. I'd like to rename them Gym Heroes - 001 (US).jpg, etc. I wrote this Powershell command:

```<code>dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }
</code>```

This works as expected when there are 35 or fewer pictures, but starting from 36 pictures, all the pictures are weirdly renamed (Gym Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - 016 (US).jpg) and I get the following error message for each file (not the exact error message since I translated it to English):

```<code>Rename-Item : Part of the access path is impossible to find.
At character Line:1 : 7
+ dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Downloads... - 062 (US).jpg:String) [Rename-Item], DirectoryNotFoundE
   xception
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommande
</code>```

I don't understand at all why this is happening... I could rename my pictures 35 by 35 but I'd like to understand why my command doesn't work properly.

Thanks!

答:
I'd suggest properly looping through your files and renaming one by one.

```<code>dir | % {
    $_ | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }
}
</code>```

I'm not sure about how piping Rename-Item from the dir command works exactly.

Anyway, tested this with 2,000 files.

Body:
I have a bunch of files named 001.jpg, 002.jpg and so on. I'd like to rename them Gym Heroes - 001 (US).jpg, etc. I wrote this Powershell command:

dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }

This works as expected when there are 35 or fewer pictures, but starting from 36 pictures, all the pictures are weirdly renamed (Gym Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - 016 (US).jpg) and I get the following error message for each file (not the exact error message since I translated it to English):

Rename-Item : Part of the access path is impossible to find.
At character Line:1 : 7
+ dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Downloads... - 062 (US).jpg:String) [Rename-Item], DirectoryNotFoundE
   xception
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommande

I don't understand at all why this is happening... I could rename my pictures 35 by 35 but I'd like to understand why my command doesn't work properly.

Thanks!

Body:
I'd suggest properly looping through your files and renaming one by one.

dir | % {
    $_ | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }
}

I'm not sure about how piping Rename-Item from the dir command works exactly.

Anyway, tested this with 2,000 files.


问:
Is there any way to pushd without enter that directory?
```<code>ls
// a b c
</code>```

So,with pushd,i want to add 'b' to the directory stack index ,but not enter directory b, is there any easy way to do this?

答:
Use the -n parameter of pushd:

```<code>pushd -n somedir
</code>```

-n will cause directory somedir to be added to the stack, while suppressing the normal change of directory.

You can see the documentation for pushd with:

```<code>man bash
</code>```

Then search for pushd by issuing (multiple times):

```<code>/pushd
</code>```

Body:
ls
// a b c

So,with pushd,i want to add 'b' to the directory stack index ,but not enter directory b, is there any easy way to do this?

Body:
Use the -n parameter of pushd:

pushd -n somedir

-n will cause directory somedir to be added to the stack, while suppressing the normal change of directory.

You can see the documentation for pushd with:

man bash

Then search for pushd by issuing (multiple times):

/pushd


问:
Get users from an AD group
I have this code to work with users from a group

```<code>DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}
</code>```

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?

答:
Assuming you're on .NET 3.5 or newer (or can upgrade to it), you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

Basically, you can define a domain context and easily find users and/or groups in AD:

```<code>// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}
</code>```

The new S.DS.AM makes it really easy to play around with users and groups in AD:

Title: Get users from an AD group

Body:
I have this code to work with users from a group

DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?

Body:
Assuming you're on .NET 3.5 or newer (or can upgrade to it), you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD:


问:
iOS13 share sheet: how to set preview thumbnail when sharing UIImage
The new share sheet on iOS13 shows a preview/thumbnail of the item being shared on its top left corner.

When sharing an UIImage using an UIActivityViewController I would expect a preview/thumbnail of the image being shared to be displayed there (like e.g. when sharing an image attached to the built in Mail app), but instead the share sheet is showing my app's icon.

What code/settings are required to show a thumbnail of the image being exported in the share sheet?

I have set up the UIActivityViewController as follows:

```<code>let image = UIImage(named: "test")!
let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = self.view
self.present(activityVC, animated: true, completion: nil)
</code>```

答:
The simplest code I've implemented to share a UIImage with better user experience:

Import the LinkPresentation framework:

```<code>#import <LinkPresentation/LPLinkMetadata.h>  // for Obj-C

import LinkPresentation  // for Swift, below
</code>```

Present the UIActivityViewController in the UIViewController, with [image, self]:

```<code>let image = UIImage(named: "YourImage")!
let share = UIActivityViewController(activityItems: [image, self], applicationActivities: nil)
present(share, animated: true, completion: nil)
</code>```

Make the UIViewController conform to UIActivityItemSource:

```<code>func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
    return ""
}

func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
    return nil
}

func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
    let image = UIImage(named: "YourImage")!
    let imageProvider = NSItemProvider(object: image)
    let metadata = LPLinkMetadata()
    metadata.imageProvider = imageProvider
    return metadata
}
</code>```

Because UIImage has already conformed to NSItemProviderWriting, just serve it for NSItemProvider.

Since it's sharing a UIImage, any URL shouldn't be expected. Otherwise user may get URL sharing, rather than image sharing experience.

To accelerate the share sheet preview, feed LPLinkMetadata object with existing resources. No need to fetch it online again. Check the WWDC19 Tech Talks video What's New in Sharing for more details.

Body:
The new share sheet on iOS13 shows a preview/thumbnail of the item being shared on its top left corner.

When sharing an UIImage using an UIActivityViewController I would expect a preview/thumbnail of the image being shared to be displayed there (like e.g. when sharing an image attached to the built in Mail app), but instead the share sheet is showing my app's icon.

What code/settings are required to show a thumbnail of the image being exported in the share sheet?

I have set up the UIActivityViewController as follows:

let image = UIImage(named: "test")!
let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = self.view
self.present(activityVC, animated: true, completion: nil)

Body:
The simplest code I've implemented to share a UIImage with better user experience:

Import the LinkPresentation framework:

#import <LinkPresentation/LPLinkMetadata.h>  // for Obj-C

import LinkPresentation  // for Swift, below

Present the UIActivityViewController in the UIViewController, with [image, self]:

let image = UIImage(named: "YourImage")!
let share = UIActivityViewController(activityItems: [image, self], applicationActivities: nil)
present(share, animated: true, completion: nil)

Make the UIViewController conform to UIActivityItemSource:

func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
    return ""
}

func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
    return nil
}

func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
    let image = UIImage(named: "YourImage")!
    let imageProvider = NSItemProvider(object: image)
    let metadata = LPLinkMetadata()
    metadata.imageProvider = imageProvider
    return metadata
}

Because UIImage has already conformed to NSItemProviderWriting, just serve it for NSItemProvider.

Since it's sharing a UIImage, any URL shouldn't be expected. Otherwise user may get URL sharing, rather than image sharing experience.

To accelerate the share sheet preview, feed LPLinkMetadata object with existing resources. No need to fetch it online again. Check the WWDC19 Tech Talks video What's New in Sharing for more details.


问:
ViewModel onchange gets called multiple times when back from Fragment
I am working with Android architecture components.
What i want is when user type "0" in Edittext and click on Button to replace Fragment with new one , and if type anything else post Toast error message. In  Problem is when i back from new Fragment(BlankFragment) and click on button again and type "0" again and click, onchange() is called multiple times so  Fragment is get created multiple times

FragmentExample.class:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        manager = getActivity().getSupportFragmentManager();
        viewmModel = ViewModelProviders.of(getActivity(), viewModelFactory)
                .get(VModel.class);

        View v = inflater.inflate(R.layout.fragment_list, container, false);
        b = (Button) v.findViewById(R.id.b);
        et = (EditText) v.findViewById(R.id.et);

        viewmModel.observeData().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {

                if(s.equals("0")) {
                    BlankFragment fragment = (BlankFragment) manager.findFragmentByTag(DETAIL_FRAG);
                    if (fragment == null) {
                        fragment = BlankFragment.newInstance();
                    }
                    addFragmentToActivity(manager,
                            fragment,
                            R.id.root_activity_detail,
                            DETAIL_FRAG
                    );
                } else {
                    Toast.makeText(getContext(), "Wrong text", Toast.LENGTH_SHORT).show();
                }
            }
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewmModel.setData(et.getText().toString());
            }
        });
        return v;
    }
    private void addFragmentToActivity(FragmentManager fragmentManager, BlankFragment fragment, int root_activity_detail, String detailFrag) {
        android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(root_activity_detail, fragment, detailFrag).addToBackStack(detailFrag);
        transaction.commit();
    }
```

<p>Repository class:</p>

<pre class="lang-java prettyprint-override"><code>
    public class Repository {
    MutableLiveData<String> dataLive = new MutableLiveData<>();

    public Repository() {

    }

    public void setListData(String data) {
       dataLive.setValue(data);
    }

    public MutableLiveData<String> getData() {
        return dataLive;
    }
}
</code>```

BlankFragment.class:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
                .get(VModel.class);
        listItemViewModel.setData("");
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }
```

答:
Adding some useful information after @Samuel-Eminet,
it's true that onCreate(Bundle?) is called only once on the Fragment creation and when you press back, the view is recreated but not the fragment (hence why the ViewModel is the same. If you subscribe in any method of the lifecycle that affects the view, it will resubscribe again and again.
Observers would have been gone and you won't be able to tell even if you ask for liveData.hasObservers().

The best thing to do is subscribing when onCreate(Bundle?) but many of us are using the binding, and the view isn't created at this time, so this is the best way to do it:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycleScope.launchWhenStarted {
        subscribeUI()
    }
}
</code>```

now you're telling the Fragment's lifecycle to do something when it starts the Fragment and it will call it only once.

Body:
I am working with Android architecture components.
What i want is when user type "0" in Edittext and click on Button to replace Fragment with new one , and if type anything else post Toast error message. In  Problem is when i back from new Fragment(BlankFragment) and click on button again and type "0" again and click, onchange() is called multiple times so  Fragment is get created multiple times

FragmentExample.class:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        manager = getActivity().getSupportFragmentManager();
        viewmModel = ViewModelProviders.of(getActivity(), viewModelFactory)
                .get(VModel.class);

        View v = inflater.inflate(R.layout.fragment_list, container, false);
        b = (Button) v.findViewById(R.id.b);
        et = (EditText) v.findViewById(R.id.et);

        viewmModel.observeData().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {

                if(s.equals("0")) {
                    BlankFragment fragment = (BlankFragment) manager.findFragmentByTag(DETAIL_FRAG);
                    if (fragment == null) {
                        fragment = BlankFragment.newInstance();
                    }
                    addFragmentToActivity(manager,
                            fragment,
                            R.id.root_activity_detail,
                            DETAIL_FRAG
                    );
                } else {
                    Toast.makeText(getContext(), "Wrong text", Toast.LENGTH_SHORT).show();
                }
            }
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewmModel.setData(et.getText().toString());
            }
        });
        return v;
    }
    private void addFragmentToActivity(FragmentManager fragmentManager, BlankFragment fragment, int root_activity_detail, String detailFrag) {
        android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(root_activity_detail, fragment, detailFrag).addToBackStack(detailFrag);
        transaction.commit();
    }

Repository class:

    public class Repository {
    MutableLiveData<String> dataLive = new MutableLiveData<>();

    public Repository() {

    }

    public void setListData(String data) {
       dataLive.setValue(data);
    }

    public MutableLiveData<String> getData() {
        return dataLive;
    }
}

BlankFragment.class:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
                .get(VModel.class);
        listItemViewModel.setData("");
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

Body:
Adding some useful information after @Samuel-Eminet,
it's true that onCreate(Bundle?) is called only once on the Fragment creation and when you press back, the view is recreated but not the fragment (hence why the ViewModel is the same. If you subscribe in any method of the lifecycle that affects the view, it will resubscribe again and again.
Observers would have been gone and you won't be able to tell even if you ask for liveData.hasObservers().

The best thing to do is subscribing when onCreate(Bundle?) but many of us are using the binding, and the view isn't created at this time, so this is the best way to do it:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycleScope.launchWhenStarted {
        subscribeUI()
    }
}

now you're telling the Fragment's lifecycle to do something when it starts the Fragment and it will call it only once.


问:
function not being added to NAMESPACE
I have a function that I'm trying to add to a package.  I am generating the documentation via devtools::document().  The .Rd files for this and ~70 other functions are generated successfully, but this one function is not added to the namespace.

The file can be found at the following link, and perhaps importantly, is called truncate.distribution.r.  I have many other functions with periods in the names, so I am almost certain that is not the problem.

However, as I was going through the NAMESPACE, I noticed this line S3method(truncate,distribution), and wondered if the similar name was a coincidence (i.e. comma, as opposed to period).  I tried removing the period from the name, and re-generating the documentation and NAMESPACE, and it all worked just fine - that is, the function is exported with the package.

While the altered name works, I would like to learn why it failed and how I can prevent similar failures in the future.  Also, I like the original name. :)

Anyone have any thoughts?  Much appreciated.

答: I found one other potential cause of similar grief.  My last line of Roxygen code had a typo in the  #' @export command resulting in the same poor behavior

Title: function not being added to NAMESPACE