问:
java.util.ConcurrentModificationException in activity onCreate
In a recent release where I added MoPub via Admob ad mediation I am seeing a bunch of ConcurrentModificationException in crash logs. It all seems to be native code and I am on the latest version of all ad related and google/android related libraries. Anyone run in to this before?

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3121)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3264)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:78)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1955)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7078)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:964)
Caused by: java.util.ConcurrentModificationException:
  at androidx.c.g.put (SimpleArrayMap.java:482)
  at com.google.android.gms.measurement.internal.hs.a
  at com.google.android.gms.measurement.internal.hi.onActivityCreated
  at android.app.Application.dispatchActivityCreated (Application.java:245)
  at android.app.Activity.onCreate (Activity.java:1108)
  at androidx.core.app.e.onCreate (ComponentActivity.java:81)
  at androidx.activity.b.onCreate (ComponentActivity.java:149)
  at androidx.fragment.app.c.onCreate (FragmentActivity.java:313)
  at androidx.appcompat.app.e.onCreate (AppCompatActivity.java:106)
  at com.teamtol.livedota.BaseActivity.onCreate (BaseActivity.java:21)
  at com.teamtol.livedota.RecentGameActivity.onCreate (RecentGameActivity.java:70)
  at android.app.Activity.performCreate (Activity.java:7327)
  at android.app.Activity.performCreate (Activity.java:7318)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1275)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3101)
</code>```

This is what the code looks like up to line 21 of BaseActivity:

```<code>protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
</code>```

This is what the code looks like up to line 70 of RecentGameActivity

```<code>public class RecentGameActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
</code>```

答: We've identified the issue, and are working on a fix for the next release of the SDK.</p>

Body:
In a recent release where I added MoPub via Admob ad mediation I am seeing a bunch of ConcurrentModificationException in crash logs. It all seems to be native code and I am on the latest version of all ad related and google/android related libraries. Anyone run in to this before?

java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3121)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3264)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:78)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1955)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7078)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:964)
Caused by: java.util.ConcurrentModificationException:
  at androidx.c.g.put (SimpleArrayMap.java:482)
  at com.google.android.gms.measurement.internal.hs.a
  at com.google.android.gms.measurement.internal.hi.onActivityCreated
  at android.app.Application.dispatchActivityCreated (Application.java:245)
  at android.app.Activity.onCreate (Activity.java:1108)
  at androidx.core.app.e.onCreate (ComponentActivity.java:81)
  at androidx.activity.b.onCreate (ComponentActivity.java:149)
  at androidx.fragment.app.c.onCreate (FragmentActivity.java:313)
  at androidx.appcompat.app.e.onCreate (AppCompatActivity.java:106)
  at com.teamtol.livedota.BaseActivity.onCreate (BaseActivity.java:21)
  at com.teamtol.livedota.RecentGameActivity.onCreate (RecentGameActivity.java:70)
  at android.app.Activity.performCreate (Activity.java:7327)
  at android.app.Activity.performCreate (Activity.java:7318)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1275)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3101)

This is what the code looks like up to line 21 of BaseActivity:

protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);

This is what the code looks like up to line 70 of RecentGameActivity

public class RecentGameActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


来源: stackexchange

问:
Can adding equals() and hashCode() method spoil something
Is it possible that adding equals() and hashCode() methods will break already existing code?

I have a class with 3 fields, getters and setters:

```<code>public class Person {
private final String name;
private final List<Friend> friends;
private final Integer age;
</code>```

to test this class I used: isEqualToComparingFieldByField() method to compare two Person objects instead of adding equals() and hashCode(). Other solution is to override equals() and hashCode() and use assertEquals() to compare these object but can I be totally sure that it won't break anything?

答: That depends on where and how you have used the person object. For example if you store person in HashSet, HashMap etc like data structure then it may behave differently. However, it is always recommended to override those methods if you are using any data-structure which uses hash and equals.</p>

ContentLicense: CC BY-SA 4.0

Body:
Is it possible that adding equals() and hashCode() methods will break already existing code?

I have a class with 3 fields, getters and setters:

public class Person {
private final String name;
private final List<Friend> friends;
private final Integer age;

to test this class I used: isEqualToComparingFieldByField() method to compare two Person objects instead of adding equals() and hashCode(). Other solution is to override equals() and hashCode() and use assertEquals() to compare these object but can I be totally sure that it won't break anything?


问:
JavaMailSender failure: javax.mail.internet.ParseException: Missing '"'
We have a JavaMailSender which failed on send().

This usually works well for us for quite a long time. Only now we have a peculiar bug:

JavaMailSender failure: javax.mail.internet.ParseException: Missing '"'

This is the code:

```<code>public class MailService {
    private static JavaMailSender fooMailSender;

    ...

    class FooSendMail extends Thread {
        MimeMessage message;

        FooSendMail(MimeMessage message) {
            this.message = message;
        }

        public void run() {
            try {
                fooMailSender.send(message);
            } catch (MailException e) {
                ...
            }
        }
    }
}
</code>```

This is a stack trace of the error:

```<code>org.springframework.mail.MailSendException: Failed messages: javax.mail.internet.ParseException: Missing '"'; message exception details (1) are:
Failed message 1:
javax.mail.internet.ParseException: Missing '"'
    at javax.mail.internet.HeaderTokenizer.readQuotedString(HeaderTokenizer.java:272)
    at javax.mail.internet.HeaderTokenizer.readToken(HeaderTokenizer.java:134)
    at javax.mail.internet.HeaderTokenizer.next(HeaderTokenizer.java:81)
    at javax.mail.internet.ParameterList.<init>(ParameterList.java:68)
    at javax.mail.internet.ContentDisposition.<init>(ContentDisposition.java:51)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:580)
    at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:128)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:1353)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:1325)
    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:443)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
    at com.builde.service.MailService$FooSendMail.run(MailService.java:434)
</code>```

We couldn't understand what the problem was.

The question is: what could be the problem?

答:
We found out that attaching a *.msg (Outlook message file) was causing the problem.

It could be that JavaMailSender doesn't support *.msg attachments

Body:
We have a JavaMailSender which failed on send().

This usually works well for us for quite a long time. Only now we have a peculiar bug:

JavaMailSender failure: javax.mail.internet.ParseException: Missing '"'

This is the code:

public class MailService {
    private static JavaMailSender fooMailSender;

    ...

    class FooSendMail extends Thread {
        MimeMessage message;

        FooSendMail(MimeMessage message) {
            this.message = message;
        }

        public void run() {
            try {
                fooMailSender.send(message);
            } catch (MailException e) {
                ...
            }
        }
    }
}

This is a stack trace of the error:

org.springframework.mail.MailSendException: Failed messages: javax.mail.internet.ParseException: Missing '"'; message exception details (1) are:
Failed message 1:
javax.mail.internet.ParseException: Missing '"'
    at javax.mail.internet.HeaderTokenizer.readQuotedString(HeaderTokenizer.java:272)
    at javax.mail.internet.HeaderTokenizer.readToken(HeaderTokenizer.java:134)
    at javax.mail.internet.HeaderTokenizer.next(HeaderTokenizer.java:81)
    at javax.mail.internet.ParameterList.<init>(ParameterList.java:68)
    at javax.mail.internet.ContentDisposition.<init>(ContentDisposition.java:51)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:580)
    at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:128)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:1353)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:1325)
    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:443)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
    at com.builde.service.MailService$FooSendMail.run(MailService.java:434)

We couldn't understand what the problem was.

The question is: what could be the problem?


问:
Unable to bind LINQ to gridview

Possible Duplicate:

  Unable to bind LINQ to gridview

I'm just using a simple LINQ query having group by clause and trying to bind its result set to GridView. My LINQ query looks like

```<code>var expData = from c in WebDB.TblTrans
              group c by c.transdate into g
              select g;
</code>```

Grid view on ASP.NET page

```<code><asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" DataKeyField="Key" />
</code>```

But getting the error:

A field or property with the name 'Key' was not found on the selected data source.

Anyone can help me please?

答:
The error message is pretty explicit, either get rid of the DataKeyField from your gridview code or you need to query against something that has a column named Key

Disregard the above, it seems I didn't notice your group statement. But I would still try binding to the gridview without the data key field to make sure your query is running appropriately

ContentLicense: CC BY-SA 3.0

Title: Unable to bind LINQ to gridview

Body:
Possible Duplicate:

  Unable to bind LINQ to gridview

I'm just using a simple LINQ query having group by clause and trying to bind its result set to GridView. My LINQ query looks like

var expData = from c in WebDB.TblTrans
              group c by c.transdate into g
              select g;

Grid view on ASP.NET page

<asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" DataKeyField="Key" />

But getting the error:

A field or property with the name 'Key' was not found on the selected data source.

Anyone can help me please?


问:
Why my python file returns unable to load app in uwsgi flask?
I have read the below questions related to uwsgi and interestingly enough nothing has helped so far:

Flask and uWSGI - unable to load app 0 (mountpoint='') (callable not found or import error)

uwsgi-nginx-flask: unable to load app 0 (mountpoint='') (callable not found or import error)

unable to load app 0 (mountpoint='') - Flask app with uwsgi

It seems that I need to import app as application as uWSGI tries to find the application variable.

```<code>from tf_api import create_app as application

if __name__ == "__main__":
    application = application()
    application.run()
else:
    print("---------------------->", __name__)
    application = application()
</code>```

When I run the below command:

```<code>uwsgi --socket 0.0.0.0:80 --protocol=tcp -w wsgi:app
</code>```

It goes to else part and outputs:

```<code>----------------------> wsgi
2020-02-20 14:25:22,168 [tf_core] Initialized! [testing=False]
2020-02-20 14:25:22,176 [tf_api] {"msg": "Initialized! Testing: False", "logger_name": "tf_api", "log_level": "DEBUG", "timestamp": "2020-02-20T14:25:22.176664"}
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 27143, cores: 1)
</code>```

Some logs are printed from the application then it prints no app loaded!

When I put application.run(host='0.0.0.0') in else, it seems that application starts running but on flask default port 5000 not on uWSGI:

```<code>----------------------> wsgi
2020-02-20 14:36:57,333 [tf_core] Initialized! [testing=False]
2020-02-20 14:36:57,339 [tf_api] {"msg": "Initialized! Testing: False", "logger_name": "tf_api", "log_level": "DEBUG", "timestamp": "2020-02-20T14:36:57.339723"}
 * Serving Flask app "tf_api" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
2020-02-20 14:36:57,405 [werkzeug]  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
2020-02-20 14:36:57,406 [werkzeug]  * Restarting with stat
unable to load configuration from /usr/local/lib/python3.6/dist-packages/tf_api/uwsgi
</code>```

BUT it gives an error related to unable to load configuration from. created_app returns app. What do you guys think is the reason for not finding the app in uswgi?

答:
When in uwsgi command I used -w wsgi:app I had to rename below code:

```<code>application = application()
</code>```

to:

```<code>app = application()
</code>```

Without app.run(), as uWSGI itself runs the flask application and it is not needed.

Body:
I have read the below questions related to uwsgi and interestingly enough nothing has helped so far:

Flask and uWSGI - unable to load app 0 (mountpoint='') (callable not found or import error)

uwsgi-nginx-flask: unable to load app 0 (mountpoint='') (callable not found or import error)

unable to load app 0 (mountpoint='') - Flask app with uwsgi

It seems that I need to import app as application as uWSGI tries to find the application variable.

from tf_api import create_app as application

if __name__ == "__main__":
    application = application()
    application.run()
else:
    print("---------------------->", __name__)
    application = application()

When I run the below command:

uwsgi --socket 0.0.0.0:80 --protocol=tcp -w wsgi:app

It goes to else part and outputs:

----------------------> wsgi
2020-02-20 14:25:22,168 [tf_core] Initialized! [testing=False]
2020-02-20 14:25:22,176 [tf_api] {"msg": "Initialized! Testing: False", "logger_name": "tf_api", "log_level": "DEBUG", "timestamp": "2020-02-20T14:25:22.176664"}
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 27143, cores: 1)

Some logs are printed from the application then it prints no app loaded!

When I put application.run(host='0.0.0.0') in else, it seems that application starts running but on flask default port 5000 not on uWSGI:

----------------------> wsgi
2020-02-20 14:36:57,333 [tf_core] Initialized! [testing=False]
2020-02-20 14:36:57,339 [tf_api] {"msg": "Initialized! Testing: False", "logger_name": "tf_api", "log_level": "DEBUG", "timestamp": "2020-02-20T14:36:57.339723"}
 * Serving Flask app "tf_api" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
2020-02-20 14:36:57,405 [werkzeug]  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
2020-02-20 14:36:57,406 [werkzeug]  * Restarting with stat
unable to load configuration from /usr/local/lib/python3.6/dist-packages/tf_api/uwsgi

BUT it gives an error related to unable to load configuration from. created_app returns app. What do you guys think is the reason for not finding the app in uswgi?

Body:
When in uwsgi command I used -w wsgi:app I had to rename below code:

application = application()

to:

app = application()

Without app.run(), as uWSGI itself runs the flask application and it is not needed.


问:
Custom error class in TypeScript
I'd like to create my own error class in TypeScript, extending core Error to provide better error handling and customized reporting. For example, I want to create an HttpRequestError class with url, response and body passed into its constructor, which reponds with Http request to http://example.com failed with status code 500 and message: Something went wrong and proper stack trace.

How to extend core Error class in TypeScript? I've already found post in SO: How do I extend a host object (e.g. Error) in TypeScript but this solution doesn't work for me. I use TypeScript 1.5.3

Any ideas?

答:
For Typescript 3.7.5 this code provided a custom error class that also captured the correct stack information. Note instanceof does not work so I use name instead

```<code>// based on https://gunargessner.com/subclassing-exception

// example usage
try {
  throw new DataError('Boom')
} catch(error) {
  console.log(error.name === 'DataError') // true
  console.log(error instanceof DataError) // false
  console.log(error instanceof Error) // true
}

class DataError {
  constructor(message: string) {
    const error = Error(message);

    // set immutable object properties
    Object.defineProperty(error, 'message', {
      get() {
        return message;
      }
    });
    Object.defineProperty(error, 'name', {
      get() {
        return 'DataError';
      }
    });
    // capture where error occured
    Error.captureStackTrace(error, DataError);
    return error;
  }
}
</code>```

There are some other alternatives and a discussion of the reasons.

Title: Custom error class in TypeScript

Body:
For Typescript 3.7.5 this code provided a custom error class that also captured the correct stack information. Note instanceof does not work so I use name instead

// based on https://gunargessner.com/subclassing-exception

// example usage
try {
  throw new DataError('Boom')
} catch(error) {
  console.log(error.name === 'DataError') // true
  console.log(error instanceof DataError) // false
  console.log(error instanceof Error) // true
}

class DataError {
  constructor(message: string) {
    const error = Error(message);

    // set immutable object properties
    Object.defineProperty(error, 'message', {
      get() {
        return message;
      }
    });
    Object.defineProperty(error, 'name', {
      get() {
        return 'DataError';
      }
    });
    // capture where error occured
    Error.captureStackTrace(error, DataError);
    return error;
  }
}

There are some other alternatives and a discussion of the reasons.


答:
You should always override those methods when you create your custom class. If you don't then implementations from Object class are used, and those implementations rely on reference - not on values of fields in objects of your custom class.

If you create two identical objects of your custom class and you use equals() method from Object class to compare them, you will get 'false' as a result. That's because even though those objects are identical, they contain different references.

Title: Can adding equals() and hashCode() method spoil something


问:
How to do mutually exclusive read or write operation on a global variable in signal handler and normal function
The application is multi-threaded.
Inside main(), I register the signal handler for SIGUSR1:

```<code>// Global variable to indicate whether directory's
// content needs to be reloaded
bool reload_dir = 0;

int main (int argc, char *argv[])
{
    ...

    signal(SIGUSR1, sigusr1_handler);

    ...

    RunServer(arg1, ...);
    return 0;
}
</code>```

Signal handler:

```<code>static void
sigusr1_handler (int signo __unused)
{
    reload_dir = 1;
    return;
}
</code>```

The following function (which is called from main) is only executed by the main thread:

```<code>void
RunServer (arg1, ...)
{
    // do some stuffs
    ...

    while (cond != true) {
        sleep(1);
    }

    server_exit();
}
</code>```

Now, when the SIGUSR1 is caught (by any thread including the main thread), I'm setting the reload_dir variable to 1. And in RunServer(), I'm reloading the directory based on that value. However, I'm also resetting the global variable reload_dir to 0 to avoid loading the directory repeatedly indefinitely. And this setting reload_dir to 0 will introduce a race.

Since we should not use locks or mutex in a signal handler, how can I achieve this without majorly changing the existing application design.

```<code>void
RunServer (arg1, ...)
{
    // do some stuffs
    ...

    while (cond != true) {
        if (reload_dir) {
           // reset reload_dir to avoid loading repeatedly indefinitely
           reload_dir = 0;   // Race condition?
           dir_reinit();
        }
        sleep(1);
    }

    server_exit();
}
</code>```

答:
Block SIGUSR1 with pthread_sigmask before any threads are spawned, so that all threads inherit that mask.  Then, in main(), use sigtimedwait instead of sleep in your main loop to check if USR1 has been delivered.

```<code>int main(...) {
    ...

    sigset_t ss_usr1;
    sigemptyset(&ss_usr1);
    sigaddset(&ss_usr1, SIGUSR1);

    // block SIGUSR1
    pthread_sigmask(SIG_BLOCK, &ss_usr1, NULL);

    ... spawn threads ...

    // RunServer
    struct timespec patience = { .tv_sec = 1 };

    while (! some_condition) {
        int s = sigtimedwait(&ss_usr1, NULL, &patience);
        if (s == SIGUSR1) dir_reinit();
        // handle errors other than timeout appropriately
    }
    server_exit();

    ...
}
</code>```

Benefits:  no signal handler complexity (and you won't be chastized, rightly, for using signal instead of the superior sigaction; no need for atomic flags or sig_atomic_t; easier to reason about behavior.

Body:
The application is multi-threaded.
Inside main(), I register the signal handler for SIGUSR1:

// Global variable to indicate whether directory's
// content needs to be reloaded
bool reload_dir = 0;

int main (int argc, char *argv[])
{
    ...

    signal(SIGUSR1, sigusr1_handler);

    ...

    RunServer(arg1, ...);
    return 0;
}

Signal handler:

static void
sigusr1_handler (int signo __unused)
{
    reload_dir = 1;
    return;
}

The following function (which is called from main) is only executed by the main thread:

void
RunServer (arg1, ...)
{
    // do some stuffs
    ...

    while (cond != true) {
        sleep(1);
    }

    server_exit();
}

Now, when the SIGUSR1 is caught (by any thread including the main thread), I'm setting the reload_dir variable to 1. And in RunServer(), I'm reloading the directory based on that value. However, I'm also resetting the global variable reload_dir to 0 to avoid loading the directory repeatedly indefinitely. And this setting reload_dir to 0 will introduce a race.

Since we should not use locks or mutex in a signal handler, how can I achieve this without majorly changing the existing application design.

void
RunServer (arg1, ...)
{
    // do some stuffs
    ...

    while (cond != true) {
        if (reload_dir) {
           // reset reload_dir to avoid loading repeatedly indefinitely
           reload_dir = 0;   // Race condition?
           dir_reinit();
        }
        sleep(1);
    }

    server_exit();
}

Body:
Block SIGUSR1 with pthread_sigmask before any threads are spawned, so that all threads inherit that mask.  Then, in main(), use sigtimedwait instead of sleep in your main loop to check if USR1 has been delivered.

int main(...) {
    ...

    sigset_t ss_usr1;
    sigemptyset(&ss_usr1);
    sigaddset(&ss_usr1, SIGUSR1);

    // block SIGUSR1
    pthread_sigmask(SIG_BLOCK, &ss_usr1, NULL);

    ... spawn threads ...

    // RunServer
    struct timespec patience = { .tv_sec = 1 };

    while (! some_condition) {
        int s = sigtimedwait(&ss_usr1, NULL, &patience);
        if (s == SIGUSR1) dir_reinit();
        // handle errors other than timeout appropriately
    }
    server_exit();

    ...
}

Benefits:  no signal handler complexity (and you won't be chastized, rightly, for using signal instead of the superior sigaction; no need for atomic flags or sig_atomic_t; easier to reason about behavior.


问:
How to use regular expressions inside C# MongoDB Driver aggregate pipeline
I would like to make a query in C# in MongoDB and show the result in a datagrid.
In my query method's pipeline I first want to filter year.
However, in my MongoDB database there is no value with the year only. I only got date values.
So my idea was to use a regular expression to filter the year out of the date value. The key for that date value is Bestelldatum.

I tried the following regular expression which I found in the MongoDB documentation but it is not working. It gives me an error ($regexMatch not recognized):

https://docs.mongodb.com/manual/reference/operator/aggregation/regexMatch/#exp._S_regexMatch

```<code>public List<T> MeistenHv<T>(string coll, string year)
    {
        /* Pipeline anlegen */
        //Alle Dokumente mit dem angegebenen Jahr
        var regex = new BsonDocument
        {
            {
                "$addFields", new BsonDocument
                {
                    { "results", new BsonDocument
                        {
                            {"$regexMatch", new BsonDocument
                                {
                                    { "input", "$Bestelldatum" },
                                    { "regex", year}
                                }
                            }
                        }
                    }

                }
            }
        };

        //Gruppiert nach Hv, bei jedem Treffer um 1 inkrementieren
        var group = new BsonDocument
        {
                { "$group", new BsonDocument
                           {
                                {"_id", new BsonDocument
                                        {
                                            {"Hv", "$Hv"}
                                        }
                                },
                                {"uniqueIds", new BsonDocument
                                        {
                                            {"$addToSet", "$_id"}
                                        }
                                },
                                {"count", new BsonDocument
                                        {
                                            {"$sum", 1 }
                                        }
                                }
                           }
                }
        };

        //Absteigend sortiert nach der Häufigkeit der Hv
        var sort = new BsonDocument
        {
            {
                "$sort", new BsonDocument
                {
                    {"count", -1 }
                }
            }
        };

        var pipeline = new[] { regex, group, sort };

        var collection = db.GetCollection<T>(coll);
        var data = collection.Aggregate<T>(pipeline).ToList();

        return data;
    }
</code>```

I also tried this with the same error:

```<code> var regex = new BsonDocument
        {
            {
               "$regex", new BsonDocument
               {
                   { "Bestelldatum", year}
               }
            }
        };
</code>```

EDIT: (included sampledoc json)

```<code>{
"_id" : ObjectId("5e31bb10c1b1e773e46be7f8"),
"LsNr" : "L1016",
"Bv" : "Blahblah",
"Hv" : "27292",
"Bauleiter" : "Jonathan Fakename",
"Projektleiter" : "Patrick NotMyRealName",
"Besteller" : "zuwenig auf Baustelle",
"Abholer" : "Herr Brown",
"Lagerort" : "Lager",
"Bemerkung" : null,
"Status" : "gebucht",
"Sachbearbeiter" : "",
"Abholdatum" : null,
"Beleg" : "L1016",
"Umsatz" : "39.39",
"Gegenkonto" : "5999",
"Buchungsdatum" : "22.08.2018",
"Konto" : "5150",
"Kost1" : null,
"Kost2" : "27292",
"Text" : "Blahblah",
"Bestelldatum" : "22.08.2018",
"Heute" : "29.01.2020",
"artikelliste" : [
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f4"),
        "Menge" : "1",
        "Bezeichnung" : "My great article",
        "Einheit" : "Eimer",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "2.91",
        "Gesamtpreis" : "29.1",
        "Mgkzswert" : "31.43",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    },
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f5"),
        "Menge" : "1",
        "Bezeichnung" : "What an awesome article",
        "Einheit" : "Stück",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "3.98",
        "Gesamtpreis" : "3.98",
        "Mgkzswert" : "4.3",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    },
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f6"),
        "Menge" : "1",
        "Bezeichnung" : "Great articles you have here man",
        "Einheit" : "Stück",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "1.69",
        "Gesamtpreis" : "1.69",
        "Mgkzswert" : "1.83",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    },
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f7"),
        "Menge" : "1",
        "Bezeichnung" : "Is it available in huge, too?",
        "Einheit" : "Stück",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "1.69",
        "Gesamtpreis" : "1.69",
        "Mgkzswert" : "1.83",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    }
]
</code>```

}

Here is my mapped model class:

```<code>    using System;
    using System.Windows;
    using Excel = Microsoft.Office.Interop.Excel;
    using Microsoft.Office.Interop.Excel;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Bson;

    namespace Lieferscheine.Models
    {
        public class

LieferscheinModel : INotifyPropertyChanged
    {
        //ATTRIBUTE
        [BsonRepresentation(BsonType.ObjectId)]
        public string _id;
        public string Bauleiter { get; set; }
        public string Projektleiter { get; set; }
        public string Besteller { get; set; }
        public string Abholer { get; set; }
        public string Lagerort { get; set; }
        public string Bemerkung { get; set; }
        //rechts
        public string Status { get; set; }
        public string Sachbearbeiter { get; set; }
        public string Abholdatum { get; set; }
        public string Buchungsdatum { get; set; }
        public string Konto { get; set; }
        public string Kost1 { get; set; }

        private ObservableCollection<ArtikelModel> _artikel = new ObservableCollection<ArtikelModel>();
        private string _heute = DateTime.Now.ToString("dd.MM.yyyy");
        private string _bestelldatum;

        //************************************************************************************
        //PROPERTIES
        private string _lsNr;
        public string LsNr
        {
            get
            {
                return _lsNr;
            }
            set
            {
                _lsNr = value;
                OnPropertyChanged("LsNr");
                Beleg = _lsNr;
            }
        }
        private string _text;
        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                OnPropertyChanged("Text");
            }
        }

        private string _hv;
        public string Hv
        {
            get { return _hv; }
            set
            {
                _hv = value;
                OnPropertyChanged("Hv");
                Kost2 = _hv;
            }
        }

        private string _bv;
        public string Bv
        {
            get { return _bv; }
            set
            {
                _bv = value;
                OnPropertyChanged("Bv");
                Text = _bv;
            }
        }

        private string _beleg;
        public string Beleg
        {
            get { return _beleg; }
            set
            {
                _beleg = value;
                OnPropertyChanged("Beleg");
            }
        }

        private string _gegenkonto = "5999";
        public string Gegenkonto
        {
            get { return _gegenkonto; }
            set
            {
                _gegenkonto = value;
                OnPropertyChanged("Gegenkonto");
            }
        }

        private decimal _umsatz = 0;

        public decimal Umsatz
        {
            get { return _umsatz; }
            set
            {
                _umsatz = value;
                OnPropertyChanged("Umsatz");
            }
        }

        private string _kost2;

        public string Kost2
        {
            get { return _kost2; }
            set
            {
                _kost2 = value;
                OnPropertyChanged("Kost2");
            }
        }

        public string Bestelldatum
        {
            get { return _bestelldatum; }
            set
            {
                _bestelldatum = value;
                OnPropertyChanged("Bestelldatum");
            }
        }
        public string Heute
        {
            get { return _heute; }
            set { _heute = value; } //private hinzufügen!
        }
        public ObservableCollection<ArtikelModel> artikelliste
        {
            get { return _artikel; }
            set
            {
                _artikel = value;
                OnPropertyChanged("artikelliste");
            }
        }

        // *******************************************************************************

        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public LieferscheinModel()
        {

        }
    }
}
</code>```

答:
you don't need regex to match the year. build your pipeline like this:

var collection = new MongoClient("mongodb://localhost")
                    .GetDatabase("test")
                    .GetCollection<BsonDocument>("LieferscheinModel");

var year = "2018";

PipelineStageDefinition<BsonDocument, BsonDocument> matchStage = $@"
{{
  $match: {{
    $expr: {{
      $eq: [
        {{
          $year: {{
            $toDate: ""$Bestelldatum""
          }}
        }},
        {year}
      ]
    }}
  }}
}}";

PipelineStageDefinition<BsonDocument, BsonDocument> groupStage = @"
{
  $group: {
    _id: ""$Hv"",
    uniqueIds: {
      $addToSet: ""$_id""
    },
    count: {
      $sum: 1
    }
  }
}";

PipelineStageDefinition<BsonDocument, BsonDocument> sortStage = @"
{
  $sort: {
    count: -1
  }
}";

var pipeline = new[] { matchStage, groupStage, sortStage };

var result = collection.Aggregate<BsonDocument>(pipeline).ToList();
```

Body:
I would like to make a query in C# in MongoDB and show the result in a datagrid.
In my query method's pipeline I first want to filter year.
However, in my MongoDB database there is no value with the year only. I only got date values.
So my idea was to use a regular expression to filter the year out of the date value. The key for that date value is Bestelldatum.

I tried the following regular expression which I found in the MongoDB documentation but it is not working. It gives me an error ($regexMatch not recognized):

https://docs.mongodb.com/manual/reference/operator/aggregation/regexMatch/#exp._S_regexMatch

public List<T> MeistenHv<T>(string coll, string year)
    {
        /* Pipeline anlegen */
        //Alle Dokumente mit dem angegebenen Jahr
        var regex = new BsonDocument
        {
            {
                "$addFields", new BsonDocument
                {
                    { "results", new BsonDocument
                        {
                            {"$regexMatch", new BsonDocument
                                {
                                    { "input", "$Bestelldatum" },
                                    { "regex", year}
                                }
                            }
                        }
                    }

                }
            }
        };

        //Gruppiert nach Hv, bei jedem Treffer um 1 inkrementieren
        var group = new BsonDocument
        {
                { "$group", new BsonDocument
                           {
                                {"_id", new BsonDocument
                                        {
                                            {"Hv", "$Hv"}
                                        }
                                },
                                {"uniqueIds", new BsonDocument
                                        {
                                            {"$addToSet", "$_id"}
                                        }
                                },
                                {"count", new BsonDocument
                                        {
                                            {"$sum", 1 }
                                        }
                                }
                           }
                }
        };

        //Absteigend sortiert nach der Häufigkeit der Hv
        var sort = new BsonDocument
        {
            {
                "$sort", new BsonDocument
                {
                    {"count", -1 }
                }
            }
        };

        var pipeline = new[] { regex, group, sort };

        var collection = db.GetCollection<T>(coll);
        var data = collection.Aggregate<T>(pipeline).ToList();

        return data;
    }

I also tried this with the same error:

 var regex = new BsonDocument
        {
            {
               "$regex", new BsonDocument
               {
                   { "Bestelldatum", year}
               }
            }
        };

EDIT: (included sampledoc json)

{
"_id" : ObjectId("5e31bb10c1b1e773e46be7f8"),
"LsNr" : "L1016",
"Bv" : "Blahblah",
"Hv" : "27292",
"Bauleiter" : "Jonathan Fakename",
"Projektleiter" : "Patrick NotMyRealName",
"Besteller" : "zuwenig auf Baustelle",
"Abholer" : "Herr Brown",
"Lagerort" : "Lager",
"Bemerkung" : null,
"Status" : "gebucht",
"Sachbearbeiter" : "",
"Abholdatum" : null,
"Beleg" : "L1016",
"Umsatz" : "39.39",
"Gegenkonto" : "5999",
"Buchungsdatum" : "22.08.2018",
"Konto" : "5150",
"Kost1" : null,
"Kost2" : "27292",
"Text" : "Blahblah",
"Bestelldatum" : "22.08.2018",
"Heute" : "29.01.2020",
"artikelliste" : [
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f4"),
        "Menge" : "1",
        "Bezeichnung" : "My great article",
        "Einheit" : "Eimer",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "2.91",
        "Gesamtpreis" : "29.1",
        "Mgkzswert" : "31.43",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    },
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f5"),
        "Menge" : "1",
        "Bezeichnung" : "What an awesome article",
        "Einheit" : "Stück",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "3.98",
        "Gesamtpreis" : "3.98",
        "Mgkzswert" : "4.3",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    },
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f6"),
        "Menge" : "1",
        "Bezeichnung" : "Great articles you have here man",
        "Einheit" : "Stück",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "1.69",
        "Gesamtpreis" : "1.69",
        "Mgkzswert" : "1.83",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    },
    {
        "_id" : ObjectId("5e31bb10c1b1e773e46be7f7"),
        "Menge" : "1",
        "Bezeichnung" : "Is it available in huge, too?",
        "Einheit" : "Stück",
        "Anforderungsgrund" : null,
        "Einzelpreis" : "1.69",
        "Gesamtpreis" : "1.69",
        "Mgkzswert" : "1.83",
        "Mgkzssatz" : "8",
        "LetztesUpdate" : "29.01.2020 18:04:16",
        "PersonUpdate" : "username",
        "Kommentar" : null
    }
]

}

Here is my mapped model class:

    using System;
    using System.Windows;
    using Excel = Microsoft.Office.Interop.Excel;
    using Microsoft.Office.Interop.Excel;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Bson;

    namespace Lieferscheine.Models
    {
        public class

LieferscheinModel : INotifyPropertyChanged
    {
        //ATTRIBUTE
        [BsonRepresentation(BsonType.ObjectId)]
        public string _id;
        public string Bauleiter { get; set; }
        public string Projektleiter { get; set; }
        public string Besteller { get; set; }
        public string Abholer { get; set; }
        public string Lagerort { get; set; }
        public string Bemerkung { get; set; }
        //rechts
        public string Status { get; set; }
        public string Sachbearbeiter { get; set; }
        public string Abholdatum { get; set; }
        public string Buchungsdatum { get; set; }
        public string Konto { get; set; }
        public string Kost1 { get; set; }

        private ObservableCollection<ArtikelModel> _artikel = new ObservableCollection<ArtikelModel>();
        private string _heute = DateTime.Now.ToString("dd.MM.yyyy");
        private string _bestelldatum;

        //************************************************************************************
        //PROPERTIES
        private string _lsNr;
        public string LsNr
        {
            get
            {
                return _lsNr;
            }
            set
            {
                _lsNr = value;
                OnPropertyChanged("LsNr");
                Beleg = _lsNr;
            }
        }
        private string _text;
        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                OnPropertyChanged("Text");
            }
        }

        private string _hv;
        public string Hv
        {
            get { return _hv; }
            set
            {
                _hv = value;
                OnPropertyChanged("Hv");
                Kost2 = _hv;
            }
        }

        private string _bv;
        public string Bv
        {
            get { return _bv; }
            set
            {
                _bv = value;
                OnPropertyChanged("Bv");
                Text = _bv;
            }
        }

        private string _beleg;
        public string Beleg
        {
            get { return _beleg; }
            set
            {
                _beleg = value;
                OnPropertyChanged("Beleg");
            }
        }

        private string _gegenkonto = "5999";
        public string Gegenkonto
        {
            get { return _gegenkonto; }
            set
            {
                _gegenkonto = value;
                OnPropertyChanged("Gegenkonto");
            }
        }

        private decimal _umsatz = 0;

        public decimal Umsatz
        {
            get { return _umsatz; }
            set
            {
                _umsatz = value;
                OnPropertyChanged("Umsatz");
            }
        }

        private string _kost2;

        public string Kost2
        {
            get { return _kost2; }
            set
            {
                _kost2 = value;
                OnPropertyChanged("Kost2");
            }
        }

        public string Bestelldatum
        {
            get { return _bestelldatum; }
            set
            {
                _bestelldatum = value;
                OnPropertyChanged("Bestelldatum");
            }
        }
        public string Heute
        {
            get { return _heute; }
            set { _heute = value; } //private hinzufügen!
        }
        public ObservableCollection<ArtikelModel> artikelliste
        {
            get { return _artikel; }
            set
            {
                _artikel = value;
                OnPropertyChanged("artikelliste");
            }
        }

        // *******************************************************************************

        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public LieferscheinModel()
        {

        }
    }
}


问:
Mozilla Firefox 68.2.0esr browser is crashing using GeckoDriver and Selenium
I was trying to launch Firefox browser through selenium, but unfortunately browser is getting closed immediately after it launches. I couldn't interpret from the log file.

Here are the log file entries:

```<code>1582121786461   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "-marionette" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofile.d4XupquDfaWC"
1582121787117   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: mozillaAddons
1582121787117   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: telemetry
1582121787118   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: resource://pdf.js/
1582121787118   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: about:reader*
JavaScript error: resource:///modules/sessionstore/SessionStore.jsm, line 1325: uncaught exception: 2147746065
1582121789421   Marionette      INFO    Listening on port 33105
1582121789488   Marionette      WARN    TLS certificate errors will be ignored for this session
19:46:29.537 INFO [ProtocolHandshake.createSession] - Detected dialect: W3C
19:46:29.559 INFO [RemoteSession$Factory.lambda$performHandshake$0] - Started new session 1420379c-5cc3-444a-8309-0492333a3c5f (org.openqa.selenium.firefox.GeckoDriverService)
1582121794637   Marionette      WARN    TimedPromise timed out after 5000 ms: stacktrace:
bail@chrome://marionette/content/sync.js:237:64
Fatal: no entropy gathering module detected
Redirecting call to abort() to mozalloc_abort

###!!! [Parent][MessageChannel] Error: (msgtype=0x1E008F,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

A content process crashed and MOZ_CRASHREPORTER_SHUTDOWN is set, shutting down
JavaScript error: resource:///modules/sessionstore/SessionFile.jsm, line 376: Error: _initWorker called too early! Please read the session file from disk first.
[Parent 423702, Gecko_IOThread] WARNING: pipe error (82): Connection reset by peer: file /home/abuild/rpmbuild/BUILD/firefox-68.2.0/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 358
1582121795636   Marionette      INFO    Stopped listening on port 33105
</code>```

Here are the versions of Browser/libraries:

Firefox version: 68.2.0esr

Geckodriver version: 0.24

Selenium version: 3.141.59

I have tried with different versions of Gecko driver and Selenium, but nothing worked. Please let me know any solution for this.

答:
This error message...

```<code>Fatal: no entropy gathering module detected
Redirecting call to abort() to mozalloc_abort
.
A content process crashed and MOZ_CRASHREPORTER_SHUTDOWN is set, shutting down
JavaScript error: resource:///modules/sessionstore/SessionFile.jsm, line 376:
Error: _initWorker called too early! Please read the session file from disk first.
[Parent 423702, Gecko_IOThread] WARNING: pipe error (82): Connection reset by peer: file /home/abuild/rpmbuild/BUILD/firefox-68.2.0/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
</code>```

...implies that a content process crashed while creating the session and there was a kernel panic.

Deep dive

A bit of more information with respect to your code trials and Trace level logs would have helped us to analyze the issue in a better way. However, this issue was earlier observed with 4.9.x kernels. At times this issue was also observed with corrupted urandom / random

However, it seems your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using GeckoDriver v0.24.0 of Jan 29, 2019, which is more then a year older.

You are using Firefox v68.2.0esr.

Your JDK version is unknown to us.

As per the documentation in Supported platforms there seems to be some mismatch among the binaries as Firefoxen section mentions:

Support is best in Firefox 57 and greater, although generally the more recent the Firefox version, the better the experience as they have more bug fixes and features. Some features will only be available in the most recent Firefox versions, and we strongly advise using the latest Firefox Nightly with geckodriver. Since Windows XP support in Firefox was dropped with Firefox 53, we do not support this platform.

Note: Starting with the 0.26.0 release geckodriver is able to connect to Android devices, and to control packages which are based on GeckoView (eg. Firefox Preview aka Fenix, or Firefox Reality). But it also still supports versions of Fennec up to 68 ESR, which is the last officially supported release from Mozilla.

Solution

Ensure that:

JDK is upgraded to current levels JDK 8u341.

Selenium is upgraded to current levels Version 3.141.59.

GeckoDriver is upgraded to GeckoDriver v0.26.0 level.

Firefox is upgraded to current Firefox v72.0 levels.

GeckoDriver is present in the desired location.

GeckoDriver is having executable permission for non-root users.

If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your Test as a non-root user.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Outro

As per best practices while working with GeckoDriver, Selenium and Firefox Browser follow the below compatibility chart:

Supported platforms

Body:
I was trying to launch Firefox browser through selenium, but unfortunately browser is getting closed immediately after it launches. I couldn't interpret from the log file.

Here are the log file entries:

1582121786461   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "-marionette" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofile.d4XupquDfaWC"
1582121787117   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: mozillaAddons
1582121787117   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: telemetry
1582121787118   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: resource://pdf.js/
1582121787118   addons.webextension.screenshots@mozilla.org     WARN    Loading extension 'screenshots@mozilla.org': Reading manifest: Invalid extension permission: about:reader*
JavaScript error: resource:///modules/sessionstore/SessionStore.jsm, line 1325: uncaught exception: 2147746065
1582121789421   Marionette      INFO    Listening on port 33105
1582121789488   Marionette      WARN    TLS certificate errors will be ignored for this session
19:46:29.537 INFO [ProtocolHandshake.createSession] - Detected dialect: W3C
19:46:29.559 INFO [RemoteSession$Factory.lambda$performHandshake$0] - Started new session 1420379c-5cc3-444a-8309-0492333a3c5f (org.openqa.selenium.firefox.GeckoDriverService)
1582121794637   Marionette      WARN    TimedPromise timed out after 5000 ms: stacktrace:
bail@chrome://marionette/content/sync.js:237:64
Fatal: no entropy gathering module detected
Redirecting call to abort() to mozalloc_abort

###!!! [Parent][MessageChannel] Error: (msgtype=0x1E008F,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

A content process crashed and MOZ_CRASHREPORTER_SHUTDOWN is set, shutting down
JavaScript error: resource:///modules/sessionstore/SessionFile.jsm, line 376: Error: _initWorker called too early! Please read the session file from disk first.
[Parent 423702, Gecko_IOThread] WARNING: pipe error (82): Connection reset by peer: file /home/abuild/rpmbuild/BUILD/firefox-68.2.0/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 358
1582121795636   Marionette      INFO    Stopped listening on port 33105

Here are the versions of Browser/libraries:

Firefox version: 68.2.0esr

Geckodriver version: 0.24

Selenium version: 3.141.59

I have tried with different versions of Gecko driver and Selenium, but nothing worked. Please let me know any solution for this.

Body:
This error message...

Fatal: no entropy gathering module detected
Redirecting call to abort() to mozalloc_abort
.
A content process crashed and MOZ_CRASHREPORTER_SHUTDOWN is set, shutting down
JavaScript error: resource:///modules/sessionstore/SessionFile.jsm, line 376:
Error: _initWorker called too early! Please read the session file from disk first.
[Parent 423702, Gecko_IOThread] WARNING: pipe error (82): Connection reset by peer: file /home/abuild/rpmbuild/BUILD/firefox-68.2.0/ipc/chromium/src/chrome/common/ipc_channel_posix.cc

...implies that a content process crashed while creating the session and there was a kernel panic.

Deep dive

A bit of more information with respect to your code trials and Trace level logs would have helped us to analyze the issue in a better way. However, this issue was earlier observed with 4.9.x kernels. At times this issue was also observed with corrupted urandom / random

However, it seems your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using GeckoDriver v0.24.0 of Jan 29, 2019, which is more then a year older.

You are using Firefox v68.2.0esr.

Your JDK version is unknown to us.

As per the documentation in Supported platforms there seems to be some mismatch among the binaries as Firefoxen section mentions:

Support is best in Firefox 57 and greater, although generally the more recent the Firefox version, the better the experience as they have more bug fixes and features. Some features will only be available in the most recent Firefox versions, and we strongly advise using the latest Firefox Nightly with geckodriver. Since Windows XP support in Firefox was dropped with Firefox 53, we do not support this platform.

Note: Starting with the 0.26.0 release geckodriver is able to connect to Android devices, and to control packages which are based on GeckoView (eg. Firefox Preview aka Fenix, or Firefox Reality). But it also still supports versions of Fennec up to 68 ESR, which is the last officially supported release from Mozilla.

Solution

Ensure that:

JDK is upgraded to current levels JDK 8u341.

Selenium is upgraded to current levels Version 3.141.59.

GeckoDriver is upgraded to GeckoDriver v0.26.0 level.

Firefox is upgraded to current Firefox v72.0 levels.

GeckoDriver is present in the desired location.

GeckoDriver is having executable permission for non-root users.

If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your Test as a non-root user.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Outro

As per best practices while working with GeckoDriver, Selenium and Firefox Browser follow the below compatibility chart:

Supported platforms


问:
GreenSock animation not working as expected
I'm trying to animate an intro page with an intro text and an arrow in the following sequence:

The background image is moved back and forth twice. After that, the arrow should scale from 1 to 1.5 and be rescaled again to the original size

The intro text should also be scaled to 1.5 and rescaled to its original size

For some reason, the arrow and text are scaled to 1.5 from the very start, how can I preserve the size for the arrow and the text while the background image inimation is still running?

Here is the code sofar:

```<code><html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <meta charset="utf-8">
    <style type="text/css">
        .intro-text {
            display: block;
            font-size: 16px !important;
            text-transform: uppercase;
            font-weight: bold;
            position: fixed;
            top: 50%;
            right: 140px;
            z-index: 99;
            color: red;
        }

        .intro-arrow {
            display: block;
            font-size: 16px !important;
            text-transform: uppercase;
            font-weight: bold;
            position: fixed;
            top: 45%;
            right: 70px;
            z-index: 99;
            color: white;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.1.1/gsap.min.js" crossorigin="anonymous"></script>
    <script>
            var tl = new TimelineMax();
            tl
            .fromTo("body", 0.5,  {x:-15}, {x:0})
            .fromTo("body", 0.5,  {x:-15}, {x:0})
            .fromTo('.intro-arrow', 0.5, {scale: 1},{scale: 1.5})
            .fromTo('.intro-arrow', 0.5, {scale: 1.5},{scale: 1})
            .fromTo('.intro-text', 0.5, {scale: 1}, {scale: 1.5})
            .fromTo('.intro-text', 0.5, {scale: 1.5}, {scale: 1})
    </script>
</head>

<body>
    <div class="container" style="height:100vh; background-image: url('http://rheinmainsport.de/images/news/boxcamp.png')">
        <div class="intro-text">Here some intro text</div>
            <div class="intro-arrow">
                <span class="SVGInline"><!--?xml version="1.0" encoding="UTF-8"?-->
                    <svg class="SVGInline-svg" width="59px" height="130px" viewBox="0 0 59 130" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                    <!-- Generator: Sketch 63.1 (92452) - https://sketch.com -->
                    <title>Fill-1</title>
                    <desc>Created with Sketch.</desc>
                        <g id="Main-Story" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                            <g id="Arrow" transform="translate(-166.000000, 0.000000)" fill="#ff0000" fill-rule="nonzero">
                                <g id="icon/arrow/x-large/white" transform="translate(166.000000, 0.000000)">
                                    <path d="M2.2131,130.025 L0.0001,128 L54.7241,68.21 C56.3381,66.446 56.3381,63.578 54.7241,61.815 L0.0001,2.025 L2.2131,0 L56.9371,59.789 C59.5731,62.669 59.5731,67.355 56.9371,70.235 L2.2131,130.025 Z" id="Fill-1"></path>
                                </g>
                            </g>
                        </g>
                    </svg>
                </span>
            </div>
    </div>
</body>
</html>
</code>```

On CodePen

https://codepen.io/gunther-von-goetzen-sanchez/pen/oNXzqgX

答:
This is because you're animating using .fromTo(). .from() and .fromTo()s by default have immediateRender set to true (because generally that's what people want). You can set immediateRender to false for the tweens that are causing the scaling issue.

Alternatively, just use .to() calls instead. Using repeat and yoyo could also make your job easier. How I'd write it in GSAP 3 format:

```<code>var tl = gsap.timeline();
tl
  .fromTo("body", {x: -15}, {x: 0, repeat: 1})
  .to('.intro-arrow', {scale: 1.5, repeat: 1, yoyo: true})
  .to('.intro-text', {scale: 1.5, repeat: 1, yoyo: true})
</code>```

The duration can be left out since 0.5 is the default in GSAP 3. If you want to change the duration for a tween, we recommend that you put it inside of the vars parameter, like duration: 1.

We highly recommend the Getting Started article as you can learn a lot of things similar to this :)

We also highly recommend the GreenSock forums because you'll be able to get quick, high quality help from experts in GSAP and web animation.

Body:
I'm trying to animate an intro page with an intro text and an arrow in the following sequence:

The background image is moved back and forth twice. After that, the arrow should scale from 1 to 1.5 and be rescaled again to the original size

The intro text should also be scaled to 1.5 and rescaled to its original size

For some reason, the arrow and text are scaled to 1.5 from the very start, how can I preserve the size for the arrow and the text while the background image inimation is still running?

Here is the code sofar:

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <meta charset="utf-8">

Here some intro text

                    <svg class="SVGInline-svg" width="59px" height="130px" viewBox="0 0 59 130" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

                    <title>Fill-1</title>
                    <desc>Created with Sketch.</desc>
                        <g id="Main-Story" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                            <g id="Arrow" transform="translate(-166.000000, 0.000000)" fill="#ff0000" fill-rule="nonzero">
                                <g id="icon/arrow/x-large/white" transform="translate(166.000000, 0.000000)">
                                    <path d="M2.2131,130.025 L0.0001,128 L54.7241,68.21 C56.3381,66.446 56.3381,63.578 54.7241,61.815 L0.0001,2.025 L2.2131,0 L56.9371,59.789 C59.5731,62.669 59.5731,67.355 56.9371,70.235 L2.2131,130.025 Z" id="Fill-1"></path>
                                </g>
                            </g>
                        </g>
                    </svg>

On CodePen

https://codepen.io/gunther-von-goetzen-sanchez/pen/oNXzqgX

Body:
This is because you're animating using .fromTo(). .from() and .fromTo()s by default have immediateRender set to true (because generally that's what people want). You can set immediateRender to false for the tweens that are causing the scaling issue.

Alternatively, just use .to() calls instead. Using repeat and yoyo could also make your job easier. How I'd write it in GSAP 3 format:

var tl = gsap.timeline();
tl
  .fromTo("body", {x: -15}, {x: 0, repeat: 1})
  .to('.intro-arrow', {scale: 1.5, repeat: 1, yoyo: true})
  .to('.intro-text', {scale: 1.5, repeat: 1, yoyo: true})

The duration can be left out since 0.5 is the default in GSAP 3. If you want to change the duration for a tween, we recommend that you put it inside of the vars parameter, like duration: 1.

We highly recommend the Getting Started article as you can learn a lot of things similar to this :)

We also highly recommend the GreenSock forums because you'll be able to get quick, high quality help from experts in GSAP and web animation.


问:
PowerShell string interpolation syntax
I always used the following syntax to be sure that variable were expanded in a string:

"my string with a $($variable)"

I recently ran into the following syntax:

"my string with a ${variable}"

Are they equivalent? Any difference?

答:
${variable} is the syntax for variable names that include special characters.

(See about_Variables -> Variable names that include special characters
)

Example:

```<code>${var with spaces} = "value"
"var with spaces: ${var with spaces}"
</code>```

So in your case it's basically the same as simply writing $variable

Title: PowerShell string interpolation syntax

Body:
${variable} is the syntax for variable names that include special characters.

(See about_Variables -> Variable names that include special characters
)

Example:

${var with spaces} = "value"
"var with spaces: ${var with spaces}"

So in your case it's basically the same as simply writing $variable


问:
Migrating Compute Engine activity logs to Cloud Audit logs - (Google Cloud)
We recently received an email from Google Cloud informing us of the upcoming shutdown of Compute Engine activity logs, and instructing us to migrate our logs to Cloud Audit logs.

After reading through the documentation, it was not completely clear to me how automatized this migration is...

I understood:

Cloud Audit Logs has 3 types of logs: Admin Activity, Data Access and System Events logs.

Admin Activity logs are automatically setup and free

Data Access must be setup and have a cost

Compute Engine instances have limited Data Access logs applicable: only ADMIN_READ, and DATA_READ (this one only applicable for instance.getSerialPortOutput logs)

My questions:

How do I setup System Events logs?

How do I check whether any of our current Compute Engine activity logs are to become Cloud Audit Data Access logs? (so I can know that I have to set them up)

Thank you!

答:
Have a look at the documentation System Event audit logs:

System Event audit logs are always written; you can't configure or
  disable them. There is no charge for your System Event audit logs.

Accordingly to the documentation Migrating from activity logs to audit logs:

Compute Engine activity logs are to be deprecated on Sep 30, 2020.
  Some activity log entries will be discontinued on June 1, 2020.

as result, it's better to migrate before deprecation date.

In addition, you can find in the migration guide that:

To use audit logs instead of activity logs, adjust your queries. Use
  the following steps:

Find your old queries. For example, you might have saved them in a
  saved search in the Logs Viewer or created a script using the API or
  SDK. For more information about how you can monitor your resources,
  see the Logging docs.

Replace the activity log fields with appropriate audit log fields.
  Refer to the table to see how the fields map to each other.

If some instructions or examples in the documentation aren't clear enough or not available for some particular features, or could be improved you can use press Send feedback button at the end of the page and ask for improvements.


问:
Filter array of objects by common properties
Is it possible in some way to filter let's say such an array of object arrays:

```<code>[[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]]
</code>```

To get array of objects which all arrays have the same property (id), so in this case it output will be:

```<code>[{id: 2}] // becasue this id is the same in all three subarrays
</code>```

I've only try intersectionBy from loadash but it seems to work in completely other way :/

Body:
Is it possible in some way to filter let's say such an array of object arrays:

[[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]]

To get array of objects which all arrays have the same property (id), so in this case it output will be:

[{id: 2}] // becasue this id is the same in all three subarrays

I've only try intersectionBy from loadash but it seems to work in completely other way :/

Body:
Using Ramda:

const input = [[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]];
R.intersection(...input);


问:
Jumping scrolling when switching fragments
Inside a ScrollView I am dynamically switching between two fragments with different heights.
Unfortunately that leads to jumping. One can see it in the following animation:

I am scrolling down until I reach the button "show yellow".

Pressing "show yellow" replaces a huge blue fragment with a tiny yellow fragment. When this happens, both buttons jump down to the end of the screen.

I want both buttons to stay at the same position when switching to the yellow fragment. How can that be done?

Source code available at https://github.com/wondering639/stack-dynamiccontent respectively https://github.com/wondering639/stack-dynamiccontent.git

Relevant code snippets:

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="800dp"
        android:background="@color/colorAccent"
        android:text="@string/long_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_fragment1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:text="show blue"
        app:layout_constraintEnd_toStartOf="@+id/button_fragment2"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_fragment2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="show yellow"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/button_fragment1"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/button_fragment2">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

MainActivity.kt

```<code>package com.example.dynamiccontent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // onClick handlers
        findViewById<Button>(R.id.button_fragment1).setOnClickListener {
            insertBlueFragment()
        }

        findViewById<Button>(R.id.button_fragment2).setOnClickListener {
            insertYellowFragment()
        }

        // by default show the blue fragment
        insertBlueFragment()
    }

    private fun insertYellowFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, YellowFragment())
        transaction.commit()
    }

    private fun insertBlueFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, BlueFragment())
        transaction.commit()
    }

}
</code>```

fragment_blue.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#0000ff"
tools:context=".BlueFragment" />
</code>```

fragment_yellow.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ffff00"
tools:context=".YellowFragment" />
</code>```

HINT

Please note that this is of course a minimum working example to show off my issue. In my real project, I also have views below the @+id/fragment_container. So giving a fixed size to @+id/fragment_container is not an option for me - it would cause a large blank area when switching to the low, yellow fragment.

UPDATE: Overview of proposed solutions

I implemented the proposed solutions for testing purposes and added my personal experiences with them.

answer by Cheticamp, https://stackoverflow.com/a/60323255

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60323255

-> FrameLayout wraps content, short code

answer by Pavneet_Singh, https://stackoverflow.com/a/60310807

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60310807

-> FrameLayout gets the size of the blue fragment. So no content wrapping. When switching to the yellow fragment, there's a gap between it and the content following it (if any content follows it). No additional rendering though!
** update ** a second version was provided showing how to do it without gaps. Check the comments to the answer.

answer by Ben P., https://stackoverflow.com/a/60251036

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60251036

-> FrameLayout wraps content. More code than the solution by Cheticamp. Touching the "show yellow" button twice leads to a "bug" (buttons jump down to the bottom, actually my original issue). One could argue about just disabling the "show yellow" button after switching to it, so I wouldn't consider this a real issue.

答:
A straightforward solution is to adjust the minimum height of the ConstraintLayout within the NestedScrollView before switching fragments. To prevent jumping, the height of the ConstraintLayout must be greater than or equal to

the amount by which the NestedScrollView has scrolled in the "y" direction

plus

the height of the NestedScrollView.

The following code encapsulates this concept:

```<code>private fun adjustMinHeight(nsv: NestedScrollView, layout: ConstraintLayout) {
    layout.minHeight = nsv.scrollY + nsv.height
}
</code>```

Please note that layout.minimumHeight will not work for ConstraintLayout. You must use layout.minHeight.

To invoke this function, do the following:

```<code>private fun insertYellowFragment() {
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, YellowFragment())
    transaction.commit()

    val nsv = findViewById<NestedScrollView>(R.id.myScrollView)
    val layout = findViewById<ConstraintLayout>(R.id.constraintLayout)
    adjustMinHeight(nsv, layout)
}
</code>```

It is similar for insertBlueFragment(). You can, of course, simplify this by doing findViewById() once.

Here is a quick video of the results.

In the video, I have added a text view at the bottom to represent additional items that may exist in your layout below the fragment. If you delete that text view, the code will still work, but your will see blank space at the bottom. Here is what that looks like:

And if the views below the fragment don't fill the scroll view, you will see the additional views plus white space at the bottom.

Body:
Inside a ScrollView I am dynamically switching between two fragments with different heights.
Unfortunately that leads to jumping. One can see it in the following animation:

I am scrolling down until I reach the button "show yellow".

Pressing "show yellow" replaces a huge blue fragment with a tiny yellow fragment. When this happens, both buttons jump down to the end of the screen.

I want both buttons to stay at the same position when switching to the yellow fragment. How can that be done?

Source code available at https://github.com/wondering639/stack-dynamiccontent respectively https://github.com/wondering639/stack-dynamiccontent.git

Relevant code snippets:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="800dp"
        android:background="@color/colorAccent"
        android:text="@string/long_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_fragment1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:text="show blue"
        app:layout_constraintEnd_toStartOf="@+id/button_fragment2"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_fragment2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="show yellow"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/button_fragment1"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/button_fragment2">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.example.dynamiccontent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // onClick handlers
        findViewById<Button>(R.id.button_fragment1).setOnClickListener {
            insertBlueFragment()
        }

        findViewById<Button>(R.id.button_fragment2).setOnClickListener {
            insertYellowFragment()
        }

        // by default show the blue fragment
        insertBlueFragment()
    }

    private fun insertYellowFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, YellowFragment())
        transaction.commit()
    }

    private fun insertBlueFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, BlueFragment())
        transaction.commit()
    }

}

fragment_blue.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#0000ff"
tools:context=".BlueFragment" />

fragment_yellow.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ffff00"
tools:context=".YellowFragment" />

HINT

Please note that this is of course a minimum working example to show off my issue. In my real project, I also have views below the @+id/fragment_container. So giving a fixed size to @+id/fragment_container is not an option for me - it would cause a large blank area when switching to the low, yellow fragment.

UPDATE: Overview of proposed solutions

I implemented the proposed solutions for testing purposes and added my personal experiences with them.

answer by Cheticamp, https://stackoverflow.com/a/60323255

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60323255

-> FrameLayout wraps content, short code

answer by Pavneet_Singh, https://stackoverflow.com/a/60310807

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60310807

-> FrameLayout gets the size of the blue fragment. So no content wrapping. When switching to the yellow fragment, there's a gap between it and the content following it (if any content follows it). No additional rendering though!
** update ** a second version was provided showing how to do it without gaps. Check the comments to the answer.

answer by Ben P., https://stackoverflow.com/a/60251036

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60251036

-> FrameLayout wraps content. More code than the solution by Cheticamp. Touching the "show yellow" button twice leads to a "bug" (buttons jump down to the bottom, actually my original issue). One could argue about just disabling the "show yellow" button after switching to it, so I wouldn't consider this a real issue.

Body:
A straightforward solution is to adjust the minimum height of the ConstraintLayout within the NestedScrollView before switching fragments. To prevent jumping, the height of the ConstraintLayout must be greater than or equal to

the amount by which the NestedScrollView has scrolled in the "y" direction

plus

the height of the NestedScrollView.

The following code encapsulates this concept:

private fun adjustMinHeight(nsv: NestedScrollView, layout: ConstraintLayout) {
    layout.minHeight = nsv.scrollY + nsv.height
}

Please note that layout.minimumHeight will not work for ConstraintLayout. You must use layout.minHeight.

To invoke this function, do the following:

private fun insertYellowFragment() {
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, YellowFragment())
    transaction.commit()

    val nsv = findViewById<NestedScrollView>(R.id.myScrollView)
    val layout = findViewById<ConstraintLayout>(R.id.constraintLayout)
    adjustMinHeight(nsv, layout)
}

It is similar for insertBlueFragment(). You can, of course, simplify this by doing findViewById() once.

Here is a quick video of the results.

In the video, I have added a text view at the bottom to represent additional items that may exist in your layout below the fragment. If you delete that text view, the code will still work, but your will see blank space at the bottom. Here is what that looks like:

And if the views below the fragment don't fill the scroll view, you will see the additional views plus white space at the bottom.


问:
Non-escaped select2 placeholder on multiple select
I think I understand how placeholders work regarding select2 library.

There is a thing bugging me for a while already, how to have non-escaped placeholder on multiple selects.

The reason is I like to place an icon at the placeholder.

Single selects uses an additional option tag and the property escapeMarkup at the select2 options object.

$('mySelector').select2({
    escapeMarkup: function(markup){
        return markup;
    }
});
```

Nothing of that is possible at multiple selects since the placeholder is placed at an input tag, so html markup is escaped and you get the  tag instead of the icon.

Is there a workarund for this?

答:
Taking your previous comment as a reference:

"the idea is to place a font awesome icon at the placeholder and
  preventing select2 from escaping it, and i'm getting the i tag instead
  of the icon"

...and if I understood correctly, you want to place a Font Awesome icon on the Placeholder of the Select2 element and keep it there, correct?

Check the following code where I'm inserting a DIV that contains a Font Awesome icon (the little airplane) and placing it on top of the Input used for searching. Even when you select different items from the Select (is a Multiple Select as you needed) the icon remains in the placeholder and also it has a text by default.

Remember to add the class="tab" in case you don't see the Icon.

$(document).ready(function(){
  $("#sel1").select2({
    placeholder: 'Search here...',
    allowClear: true
  });
$(".select2-search.select2-search--inline").prepend("

");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>select {
    width:300px;
    }
.multi {
    padding:10px;
 font-family: FontAwesome, "Open Sans", Verdana, sans-serif;
    font-style: normal;
    font-weight: 600;
    text-decoration: inherit;
}
.top {
    position: absolute;
    left: 0px; top:0px;
    }</code>```

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

  <link href="https://raw.githack.com/ttskch/select2-bootstrap4-theme/master/dist/select2-bootstrap4.css" rel="stylesheet">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<select class="multi fab" multiple placeholder="" data-allow-clear="1" id="sel1">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
</select>

```

Body:
I think I understand how placeholders work regarding select2 library.

There is a thing bugging me for a while already, how to have non-escaped placeholder on multiple selects.

The reason is I like to place an icon at the placeholder.

Single selects uses an additional option tag and the property escapeMarkup at the select2 options object.

$('mySelector').select2({
    escapeMarkup: function(markup){
        return markup;
    }
});

Nothing of that is possible at multiple selects since the placeholder is placed at an input tag, so html markup is escaped and you get the  tag instead of the icon.

Is there a workarund for this?

Body:
Taking your previous comment as a reference:

"the idea is to place a font awesome icon at the placeholder and
  preventing select2 from escaping it, and i'm getting the i tag instead
  of the icon"

...and if I understood correctly, you want to place a Font Awesome icon on the Placeholder of the Select2 element and keep it there, correct?

Check the following code where I'm inserting a DIV that contains a Font Awesome icon (the little airplane) and placing it on top of the Input used for searching. Even when you select different items from the Select (is a Multiple Select as you needed) the icon remains in the placeholder and also it has a text by default.

Remember to add the class="tab" in case you don't see the Icon.

$(document).ready(function(){
  $("#sel1").select2({
    placeholder: 'Search here...',
    allowClear: true
  });
$(".select2-search.select2-search--inline").prepend("<div class='fab'>&#xf374;</div>");
});

select {
    width:300px;
    }
.multi {
    padding:10px;
 font-family: FontAwesome, "Open Sans", Verdana, sans-serif;
    font-style: normal;
    font-weight: 600;
    text-decoration: inherit;
}
.top {
    position: absolute;
    left: 0px; top:0px;
    }

<html>
<head>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- select2 -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

  <!-- select2-bootstrap4-theme -->
  <link href="https://raw.githack.com/ttskch/select2-bootstrap4-theme/master/dist/select2-bootstrap4.css" rel="stylesheet"> <!-- for live demo page -->

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- select2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

</head>
<body>
<div class="container-fluid" style="width: 100%;">

<select class="multi fab" multiple placeholder="" data-allow-clear="1" id="sel1">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
</select>
</div>
<script>

</script>
</body>
</html>


问:
Is Java breaking its own rules with setter methods that have non-void return types?
I was given to understand that the standard convention was for setters not to return anything. However, the NIO.2 API has a few methods like setOwner, setLastModifiedTime and setAttribute that return Path instances. Are these methods not true setters, or else do not all setters have to have void return types?</p>

答:
A setter is usually used as an accessor method to change the state of an object. As Kayaman mentioned it can be useful to return the object itself to create a fluent api instead of void - see it as syntactical sugar, when working with these objects.

Nevertheless, in the NIO case, it is a static method of the class "Files" that changes the state of the Path that is given as first argument - so in this case it's no accessor but a "normal" method that has "set" in its name.


问:
PHP Post array empty on axios POST
I'm trying out Vue 2.0 and axios and I've got a little issue.
When I try to send a post request using axios to my post.php file the $_POST array is always empty.

Post function:

```<code>doPost: function() {
  console.log("post in progress")
  axios.post('api/post.php', {
      title: 'foo',
      body: 'bar',
      userId: 1
  })
  .then(response => {
    console.log(response)
    console.log(response.data)
    this.filter = response.data
  })
  .catch(e => {
    this.errors.push(e)
  })
}
</code>```

post.php

```<code><?php
header('Content-Type: application/x-www-form-urlencoded');

echo json_encode($_POST);
?>
</code>```

The request is completed with status 200 but returns an empty object "[]"

Note: when I change the post endpoint to jsonplaceholder tool it works fine.

答:
The data that is send with axios is not put into PHP's $_POST.
Instead, it is in the request body and most likely in json format.
To get it, try the following code:

function getRequestDataBody()
{
    $body = file_get_contents('php://input');

    if (empty($body)) {
        return [];
    }

    // Parse json body and notify when error occurs
    $data = json_decode($body, true);
    if (json_last_error()) {
        trigger_error(json_last_error_msg());
        return [];
    }

    return $data;
}

$data = getRequestDataBody();
var_dump($data)
```

Or you could use FormData like the other answer suggests.

Title: PHP Post array empty on axios POST

Body:
I'm trying out Vue 2.0 and axios and I've got a little issue.
When I try to send a post request using axios to my post.php file the $_POST array is always empty.

Post function:

doPost: function() {
  console.log("post in progress")
  axios.post('api/post.php', {
      title: 'foo',
      body: 'bar',
      userId: 1
  })
  .then(response => {
    console.log(response)
    console.log(response.data)
    this.filter = response.data
  })
  .catch(e => {
    this.errors.push(e)
  })
}

post.php

<?php
header('Content-Type: application/x-www-form-urlencoded');

echo json_encode($_POST);
?>

The request is completed with status 200 but returns an empty object "[]"

Note: when I change the post endpoint to jsonplaceholder tool it works fine.

Body:
The data that is send with axios is not put into PHP's $_POST.
Instead, it is in the request body and most likely in json format.
To get it, try the following code:

function getRequestDataBody()
{
    $body = file_get_contents('php://input');

    if (empty($body)) {
        return [];
    }

    // Parse json body and notify when error occurs
    $data = json_decode($body, true);
    if (json_last_error()) {
        trigger_error(json_last_error_msg());
        return [];
    }

    return $data;
}

$data = getRequestDataBody();
var_dump($data)

Or you could use FormData like the other answer suggests.