问:
Confused between whether or not to change the class_mode from binary to categorical in Imagedatagenerator
When i shifted from 2 classes to 4 classes in a CNN model. I got errors. A lot of people helped me solve them, like I needed to change loss to sparse_categorical_crossentropy and last layer activation function.

```<code>model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)
</code>```

I am confused as I had to change the loss function from binary_crossentropy to categorical_crossenpropy. I want to know whether I should change the class_mode from binary to categorical for 4 classes or should I leave it as binary.

```<code>train_datagen=ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip = True,
    #vertical_flip = True,
    validation_split=0.2,
    brightness_range=[0.5, 1.5]

)

#test_datagen = ImageDataGenerator(
 #   rescale=1./255,
 #
#)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width,img_height),
    batch_size=batch_size,
    shuffle=True,
    class_mode='binary',
    subset='training'
)

validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation'
    #validation_data_dir,
    #target_size=(img_width,img_height),
    #batch_size=batch_size,
    #class_mode='binary'
)
</code>```

答: Of course, you should change it. If you have only 2 classes use class_mode='binary' in flow_from_directory function and binary_crossentropy as loss. In case you have more than 2 classes, use class_mode='categorical' and categorical_crossentropy

Body:
When i shifted from 2 classes to 4 classes in a CNN model. I got errors. A lot of people helped me solve them, like I needed to change loss to sparse_categorical_crossentropy and last layer activation function.

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)

I am confused as I had to change the loss function from binary_crossentropy to categorical_crossenpropy. I want to know whether I should change the class_mode from binary to categorical for 4 classes or should I leave it as binary.

train_datagen=ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip = True,
    #vertical_flip = True,
    validation_split=0.2,
    brightness_range=[0.5, 1.5]

)

#test_datagen = ImageDataGenerator(
 #   rescale=1./255,
 #
#)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width,img_height),
    batch_size=batch_size,
    shuffle=True,
    class_mode='binary',
    subset='training'
)

validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation'
    #validation_data_dir,
    #target_size=(img_width,img_height),
    #batch_size=batch_size,
    #class_mode='binary'
)


来源: stackexchange

问:
How do I use random numbers to generate truly random results? ABS(CHECKSUM(NewID))) is not working
Each time I run a query I need different results.

If I

```<code>SELECT AccountNumber
FROM TABLE
</code>```

with no other specifications, the table returns the records in order of account number by default (i have no control over this).

My solution (I thought) was to

```<code>SELECT ABS(CHECKSUM(NewID())) [RandomNumber], AccountNumber
INTO #tempTABLE
FROM TABLE
ORDER BY [RandomNumber]
</code>```

So a whole new table gets built ordered by the randomly generated numbers. Then I could just

```<code>SELECT TOP 1 AccountNumber
FROM #tempTABLE
</code>```

What I'm finding is there is a very high probability that the lowest random number will correlate with the lowest accountnumber. In short, this random number strategy is giving the same results very frequently. I need the results of my query to be a different, randomly selected account number each time i run it.

答:
As a shortcut, you could simply order by a generated guid.</p>

```<code>SELECT TOP(1)
    AccountNumber
FROM
   TABLE
ORDER BY
    NewID()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Each time I run a query I need different results.

If I

SELECT AccountNumber
FROM TABLE

with no other specifications, the table returns the records in order of account number by default (i have no control over this).

My solution (I thought) was to

SELECT ABS(CHECKSUM(NewID())) [RandomNumber], AccountNumber
INTO #tempTABLE
FROM TABLE
ORDER BY [RandomNumber]

So a whole new table gets built ordered by the randomly generated numbers. Then I could just

SELECT TOP 1 AccountNumber
FROM #tempTABLE

What I'm finding is there is a very high probability that the lowest random number will correlate with the lowest accountnumber. In short, this random number strategy is giving the same results very frequently. I need the results of my query to be a different, randomly selected account number each time i run it.

Body:
As a shortcut, you could simply order by a generated guid.

SELECT TOP(1)
    AccountNumber
FROM
   TABLE
ORDER BY
    NewID()


问:
how to pass multiple values from Html Action Link control capturing from user entered text box and send to Action method?
I have the following View:

```<code><div class="form-group">
    @Html.LabelFor(m => m.LoginId, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.LoginId, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.LoginId, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        @Html.ActionLink("Log in", "Login1", null, new { @class = "link" })
    </div>
</div>
</code>```

And this the javascript:

```<code>$(function () {
    $('.link').click(function () {
        var loginid = $("#LoginId").val();
        var pass = $("#Password").val();
        this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
        this.href = this.href + '?password=' + encodeURIComponent(pass); // Something is going wrong here!
    });
});
</code>```

And this is the Controller Action method:

```<code>public ActionResult Login1(string loginid,string password)
{
    if (loginid == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    User user = db.Users.Find(loginid);
    if (user == null)
    {
        return HttpNotFound();
    }
    return RedirectToAction("Index", "Products");
}
</code>```

I have entered loginid=a and password=b.
But the problem is:it is sending the loginid =:a?password=b  and password=null.
How can I send the parameter properly?

答:
I think, and i'm no pro, that the error is in the ajax function. The '?' is causing the problem. Current is as follows:

```<code>this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
this.href = this.href + '?password=' + encodeURIComponent(pass);
</code>```

But should rather be:

```<code>this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
this.href = this.href + '&password=' + encodeURIComponent(pass);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following View:

    @Html.LabelFor(m => m.LoginId, new { @class = "col-md-2 control-label" })

        @Html.TextBoxFor(m => m.LoginId, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.LoginId, "", new { @class = "text-danger" })

    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

        @Html.ActionLink("Log in", "Login1", null, new { @class = "link" })

And this the javascript:

$(function () {
    $('.link').click(function () {
        var loginid = $("#LoginId").val();
        var pass = $("#Password").val();
        this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
        this.href = this.href + '?password=' + encodeURIComponent(pass); // Something is going wrong here!
    });
});

And this is the Controller Action method:

public ActionResult Login1(string loginid,string password)
{
    if (loginid == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    User user = db.Users.Find(loginid);
    if (user == null)
    {
        return HttpNotFound();
    }
    return RedirectToAction("Index", "Products");
}

I have entered loginid=a and password=b.
But the problem is:it is sending the loginid =:a?password=b  and password=null.
How can I send the parameter properly?

Body:
I think, and i'm no pro, that the error is in the ajax function. The '?' is causing the problem. Current is as follows:

this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
this.href = this.href + '?password=' + encodeURIComponent(pass);

But should rather be:

this.href = this.href + '?loginid=' + encodeURIComponent(loginid);
this.href = this.href + '&password=' + encodeURIComponent(pass);


问:
Program type already present: io.invertase.firebase.BuildConfig
Based on some googling, it seems that there is some overlap between 2 packages.  I've encountered a similar issue in the past and I think I was able to fix it with ./gradlew clean, but that isn't fixing my current issue.  Here's the error:

Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
    Program type already present: io.invertase.firebase.BuildConfig

I started encountering this issue as I was trying to get react-native-firebase wired up into my application.  Here are a few relevant dependencies in my package.json file:

```<code>"@react-native-firebase/app": "^6.0.3",
"@react-native-firebase/database": "^6.0.3",
"firebase-auth": "^0.1.2",
"react-native-firebase": "^5.5.6",
</code>```

Do I need to uninstall one of these packages or is it possible that I made a wireup mistake in a file like build.gradle, MainApplication.java?

答:
Another solution is to look for you react native error at yarn android / react-native run-android

```<code>error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:
  - @react-native-community/async-storage (to unlink run: "react-native unlink @react-native-community/async-storage")
  - @react-native-community/google-signin (to unlink run: "react-native unlink @react-native-community/google-signin")
  - @react-native-community/viewpager (to unlink run: "react-native unlink @react-native-community/viewpager")
  - react-native-blur-overlay (to unlink run: "react-native unlink react-native-blur-overlay")
  - react-native-date-picker (to unlink run: "react-native unlink react-native-date-picker")
  - react-native-extra-dimensions-android (to unlink run: "react-native unlink react-native-extra-dimensions-android")
  - react-native-fs (to unlink run: "react-native unlink react-native-fs")
  - react-native-gesture-handler (to unlink run: "react-native unlink react-native-gesture-handler")
  - react-native-linear-gradient (to unlink run: "react-native unlink react-native-linear-gradient")
  - react-native-push-notification (to unlink run: "react-native unlink react-native-push-notification")
  - react-native-svg (to unlink run: "react-native unlink react-native-svg")
  - react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")
  - rn-fetch-blob (to unlink run: "react-native unlink rn-fetch-blob")
</code>```

Just do the react-native unlink <specified-package> for all, it works for me cleared all the errors

but make sure some of them would break your functionality or ui

Body:
Based on some googling, it seems that there is some overlap between 2 packages.  I've encountered a similar issue in the past and I think I was able to fix it with ./gradlew clean, but that isn't fixing my current issue.  Here's the error:

Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
    Program type already present: io.invertase.firebase.BuildConfig

I started encountering this issue as I was trying to get react-native-firebase wired up into my application.  Here are a few relevant dependencies in my package.json file:

"@react-native-firebase/app": "^6.0.3",
"@react-native-firebase/database": "^6.0.3",
"firebase-auth": "^0.1.2",
"react-native-firebase": "^5.5.6",

Do I need to uninstall one of these packages or is it possible that I made a wireup mistake in a file like build.gradle, MainApplication.java?

Body:
Another solution is to look for you react native error at yarn android / react-native run-android

error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:
  - @react-native-community/async-storage (to unlink run: "react-native unlink @react-native-community/async-storage")
  - @react-native-community/google-signin (to unlink run: "react-native unlink @react-native-community/google-signin")
  - @react-native-community/viewpager (to unlink run: "react-native unlink @react-native-community/viewpager")
  - react-native-blur-overlay (to unlink run: "react-native unlink react-native-blur-overlay")
  - react-native-date-picker (to unlink run: "react-native unlink react-native-date-picker")
  - react-native-extra-dimensions-android (to unlink run: "react-native unlink react-native-extra-dimensions-android")
  - react-native-fs (to unlink run: "react-native unlink react-native-fs")
  - react-native-gesture-handler (to unlink run: "react-native unlink react-native-gesture-handler")
  - react-native-linear-gradient (to unlink run: "react-native unlink react-native-linear-gradient")
  - react-native-push-notification (to unlink run: "react-native unlink react-native-push-notification")
  - react-native-svg (to unlink run: "react-native unlink react-native-svg")
  - react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")
  - rn-fetch-blob (to unlink run: "react-native unlink rn-fetch-blob")

Just do the react-native unlink <specified-package> for all, it works for me cleared all the errors

but make sure some of them would break your functionality or ui


问:
Validation in jquery ,
```<code><div id="default-box">
    <span class="add"><input type="text" class="name" /><input type="text"  class="email"/></span>
    <span class="add"><input type="text" class="name" /><input type="text"  class="email"/></span>
    <span class="add"><input type="text" class="name" /><input type="text"  class="email"/></span>
</code>```

There is a button to submit.

```<code>validation:
</code>```

1. On these three row if any row is filled it is OK, if all three row is empty then it is invalid.

2. While writing emails if it is wrong it validates on loosing focus.

答:
You should at least give it a try.  Post your code.  Here is a head start. This will loop through the inputs.</p>

```<code>var $inputs = $('input');
for(var i = 0; i <= $inputs.length; ++i) {
   if($inputs[i].val() != "")
    return true;
}
</code>```

Title: Validation in jquery ,

Body:
    <input type="text" class="name" /><input type="text"  class="email"/>
    <input type="text" class="name" /><input type="text"  class="email"/>
    <input type="text" class="name" /><input type="text"  class="email"/>

There is a button to submit.

validation:

1. On these three row if any row is filled it is OK, if all three row is empty then it is invalid.

2. While writing emails if it is wrong it validates on loosing focus.

Body:
You should at least give it a try.  Post your code.  Here is a head start. This will loop through the inputs.

var $inputs = $('input');
for(var i = 0; i <= $inputs.length; ++i) {
   if($inputs[i].val() != "")
    return true;
}


问:
Get orders of a user with orderItems and product details in Laravel
I have 3 tables (foods, orders and orderItems). I want to get orders of a user with orderItems and foods, but i failed.

Here's a result what i am getting right now, but i need to get food details instead of food_id.

```<code>[
    {
        "id": 16,
        "user_id": 2,
        "total": "12.50",
        "items": [
            {
                "id": 20,
                "order_id": 16,
                "food_id": 1,
                "quantity": 1,
                "food_price": "12.50",
            }
        ]
    }
]
</code>```

OrderController

```<code>$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items')->get());
</code>```

User Model

```<code>public function deliveredOrders()
{
    return $this->hasMany(Order::class)->where('status', '=', 'delivered');
}
</code>```

Order Model

```<code>public function items()
    {
        return $this->hasMany(OrderItem::class);
    }
</code>```

答:
You should create this relationship in the OrderItem model

```<code>public function food()
{
   return $this->belongsTo('App\Food'); //or wherever you have the model
}
</code>```

and then get it

```<code>$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());
</code>```

Body:
I have 3 tables (foods, orders and orderItems). I want to get orders of a user with orderItems and foods, but i failed.

Here's a result what i am getting right now, but i need to get food details instead of food_id.

[
    {
        "id": 16,
        "user_id": 2,
        "total": "12.50",
        "items": [
            {
                "id": 20,
                "order_id": 16,
                "food_id": 1,
                "quantity": 1,
                "food_price": "12.50",
            }
        ]
    }
]

OrderController

$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items')->get());

User Model

public function deliveredOrders()
{
    return $this->hasMany(Order::class)->where('status', '=', 'delivered');
}

Order Model

public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

Body:
You should create this relationship in the OrderItem model

public function food()
{
   return $this->belongsTo('App\Food'); //or wherever you have the model
}

and then get it

$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());


问:
SSH key exchange
I have 2 servers with which I work: first one is application server and another one is archival server.
I access both of these servers using F-Secure SSH Client using the same user id and public-private key pair for authentication. It means that private key is stored on the Windows machine and public key is stored on both servers.

Now I need to access archival server from application server. To do that I have to do a key exchange first.

What is a standard aproach in this case? Do I just copy my private key from Windows to the application server? Would it compromise security? Or I need to generate a new key pare?

I appretiate your help!

P.S. I am relatively new to Unix administration, so don't be very hard on me :)

答:
@fyr's answer is correct, however you don't need to manually add or copy anything. You can do it with ssh-copy-id.

Assuming that the SSH server on your new machine is already running, from your old machine (which already has an SSH key pair, if not run ssh-keygen), run

```<code>ssh-copy-id -i ~/.ssh/mykey user@host
</code>```

where the -i parameter denotes the location of your public key. The ssh-copy-id tool will add the .pub extension if necessary, so it won't be trying to send your private key.

A real-world example of this, let's say to exchange keys with a Raspberry Pi, would be:

```<code>ssh-copy-id -i ~/.ssh/id_rsa pi@192.168.1.11
</code>```

This will ask for your password, but just once. If the key exchange is successful, you'll be able to ssh into it without needing a password.

Title: SSH key exchange

Body:
@fyr's answer is correct, however you don't need to manually add or copy anything. You can do it with ssh-copy-id.

Assuming that the SSH server on your new machine is already running, from your old machine (which already has an SSH key pair, if not run ssh-keygen), run

ssh-copy-id -i ~/.ssh/mykey user@host

where the -i parameter denotes the location of your public key. The ssh-copy-id tool will add the .pub extension if necessary, so it won't be trying to send your private key.

A real-world example of this, let's say to exchange keys with a Raspberry Pi, would be:

ssh-copy-id -i ~/.ssh/id_rsa pi@192.168.1.11

This will ask for your password, but just once. If the key exchange is successful, you'll be able to ssh into it without needing a password.


问:
GD Library doesn't work in PHP 7.4.6 on Windows
When i try using the GD Library in PHP 7.4.6 on my Windows PC, it shows me this error:

```<code>Fatal error: Uncaught Error: Call to undefined function imagecreate() in C:\Users\user\Desktop\Site\index.php:11 Stack trace: #0 {main} thrown in C:\Users\user\Desktop\Site\index.php on line 11
</code>```

The line 11 is:

```<code> $image = imagecreate(200,20);
</code>```

The full PHP code is:

```<code><?php

    $image = imagecreate(200,20);
    $background = imagecolorallocate($image,0,0,0);
    $foreground = imagecolorallocate($image, 255,255,255);

    $imagestring($image,5,5,1,"Test",$foreground);

    $header("Content-type: image/jpeg");
    $imagejpeg($image);

?>
</code>```

I tried fixing this by following this guide, and i uncommented the GD line, but it still gives me this error.

Thanks in advance.

答:
Try this code:

```<code><?php
phpinfo();
</code>```

Search for "GD Support" in the resulting output.  If you don't see it or it's not enabled, you need to enable gd in php.ini - search for:

```<code>;extension=php_gd2.dll
</code>```

Remove the comment in front of it, save the ini file, and restart IIS/Apache/Nginx/whatever server you're running.

Body:
When i try using the GD Library in PHP 7.4.6 on my Windows PC, it shows me this error:

Fatal error: Uncaught Error: Call to undefined function imagecreate() in C:\Users\user\Desktop\Site\index.php:11 Stack trace: #0 {main} thrown in C:\Users\user\Desktop\Site\index.php on line 11

The line 11 is:

 $image = imagecreate(200,20);

The full PHP code is:

<?php

    $image = imagecreate(200,20);
    $background = imagecolorallocate($image,0,0,0);
    $foreground = imagecolorallocate($image, 255,255,255);

    $imagestring($image,5,5,1,"Test",$foreground);

    $header("Content-type: image/jpeg");
    $imagejpeg($image);

?>

I tried fixing this by following this guide, and i uncommented the GD line, but it still gives me this error.

Thanks in advance.

Body:
Try this code:

<?php
phpinfo();

Search for "GD Support" in the resulting output.  If you don't see it or it's not enabled, you need to enable gd in php.ini - search for:

;extension=php_gd2.dll

Remove the comment in front of it, save the ini file, and restart IIS/Apache/Nginx/whatever server you're running.


问:
Perl: match against a large array
Say I have $sentence = "The quick brown fox jumps over the lazy dog" and an array @targets = qw(brown red black lazy quick);.

The goal is to find out all words in @targets that contains in the $sentence, in this case, it's this three words: brown lazy quick.

Note: The @targets array could be very large, like there could be 10,000 elements in it. And there could be 10,000 $sentences to deal with.

Is there an efficient and elegant way to do it?

答:
Using only pure perl

```<code>use strict;
use warnings;
use feature 'say';

my $sentence = "The quick brown fox jumps over the lazy dog";

my @targets   = qw/brown red black lazy quick/;
my $filter    = join('|',@targets);
my $re_filter = qr/\b($filter)\b/;

my @found = $sentence =~ /$re_filter/g;

say for @found;
</code>```

Output

```<code>quick
brown
lazy
</code>```

Title: Perl: match against a large array

Body:
Using only pure perl

use strict;
use warnings;
use feature 'say';

my $sentence = "The quick brown fox jumps over the lazy dog";

my @targets   = qw/brown red black lazy quick/;
my $filter    = join('|',@targets);
my $re_filter = qr/\b($filter)\b/;

my @found = $sentence =~ /$re_filter/g;

say for @found;

Output

quick
brown
lazy


问:
ObsoleteLintCustomCheck lint warning after upgrade to WorkManager 2.3.4
After upgrading WorkManager from 2.2.0 to 2.3.4, I get a new ObsoleteLintCustomCheck lint warning. If I understand the warning message right, then they added a new lint check that uses an old API version? Google doesn't show anything useful related to WorkManagerIssueRegistry though.

Anyone ran into this issue before or has an idea how to fix this?

In gradle:

```<code>implementation "androidx.work:work-runtime-ktx:2.3.4"
testImplementation "androidx.work:work-testing:2.3.4"
</code>```

```<code>Lint found an issue registry (`androidx.work.lint.WorkManagerIssueRegistry`) which is older than
the current API level; these checks may not work correctly. Recompile the checks against the
latest version. Custom check API version is 3 (3.3), current lint API level is 6 (3.6+)

Lint can be extended with "custom checks": additional checks implemented by
developers and libraries to for example enforce specific API usages required by a library or a
company coding style guideline. The Lint APIs are not yet stable, so these checks may either
cause a performance degradation, or stop working, or provide wrong results. This warning flags
custom lint checks that are found to be using obsolete APIs and will need to be updated to run
in the current lint environment. It may also flag issues found to be using a **newer** version
of the API, meaning that you need to use a newer version of lint (or Android Studio or Gradle
plugin etc) to work with these checks.
</code>```

答: You can ignore this. We fixed this in WorkManager 2.4.x. Sorry about the confusion.

Body:
After upgrading WorkManager from 2.2.0 to 2.3.4, I get a new ObsoleteLintCustomCheck lint warning. If I understand the warning message right, then they added a new lint check that uses an old API version? Google doesn't show anything useful related to WorkManagerIssueRegistry though.

Anyone ran into this issue before or has an idea how to fix this?

In gradle:

implementation "androidx.work:work-runtime-ktx:2.3.4"
testImplementation "androidx.work:work-testing:2.3.4"

Lint found an issue registry (`androidx.work.lint.WorkManagerIssueRegistry`) which is older than
the current API level; these checks may not work correctly. Recompile the checks against the
latest version. Custom check API version is 3 (3.3), current lint API level is 6 (3.6+)

Lint can be extended with "custom checks": additional checks implemented by
developers and libraries to for example enforce specific API usages required by a library or a
company coding style guideline. The Lint APIs are not yet stable, so these checks may either
cause a performance degradation, or stop working, or provide wrong results. This warning flags
custom lint checks that are found to be using obsolete APIs and will need to be updated to run
in the current lint environment. It may also flag issues found to be using a **newer** version
of the API, meaning that you need to use a newer version of lint (or Android Studio or Gradle
plugin etc) to work with these checks.


问:
ios 13.1 Cannot save file to App Directory
I was writing an app in ios 13 and saving my own filetype to the apps own directory folder. I could see this in the Files app, with my apps name and icon.

I have updated my ipad to ios 13.1 and cannot save or open any files.  If I open the Files app, my apps directory doesn't even exist. Why would this have changed? I have tried uninstalling the app, and reinstalling it.  I have checked my permissions were as before. It is like the main app directory is not being created, therefore any attempts to write to it do not succeed.

I am using this method to get the directory and save:

```<code>    let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let url = DocumentDirURL.appendingPathComponent(name).appendingPathExtension(fileExt)

    do {
            try jsonString!.write(to: url, atomically: true, encoding: String.Encoding.utf8)
            print(url.path)
        }
</code>```

I have checked my permissions in the Info.plist file and the 'supports opening documents' and the 'itunes file sharing' are both turned on,  along with my UTI File type info.

Does anybody know of any changes that may have caused this to act this way?  Do I manually need to create the documents folder for my files now?

答:
Have you tried to using the keys UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace equal to YES in your Info.plist file project?
This works for me.

Body:
I was writing an app in ios 13 and saving my own filetype to the apps own directory folder. I could see this in the Files app, with my apps name and icon.

I have updated my ipad to ios 13.1 and cannot save or open any files.  If I open the Files app, my apps directory doesn't even exist. Why would this have changed? I have tried uninstalling the app, and reinstalling it.  I have checked my permissions were as before. It is like the main app directory is not being created, therefore any attempts to write to it do not succeed.

I am using this method to get the directory and save:

    let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let url = DocumentDirURL.appendingPathComponent(name).appendingPathExtension(fileExt)

    do {
            try jsonString!.write(to: url, atomically: true, encoding: String.Encoding.utf8)
            print(url.path)
        }

I have checked my permissions in the Info.plist file and the 'supports opening documents' and the 'itunes file sharing' are both turned on,  along with my UTI File type info.

Does anybody know of any changes that may have caused this to act this way?  Do I manually need to create the documents folder for my files now?


问:
Is there a way to store in a PHP array the selected <option> from a HTML <select>?
My idea is to store in a PHP array the selected <option> from different html <select> ' s.

In a form I generate using a php function called from a Jquery function a
 containing each list element text and a <select>

Like so:

Part of the form where the list elements are added:

    Productos de este pedido:

```

<hr>

<h2>JQuery function that calls the PHP function:</h2>

<pre class="lang-js prettyprint-override"><code>$("#pedidos").on("input", function() {
    $.get("cambio_cliente.php", { idPedido: $("#pedidos").val()}, function (data) {
        $("#lineaPedidos").empty();
        $("#lineaPedidos").append(data);

        $("#asignarBdto").show();
        $("#lineaPedidos").show();
    });
});
</code>```

PHP function:

// Si llegamos a este script por haber seleccionado un pedido
if(isset($_GET["idPedido"])){
    // Abrimos una conexión con la BD y consultamos la lista de productos dado un pedido
    $conexion = crearConexionBD();
    $resultado = listarProductos($conexion, $_GET["idPedido"]);

    if($resultado != NULL){
        // Para cada producto del listado devuelto
        foreach($resultado as $lineaPedido) {
            //Listamos los productos de cada pedido
            echo "
" . $lineaPedido["NUM_LINEA_P"] .": cantidad= ". $lineaPedido["CANTIDAD"] .", importe= ". $lineaPedido["IMPORTE"] ."
Base de dto: <select class=\"linPed\" required><option value=\"\" hidden disabled selected>% DTO</option> <option value=\"21\">21%</option> <option value=\"16\">16%</option> <option value=\"8\">8%</option></select>
";
        }
    }
    // Cerramos la conexión y borramos de la sesión la variable "idPedido"
    cerrarConexionBD($conexion);
    unset($_GET["idPedido"]);
}
```

<hr>

<p>So far so good.</p>

<p>The form display this fields without problems:</p>

<p><img src="https://i.stack.imgur.com/D7bIU.jpg" alt="form alta factura"></p>

<hr>

<h1>The problem starts here</h1>

<p>I need to store each selected <code><option></code> into the array I mentioned in the very begining. I don't know how many <code><select></code> ' s will be created, so I can't create id's for each of them. I decided to create a class (linPed) for this selects, and tried this JS function:</p>

<pre class="lang-js prettyprint-override"><code>$(".linPed").on("input", function(){
   alert("all good");
});
</code>```

I first tried do some 'logging' to see if the function executes correctly, but doesn't show the alert.
Despite of that, even if the function executed correctly, how do I add in the array the selected .linPed value? Or maybe there is an easier way to do it?

EDIT 1:

alert("hello");
    $("select.linPed").on("change", function(){
       alert("this works");
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
    <div>
        <li>
            Hello
        </li>
        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>
    </div>
   <div>
        <li>
            bye
        </li>
        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>
    </div>
</ul>
<select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
</select></code>```

I have created an snippet testing if the problem was that the <select> 's were inside the
.

EDIT 2:

I still don't know why, but if I try to acces the <option> 's value from a separated script, doesn't work. I tried adding an onchange field to the <select>'s and finally works.

答:
Despite the fact I wouldn't have achieved the solution without Tim's answer, I want to post how have I stored the html values into the php array in case someone ecounters this same problem.

Using onchange inside the <select> field I call a js function (with parameters: the value of the selected option and the select id)

<select onchange="añadirDTO(this.value, this.id)">
   ...
</select>
```

<hr>

<h1>JS</h1>

<p>First of all, create 2 global variables that correspond to the parameters of the function, in this case array and number.</p>

<pre class="lang-js prettyprint-override"><code>var dtoSeleccionados = [];
var id = 0; //Initialize both var
</code>```

Now the function that receives the data:

This function will be called each time the user changes a select, so to avoid useless values an store only the final decision of each select, check if the id of the select passed as parameter is equal to the global id var. If it isn't we change the global id for the new id, else change the last element of the global array

function añadirDTO(baseDTO, linId){
    if(linId !== id){
        id = linId;
        dtoSeleccionados.push(baseDTO);
    }else{
        dtoSeleccionados[dtoSeleccionados.length - 1] = baseDTO;
    }
}
```

<p>Once the user has completed the form and the array values are definitives, using an auxiliar <code><select multiple></code> field that is hidden, we modify its inner html like so:</p>

<pre class="lang-html prettyprint-override"><code><div>
    <!-- we use a label to identify the element that it corresponds with the php var -->
    <label for="baseDTO" hidden></label>
    <!-- the name of the select must match with the php array name with '[]' at the end -->
    <select multiple name="baseDTO[]" id="baseDTO" hidden>

    </select>
</div>
</code>```

function seleccionarTodo(){
    text="";
    for(i=0; i<dtoSeleccionados.length; i++){
        text += "<option selected value=\""+dtoSeleccionados[i]+"\"></option>\n";
    }

    document.getElementById("baseDTO").innerHTML = text;
}
```

<p>The above function goes at the submit of the form like so:</p>

<pre class="lang-html prettyprint-override"><code><input type="submit" onclick="seleccionarTodo()" value="Registrar factura"/>
</code>```

And that succesfully add one by one different <select> <option> 's into an array

Body:
My idea is to store in a PHP array the selected <option> from different html <select> ' s.

In a form I generate using a php function called from a Jquery function a
 containing each list element text and a <select>

Like so:

Part of the form where the list elements are added:

    Productos de este pedido:

JQuery function that calls the PHP function:

$("#pedidos").on("input", function() {
    $.get("cambio_cliente.php", { idPedido: $("#pedidos").val()}, function (data) {
        $("#lineaPedidos").empty();
        $("#lineaPedidos").append(data);

        $("#asignarBdto").show();
        $("#lineaPedidos").show();
    });
});

PHP function:

// Si llegamos a este script por haber seleccionado un pedido
if(isset($_GET["idPedido"])){
    // Abrimos una conexión con la BD y consultamos la lista de productos dado un pedido
    $conexion = crearConexionBD();
    $resultado = listarProductos($conexion, $_GET["idPedido"]);

    if($resultado != NULL){
        // Para cada producto del listado devuelto
        foreach($resultado as $lineaPedido) {
            //Listamos los productos de cada pedido
            echo "
" . $lineaPedido["NUM_LINEA_P"] .": cantidad= ". $lineaPedido["CANTIDAD"] .", importe= ". $lineaPedido["IMPORTE"] ."
Base de dto: <select class=\"linPed\" required><option value=\"\" hidden disabled selected>% DTO</option> <option value=\"21\">21%</option> <option value=\"16\">16%</option> <option value=\"8\">8%</option></select>
";
        }
    }
    // Cerramos la conexión y borramos de la sesión la variable "idPedido"
    cerrarConexionBD($conexion);
    unset($_GET["idPedido"]);
}

So far so good.

The form display this fields without problems:

The problem starts here

I need to store each selected <option> into the array I mentioned in the very begining. I don't know how many <select> ' s will be created, so I can't create id's for each of them. I decided to create a class (linPed) for this selects, and tried this JS function:

$(".linPed").on("input", function(){
   alert("all good");
});

I first tried do some 'logging' to see if the function executes correctly, but doesn't show the alert.
Despite of that, even if the function executed correctly, how do I add in the array the selected .linPed value? Or maybe there is an easier way to do it?

EDIT 1:

alert("hello");
    $("select.linPed").on("change", function(){
       alert("this works");
    });

            Hello

        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>

            bye

        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>

<select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
</select>

I have created an snippet testing if the problem was that the <select> 's were inside the
.

EDIT 2:

I still don't know why, but if I try to acces the <option> 's value from a separated script, doesn't work. I tried adding an onchange field to the <select>'s and finally works.

Body:
Despite the fact I wouldn't have achieved the solution without Tim's answer, I want to post how have I stored the html values into the php array in case someone ecounters this same problem.

Using onchange inside the <select> field I call a js function (with parameters: the value of the selected option and the select id)

<select onchange="añadirDTO(this.value, this.id)">
   ...
</select>

JS

First of all, create 2 global variables that correspond to the parameters of the function, in this case array and number.

var dtoSeleccionados = [];
var id = 0; //Initialize both var

Now the function that receives the data:

This function will be called each time the user changes a select, so to avoid useless values an store only the final decision of each select, check if the id of the select passed as parameter is equal to the global id var. If it isn't we change the global id for the new id, else change the last element of the global array

function añadirDTO(baseDTO, linId){
    if(linId !== id){
        id = linId;
        dtoSeleccionados.push(baseDTO);
    }else{
        dtoSeleccionados[dtoSeleccionados.length - 1] = baseDTO;
    }
}

Once the user has completed the form and the array values are definitives, using an auxiliar <select multiple> field that is hidden, we modify its inner html like so:

<div>
    <!-- we use a label to identify the element that it corresponds with the php var -->
    <label for="baseDTO" hidden></label>
    <!-- the name of the select must match with the php array name with '[]' at the end -->
    <select multiple name="baseDTO[]" id="baseDTO" hidden>

    </select>
</div>

function seleccionarTodo(){
    text="";
    for(i=0; i<dtoSeleccionados.length; i++){
        text += "<option selected value=\""+dtoSeleccionados[i]+"\"></option>\n";
    }

    document.getElementById("baseDTO").innerHTML = text;
}

The above function goes at the submit of the form like so:

<input type="submit" onclick="seleccionarTodo()" value="Registrar factura"/>

And that succesfully add one by one different <select> <option> 's into an array


问:
Android Gradle Plugin 3.6 & 4.0 R8 not substituting src / main with src / test
I run Espresso tests using MockRetrofit to test UI flows in the app. The Espresso tests rely on swapping the production Dagger ApiModule located in src/main/java/com/my/app/ApiModule

```<code>@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        val apiRetrofit = retrofit.client(clientBuilder.build()).build()
        return apiRetrofit.create<RestApi>(RestApi::class.java)
    }
}
</code>```

with the fake ApiModule located in src/androidTest/java/com/my/app/ApiModule

```<code>@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        return MockApiModule.getApi(failureRate = FailureRate.NEVER, responseDelay = 500L)
    }
}
</code>```

I just upgraded to AGP 3.6 (and then to 4.0). The tests are still passing when running ./gradlew connectedDebugAndroidTest. But I also have a build configuration called debugMinified

```<code>buildTypes{
        ...

        debugMinified {
            minifyEnabled true
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules-testing.pro'
            signingConfig signingConfigs.debug
        }
    ...
}
</code>```

which I use to run Espresso tests with an obfuscated apk to catch Pro-guard related Runtime errors.

Now when I run ./gradlew connectedDebugMinifiedAndroidTest, my tests fail because AGP is not swapping the fake implementation in the androidTest src set, upon analysis of the apk. It's just using the real implementation in main. But again, this only happens for minified builds.

The above class ApiModule is one of 5 classes I swap out in this manner, when running UI tests. The other 4 have nothing to do with Dagger and are also not being swapped out, so I am relatively certain it's not just a Dagger issue.

This is currently blocking me from upgrading to AGP 4.0 so any help is greatly appreciated.

答:
After some trial and error I was able to resolve this issue simply by adding @Keep to all fake and real implementation class signatures

```<code>@Keep
@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        val apiRetrofit = retrofit.client(clientBuilder.build()).build()
        return apiRetrofit.create<RestApi>(RestApi::class.java)
    }
}
</code>```

```<code>@Keep
@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        return MockApiModule.getApi(failureRate = FailureRate.NEVER, responseDelay = 500L)
    }
}
</code>```

I'm still not sure why this works, or even why it's needed now. Just a lucky guess. Any further insight would be greatly appreciated.

Body:
I run Espresso tests using MockRetrofit to test UI flows in the app. The Espresso tests rely on swapping the production Dagger ApiModule located in src/main/java/com/my/app/ApiModule

@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        val apiRetrofit = retrofit.client(clientBuilder.build()).build()
        return apiRetrofit.create<RestApi>(RestApi::class.java)
    }
}

with the fake ApiModule located in src/androidTest/java/com/my/app/ApiModule

@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        return MockApiModule.getApi(failureRate = FailureRate.NEVER, responseDelay = 500L)
    }
}

I just upgraded to AGP 3.6 (and then to 4.0). The tests are still passing when running ./gradlew connectedDebugAndroidTest. But I also have a build configuration called debugMinified

buildTypes{
        ...

        debugMinified {
            minifyEnabled true
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules-testing.pro'
            signingConfig signingConfigs.debug
        }
    ...
}

which I use to run Espresso tests with an obfuscated apk to catch Pro-guard related Runtime errors.

Now when I run ./gradlew connectedDebugMinifiedAndroidTest, my tests fail because AGP is not swapping the fake implementation in the androidTest src set, upon analysis of the apk. It's just using the real implementation in main. But again, this only happens for minified builds.

The above class ApiModule is one of 5 classes I swap out in this manner, when running UI tests. The other 4 have nothing to do with Dagger and are also not being swapped out, so I am relatively certain it's not just a Dagger issue.

This is currently blocking me from upgrading to AGP 4.0 so any help is greatly appreciated.

Body:
After some trial and error I was able to resolve this issue simply by adding @Keep to all fake and real implementation class signatures

@Keep
@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        val apiRetrofit = retrofit.client(clientBuilder.build()).build()
        return apiRetrofit.create<RestApi>(RestApi::class.java)
    }
}

@Keep
@Module(includes = [NetworkModule::class])
class ApiModule {

    @Provides
    @Singleton
    fun restApi(
        retrofit: Retrofit.Builder,
        @DefaultClientBuilder clientBuilder: OkHttpClient.Builder
    ): RestApi {
        return MockApiModule.getApi(failureRate = FailureRate.NEVER, responseDelay = 500L)
    }
}

I'm still not sure why this works, or even why it's needed now. Just a lucky guess. Any further insight would be greatly appreciated.


问:
suggestion for improving my long python code with a shorter and correct version
As a part of an online exercise, I want to Write a function, persistence, that takes in a positive parameter num and returns its
multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:

persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.

persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.

persistence(4) => 0   # Because 4 is already a one-digit number.

This is my code:

```<code>def persistence(n):
    count=0
    if n<10:
        return(count)
    else:
        count+=1
        a=([int(d) for d in str(n)])
        result = 1
        for i in a:
            result=result*i
        if result<10:
            return(count)
        else:
            count+=1
            a=([int(d) for d in str(result)])
            result1 = 1
            for i in a:
                result1=result1*i
                if result1<10:
                    return(count)
                else:
                    count+=1
                    a=([int(d) for d in str(result1)])
                    result2=1
                    for i in a:
                        result2=result2*i
                        if result2<10:
                            return(count)
                        else:
                            count+=1
                            a=([int(d) for d in str(result1)])
                            result3=1
                            for i in a:
                                result3=result3*i
                                if result3<10:
                                    return(count)
</code>```

but when I try n=999 it gives me 2 which is incorrect. Also it is limited to only 4 multiplicative persistence. How can I improve this code. Tnx in advance!

答:
I found this short answer as well:</p>

```<code>import operator
def persistence(n):
    i = 0
    while n>=10:
        n=reduce(operator.mul,[int(x) for x in str(n)],1)
        i+=1
    return i
</code>```

Body:
As a part of an online exercise, I want to Write a function, persistence, that takes in a positive parameter num and returns its
multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:

persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.

persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.

persistence(4) => 0   # Because 4 is already a one-digit number.

This is my code:

def persistence(n):
    count=0
    if n<10:
        return(count)
    else:
        count+=1
        a=([int(d) for d in str(n)])
        result = 1
        for i in a:
            result=result*i
        if result<10:
            return(count)
        else:
            count+=1
            a=([int(d) for d in str(result)])
            result1 = 1
            for i in a:
                result1=result1*i
                if result1<10:
                    return(count)
                else:
                    count+=1
                    a=([int(d) for d in str(result1)])
                    result2=1
                    for i in a:
                        result2=result2*i
                        if result2<10:
                            return(count)
                        else:
                            count+=1
                            a=([int(d) for d in str(result1)])
                            result3=1
                            for i in a:
                                result3=result3*i
                                if result3<10:
                                    return(count)

but when I try n=999 it gives me 2 which is incorrect. Also it is limited to only 4 multiplicative persistence. How can I improve this code. Tnx in advance!

Body:
I found this short answer as well:

import operator
def persistence(n):
    i = 0
    while n>=10:
        n=reduce(operator.mul,[int(x) for x in str(n)],1)
        i+=1
    return i


问:
Differences between XMPP and Channel API for Google App Engine
I am developing an application that doesn't reside on AppEngine and having the functionality of a chat putting in communication web clients (browser + javascript) and mobile clients (ActionScript).
I'm thinking of using the XMPP protocol on AppEngine (then use only the servers for the chat feature on Google and still leave the rest on my server). You tell me if this is possible?
What are the differences with the Channel API?
Thanks</p>

答:
Channel API uses something called XPC to communicate to Google's GTalk client via an IFrame.  This client facilitates bi-directional communication between the browser and your App.  The JavaScript library that's provided for you, is loosely mapped to the current WebSocket's API and should ease transitioning from Channel API to WebSockets, once/if it's supported on AppEngine.

I believe that XMPP is the backbone for the Channel API and is a superset of features.  For example, the XMPP API has support for  Invitations

So, yes you can use the Channel API(browser) and XMPP(everywhere) to build chat features.


问:
How to delete all the documents in a firestore collection database
I use Firestore database to store and retrieve data.
Every night there need to be fresh data set (documents)available in the Firestore collection.
So is there any way to fully delete all the existing documents inside a collection at once.

I tried there documentation and it says we need to delete one by one which is impossible to do.
Because document ID is generating automatically.

Below is the code from documantaion.

```<code>var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});
</code>```

So is there any way to delete entire documents on a given fire base collection?

I tried with above code  and I got below error.

```<code>(index):63 Uncaught ReferenceError: Firestore is not defined
    at myFunction ((index):63)
    at HTMLParagraphElement.onclick ((index):57)
</code>```

Below is my code:

```<code><p id="demo" onclick="myFunction()">Click me.</p>

<script>

function myFunction() {

describe("firestore", () => {
    var db;
    before(() => {
        var config = {
            apiKey: "xxxx",
            aauthDomain: "xxxxfirebaseapp.com",
            projectId: "xxx",
        };
        var app = firebase.initializeApp(config);
        db = firebase.firestore(app);
        //firebase.firestore.setLogLevel("debug");
    });

db.collection('Headings').get().then(querySnapshot => {
    querySnapshot.docs.forEach(snapshot => {
        snapshot.ref.delete();
    })
})
}
</script>
</code>```

答:
The documentation is correct: you have to delete the documents individually.  It's not impossible - you just have to query for all the documents first, then delete each one.  For example:</p>

```<code>db.collection('cities').get().then(querySnapshot => {
    querySnapshot.docs.forEach(snapshot => {
        snapshot.ref.delete();
    })
})
</code>```

Body:
I use Firestore database to store and retrieve data.
Every night there need to be fresh data set (documents)available in the Firestore collection.
So is there any way to fully delete all the existing documents inside a collection at once.

I tried there documentation and it says we need to delete one by one which is impossible to do.
Because document ID is generating automatically.

Below is the code from documantaion.

var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});

So is there any way to delete entire documents on a given fire base collection?

I tried with above code  and I got below error.

(index):63 Uncaught ReferenceError: Firestore is not defined
    at myFunction ((index):63)
    at HTMLParagraphElement.onclick ((index):57)

Below is my code:

Click me.

Body:
The documentation is correct: you have to delete the documents individually.  It's not impossible - you just have to query for all the documents first, then delete each one.  For example:

db.collection('cities').get().then(querySnapshot => {
    querySnapshot.docs.forEach(snapshot => {
        snapshot.ref.delete();
    })
})


问:
Animation translate doesn't work properly
I wanna make a drop animation when the page loads similar to a working example I've seen at someone else but mine doesn't. The image doesn't drop at all, does not transition from 0 opacity to 1 opacity. It just suddenly appears after the given duration. Help me, please.</p>

```<code>.cover img{
    height: 60vh;
    filter: drop-shadow(1px 5px 3px black);
    position: relative;
    left: 60px;
    animation: drop 1.5s ease;
}
@keyframes drop{
    0% {
        opacity: 0%;
        transform: translateY(-80px);
    }

    100% {
        opacity: 1%;
        transform: translateY(0px);
    }
}
</code>```

答:
What I think you've done wrong is used a percentage in the opacity. You just need the number.

```<code>@keyframes drop {
    0% {
        opacity: 0;
        transform: translateY(-80px);
    }
    100% {
        opacity: 1;
        transform: translateY(0px);
    }
}
</code>```

Does this help?

Body:
I wanna make a drop animation when the page loads similar to a working example I've seen at someone else but mine doesn't. The image doesn't drop at all, does not transition from 0 opacity to 1 opacity. It just suddenly appears after the given duration. Help me, please.

.cover img{
    height: 60vh;
    filter: drop-shadow(1px 5px 3px black);
    position: relative;
    left: 60px;
    animation: drop 1.5s ease;
}
@keyframes drop{
    0% {
        opacity: 0%;
        transform: translateY(-80px);
    }

    100% {
        opacity: 1%;
        transform: translateY(0px);
    }
}

Body:
What I think you've done wrong is used a percentage in the opacity. You just need the number.

@keyframes drop {
    0% {
        opacity: 0;
        transform: translateY(-80px);
    }
    100% {
        opacity: 1;
        transform: translateY(0px);
    }
}

Does this help?


问:
how to Concatenate various strings in php with null effect
I have four php variables like: $abc, $bcd, $dsf, $gkg. Now I want to concatenate them with a comma separating each.

output:

```<code>abc,bcd,dsf,gkg
</code>```

Now if any of the variable does not return any value.. then the output is coming like this:

```<code>abc,,dsf,gkg
</code>```

So what to do to avoid this if value of any variable is null??

```<code>$street = tribe_get_address( $event->ID );
$city = tribe_get_city( $event->ID );
$state = tribe_get_stateprovince($event->ID);
$country = tribe_get_country( $event->ID );
$zipcode = tribe_get_zip( $event->ID );
$fulladdress= concatenation of these variables..
</code>```

答:
could help:

```<code>function concat_ws(){
    $ar=func_get_args();
    return implode(array_shift($ar), array_filter($ar)) ;
}
echo concat_ws(" - ", "hello", "", null, "world");
</code>```

return : hello - world

Body:
I have four php variables like: $abc, $bcd, $dsf, $gkg. Now I want to concatenate them with a comma separating each.

output:

abc,bcd,dsf,gkg

Now if any of the variable does not return any value.. then the output is coming like this:

abc,,dsf,gkg

So what to do to avoid this if value of any variable is null??

$street = tribe_get_address( $event->ID );
$city = tribe_get_city( $event->ID );
$state = tribe_get_stateprovince($event->ID);
$country = tribe_get_country( $event->ID );
$zipcode = tribe_get_zip( $event->ID );
$fulladdress= concatenation of these variables..

Body:
could help:

function concat_ws(){
    $ar=func_get_args();
    return implode(array_shift($ar), array_filter($ar)) ;
}
echo concat_ws(" - ", "hello", "", null, "world");

return : hello - world


问:
How to set layouts instead of text in RadioButton
Normally Radio Buttons, you can have text along with them, is there a possibility to add a layout instead of text as shown in figure below?

P.S:

I have kept all the radio buttons in a radio group. Just for this layout sake, i don't want to create a separate linear layout along the radio group.

答:
This answer maybe overkill but you can create a custom view, i put together what you have with the following

custom_radio_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <RadioButton
        android:id="@+id/radioButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="For one hour"
        app:layout_constraintBottom_toBottomOf="@+id/radioButton"
        app:layout_constraintStart_toEndOf="@+id/radioButton"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="Until 9:08pm"
        app:layout_constraintBottom_toBottomOf="@+id/radioButton"
        app:layout_constraintStart_toEndOf="@+id/radioButton"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button"
        style="@style/Widget.AppCompat.Light.ActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        style="@style/Widget.AppCompat.Light.ActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="12dp"
        android:text="-"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent" />

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

RadioCustomLayout.kt

```<code>class RadioCustomLayout: ConstraintLayout {
    constructor(context: Context?): super(context)
    constructor(context: Context?, attrs: AttributeSet?): super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr)

    init {
        inflate(context, R.layout.custom_radio_view, this)
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.test.test.RadioCustomLayout
        android:id="@+id/group1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
</code>```

With a few declare-styleable and callbacks you could create a fully re-usable layout, rather than a radio-group

Body:
This answer maybe overkill but you can create a custom view, i put together what you have with the following

custom_radio_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

    <RadioButton
        android:id="@+id/radioButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="For one hour"
        app:layout_constraintBottom_toBottomOf="@+id/radioButton"
        app:layout_constraintStart_toEndOf="@+id/radioButton"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:text="Until 9:08pm"
        app:layout_constraintBottom_toBottomOf="@+id/radioButton"
        app:layout_constraintStart_toEndOf="@+id/radioButton"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button"
        style="@style/Widget.AppCompat.Light.ActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        style="@style/Widget.AppCompat.Light.ActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="12dp"
        android:text="-"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

RadioCustomLayout.kt

class RadioCustomLayout: ConstraintLayout {
    constructor(context: Context?): super(context)
    constructor(context: Context?, attrs: AttributeSet?): super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr)

    init {
        inflate(context, R.layout.custom_radio_view, this)
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.test.test.RadioCustomLayout
        android:id="@+id/group1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

With a few declare-styleable and callbacks you could create a fully re-usable layout, rather than a radio-group


问:
Use map(v, reduce) to create Fibonacci sequence in R?
I was wondering if we could use purrr's map and reduce to create to Fibonacci function akin to this one in JavaScript:

```<code>function fib(n){
  return new Array(n).fill(1).reduce((arr, _ ,i) => {
    arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
    return arr
  },[]) ;
}
console.log(fib(10))
</code>```

I see answers here Fibonacci Sequence in R that use recursion but I was wondering if we could specifically use purrr's reduce and if so how?

答:
I think purrr::accumulate() is better suited for the task:

```<code>n <- 10                                         # Desired number of values
purrr::accumulate( .init = c(0L,1L),            # Starting with (0,1)
                   rep(0,n),                    # Accumulate n times
                   ~c(.x,sum(.x))[2:3]          # (x,y) -> (x, y, x+y)[2:3]
                 ) %>%
    purrr::map_int( `[`, 1 )                    # (x,y) -> x

# [1]  0  1  1  2  3  5  8 13 21 34 55
</code>```

The key to this solution is to keep pairs of values throughout the accumulate() call: (0,1), (1,1), (1,2), etc., since you need two previous values to compute the new one.

This is followed by retrieving the first element of each pair.

Body:
I was wondering if we could use purrr's map and reduce to create to Fibonacci function akin to this one in JavaScript:

function fib(n){
  return new Array(n).fill(1).reduce((arr, _ ,i) => {
    arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
    return arr
  },[]) ;
}
console.log(fib(10))

I see answers here Fibonacci Sequence in R that use recursion but I was wondering if we could specifically use purrr's reduce and if so how?

Body:
I think purrr::accumulate() is better suited for the task:

n <- 10                                         # Desired number of values
purrr::accumulate( .init = c(0L,1L),            # Starting with (0,1)
                   rep(0,n),                    # Accumulate n times
                   ~c(.x,sum(.x))[2:3]          # (x,y) -> (x, y, x+y)[2:3]
                 ) %>%
    purrr::map_int( `[`, 1 )                    # (x,y) -> x

# [1]  0  1  1  2  3  5  8 13 21 34 55

The key to this solution is to keep pairs of values throughout the accumulate() call: (0,1), (1,1), (1,2), etc., since you need two previous values to compute the new one.

This is followed by retrieving the first element of each pair.


问:
Why does a nested loop perform much faster than the flattened one?
UPDATE

Sorry guys but the pervious number is INACCURATE. When I tested the previous code I used tqdm to see the expected time and the function will hurt the performance when the iterable object is very long. So I get 18.22s, which is 9 times longer than 2.43s.

HOWEVER, the conclusion is CONSISTENT: The nested loop is much FASTER. When the iteration time is 100^5, the difference is significant: 321.49 vs 210.05. There is about 1.53-time gap between them. Generally, we don't face this kind of long iteration, I'm just curious to know reason of the anomalistic situation.

My python version is 3.7.3. I use 13-inch MacBookPro2019 with 2.4 GHz Intel Core i5. The OS is macOS Mojave 10.14.6

I found a weird situation in python as follows:

import time

start = time.time()
# flattened loop
for i in range(100**4):
    pass
print(time.time() - start) # 18.22(Wrong! Should be 3.09)

# nested loop
start = time.time()
for i in range(100):
    for j in range(100):
        for k in range(100):
            for l in range(100):
                pass
print(time.time() - start) # 2.43
```

The two kinds of loops above have the same iteration times. However the nested loop(2.43s) is running much faster that the flattened one(18.22s). The difference is bigger with the increasing of the iteration time. Hoes does this happen?

答:
I did run the script you provided with both python 2.x and 3.x multiple times. It did surprise me too that nested loop constantly completed faster. Here is what is think that what causes this issue:

When you run your python script operating system you are running on will assign a PID for it.It can be interrupted by system calls and its priority can be changed over time. But system is not likely to take resources away from a process when you change memory addresses or values. When you run flat for loop it is assigning (also i tried them assignment statement ones they have much more close results!) much less variables than nested loop. So we can say that nested loop utilizes resources more than flat loop if they are available. If they are not (Try them in constrained docker containers) flat loop will be faster.

Body:
UPDATE

Sorry guys but the pervious number is INACCURATE. When I tested the previous code I used tqdm to see the expected time and the function will hurt the performance when the iterable object is very long. So I get 18.22s, which is 9 times longer than 2.43s.

HOWEVER, the conclusion is CONSISTENT: The nested loop is much FASTER. When the iteration time is 100^5, the difference is significant: 321.49 vs 210.05. There is about 1.53-time gap between them. Generally, we don't face this kind of long iteration, I'm just curious to know reason of the anomalistic situation.

My python version is 3.7.3. I use 13-inch MacBookPro2019 with 2.4 GHz Intel Core i5. The OS is macOS Mojave 10.14.6

I found a weird situation in python as follows:

import time

start = time.time()
# flattened loop
for i in range(100**4):
    pass
print(time.time() - start) # 18.22(Wrong! Should be 3.09)

# nested loop
start = time.time()
for i in range(100):
    for j in range(100):
        for k in range(100):
            for l in range(100):
                pass
print(time.time() - start) # 2.43

The two kinds of loops above have the same iteration times. However the nested loop(2.43s) is running much faster that the flattened one(18.22s). The difference is bigger with the increasing of the iteration time. Hoes does this happen?


问:
What algorithms there are for failover in a distributed system?
I'm planning on making a distributed database system using a shared-nothing architecture and multiversion concurrency control. Redundancy will be achieved through asynchronous replication (it's allowed to lose some recent changes in case of a failure, as long as the data in the system remains consistent). For each database entry, one node has the master copy (only that node has write access to it), in addition to which one or more nodes have secondary copies of the entry for scalability and redundancy purposes (the secondary copies are read-only). When the master copy of an entry is updated, it is timestamped and sent asynchronously to nodes with secondary copies so that finally they will get the latest version of the entry. The node that has the master copy can change at any time - if another node needs to write that entry, it will request the current owner of the master copy to give that node the ownership of that entry's master copy, and after receiving ownership that node can write the entry (all transactions and writes are local).

Lately I've been thinking about what to do when a node in the cluster goes down, that what strategy to use for failover. Here are some questions. I hope that you would know available alternatives to at least some of them.

What algorithms there are for doing failover in a distributed system?

What algorithms there are for consensus in a distributed system?

How should the nodes in the cluster determine that a node is down?

How should the nodes determine that what database entries had their master copy on the failed node at the time of failure, so that other nodes may recover those entries?

How to decide that which node(s) has the latest secondary copy of some entry?

How to decide that which node's secondary copy should be promoted to be the new master copy?

How to handle it, if the node which was though to be down, suddenly comes back as if nothing happened?

How to avoid split-brain scenarios, where the network is temporarily split into two, and both sides think that the other side has died?

答:
You are asking an absolutely massive question, and a lot of what you want to know is still in active research.

Some thoughts:

Distributed systems are difficult, because there are no foolproof  systems to deal with failures;  in an asynchronous system, there is no way to be sure that a node is down or whether there is network delay.  This may sound trivial, but it really isn't.

Achieving consensus can be done by the Paxos family of algorithms, versions of which are used in Google's bigtable, and in other places.

You'll want to delve into a distributed systems textbook (or several).  I like Tannenbaum's Distributed Systems: Principles and Paradigms

OwnerDisplayName: Esko Luontola

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Esko Luontola

OwnerDisplayName: Rob


问:
pandas clients table >> add edges to a nodes column and deltatimes
I have a data table I would like to create a graph. (see data example for pasting at the end)
For that I would like to create the nodes and the edges.
Every client go through different process states.
The edges connect two states (nodes)
My aim is to get the edges as shown in the excel table screenshot and the delta time of every time change.

My code:
First I sorted the table by client and by timestamp (i.e. the nodes (states) go from t1 to t2 to t3 ... where t1

```<code>estados=estados.sort_values(['CLIENT', 'timestamp'], ascending=[True, True])
</code>```

And now follows a 20% pythonic code and 0% pandonic code:

```<code>edges_column = []
delta_column = []
for client in list_of_clients:
    client_df = estados.loc[estados['CLIENT'] == client,['node','timestamp']]
    client_nodes      = client_df['node']
    client_timestamps = client_df['timestamp']
    list_edges        = [node1 + '-' + node2 for node1,node2 in  zip(client_nodes[:-1],client_nodes[1:])]
    list_delta_times  = [t2 -t1 for t1,t2 in  zip(client_timestamps[:-1],client_timestamps[1:])]
    print(list_edges)
    print(list_delta_times)
    # adding ['-'] because if there are n nodes there are n-1 edges. the same for delta times
    edges_column = edges_column + list_edges + ['-']
    delta_column = delta_column + list_delta_times + ['-']

# adding the columns edges_column and delta_column
print(len(edges_column))
estados['edge']      = edges_column
estados['deltatime'] = delta_column
</code>```

This code works but it is far from ideal.
This should be a pretty common problem. I need a more efficient code because I have half a million rows and it should run in a reasonable time.

I am looking for a function to create the columns edge and timestamp
I can not come to such a solution because the function is referring to values out of two different rows and not only to ony, in such a case I could do something like

```<code>estados['edge'] = estados['node'].apply(function)
</code>```

because I have to pass two values not only one.

Is there at all a way without using for loops?

thx.

the table is in pandas format:

NOTE1 for copy and paste JSON file: {"CLIENT":{"0":"client1","1":"client1","2":"client1","3":"client1","4":"client2","5":"client2","6":"client2","7":"client3","8":"client4","9":"client4","10":"client4","11":"client4","12":"client4","13":"client4"},"node":{"0":"A","1":"B","2":"C","3":"H","4":"B","5":"F","6":"G","7":"C","8":"D","9":"E","10":"F","11":"H","12":"G","13":"K"},"timestamp":{"0":1590684862000,"1":1590771262270,"2":1590857662000,"3":1590598462000,"4":1590425662000,"5":1590512062000,"6":1590598462000,"7":1590771262270,"8":1588352062000,"9":1588524862000,"10":1588611262000,"11":1588697662000,"12":1588956862000,"13":1589043262000}}

Body:
I have a data table I would like to create a graph. (see data example for pasting at the end)
For that I would like to create the nodes and the edges.
Every client go through different process states.
The edges connect two states (nodes)
My aim is to get the edges as shown in the excel table screenshot and the delta time of every time change.

My code:
First I sorted the table by client and by timestamp (i.e. the nodes (states) go from t1 to t2 to t3 ... where t1

estados=estados.sort_values(['CLIENT', 'timestamp'], ascending=[True, True])

And now follows a 20% pythonic code and 0% pandonic code:

edges_column = []
delta_column = []
for client in list_of_clients:
    client_df = estados.loc[estados['CLIENT'] == client,['node','timestamp']]
    client_nodes      = client_df['node']
    client_timestamps = client_df['timestamp']
    list_edges        = [node1 + '-' + node2 for node1,node2 in  zip(client_nodes[:-1],client_nodes[1:])]
    list_delta_times  = [t2 -t1 for t1,t2 in  zip(client_timestamps[:-1],client_timestamps[1:])]
    print(list_edges)
    print(list_delta_times)
    # adding ['-'] because if there are n nodes there are n-1 edges. the same for delta times
    edges_column = edges_column + list_edges + ['-']
    delta_column = delta_column + list_delta_times + ['-']

# adding the columns edges_column and delta_column
print(len(edges_column))
estados['edge']      = edges_column
estados['deltatime'] = delta_column

This code works but it is far from ideal.
This should be a pretty common problem. I need a more efficient code because I have half a million rows and it should run in a reasonable time.

I am looking for a function to create the columns edge and timestamp
I can not come to such a solution because the function is referring to values out of two different rows and not only to ony, in such a case I could do something like

estados['edge'] = estados['node'].apply(function)

because I have to pass two values not only one.

Is there at all a way without using for loops?

thx.

the table is in pandas format:

NOTE1 for copy and paste JSON file: {"CLIENT":{"0":"client1","1":"client1","2":"client1","3":"client1","4":"client2","5":"client2","6":"client2","7":"client3","8":"client4","9":"client4","10":"client4","11":"client4","12":"client4","13":"client4"},"node":{"0":"A","1":"B","2":"C","3":"H","4":"B","5":"F","6":"G","7":"C","8":"D","9":"E","10":"F","11":"H","12":"G","13":"K"},"timestamp":{"0":1590684862000,"1":1590771262270,"2":1590857662000,"3":1590598462000,"4":1590425662000,"5":1590512062000,"6":1590598462000,"7":1590771262270,"8":1588352062000,"9":1588524862000,"10":1588611262000,"11":1588697662000,"12":1588956862000,"13":1589043262000}}

Body:
You can use df.shift with pd.Series.str.cat here.

df['result'] = df.groupby('CLIENT').node.shift(1).str.cat(df.node,'-')
df

     CLIENT node      timestamp result
0   client1    A  1590684862000    NaN
1   client1    B  1590771262270    A-B
2   client1    C  1590857662000    B-C
3   client1    H  1590598462000    C-H
4   client2    B  1590425662000    NaN
5   client2    F  1590512062000    B-F
6   client2    G  1590598462000    F-G
7   client3    C  1590771262270    NaN
8   client4    D  1588352062000    NaN
9   client4    E  1588524862000    D-E
10  client4    F  1588611262000    E-F
11  client4    H  1588697662000    F-H
12  client4    G  1588956862000    H-G
13  client4    K  1589043262000    G-K


问:
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
I'm having xcode issues when I try to use brew and git:

xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist, use xcode-select --switch path/to/Xcode.app to specify the Xcode that you wish to use for command line developer tools (or see man xcode-select)

I can type xcode-select and it shows that the command exists. When I type xcode-select -p it shows:

/Applications/Xcode.app/Contents/Developer

but when I do which xcode-select, it gives me:

/usr/bin/xcode-select

I've tried to use the command switch and install again via Apple Developer site but none of these options have work so far... How can I fix this?

答:
Try error suggestion :

```<code>sudo xcode-select --switch /Applications/Xcode.app
</code>```

And Then test Git Executable Path.

Body:
Try error suggestion :

sudo xcode-select --switch /Applications/Xcode.app

And Then test Git Executable Path.


问:
react appjs triggering before useeffect router
i have a problem how can i trigger my useeffect method in my appjs file before the router

first of all what can i do to have useeffect trigger in app js

Appjs File

```<code>import GlobalContext from "./context/globalContext";
import Routers from "./router/index"
function App() {
    const {initAuth} = useContext(GlobalContext)
    alert("appjs")
    useEffect(() => {
        alert("appJS Use Effect")
        initAuth()
    }, [])
    return (
        <React.Fragment>
                <Routers/>
        </React.Fragment>
    );
}
export default App;

</code>```

My Router

```<code>export default function Routers() {
    alert("RoutersJS")
    useEffect(()=>{
        alert("useEffect RouterJS")
    },[])
    return (
        <Router>
             ....
       </Router>

    )
}

</code>```

答:
Yousaf is correct that you cannot do this directly, or change the order of rendering. If there's a side-effect that absolutely must be sequenced correctly between the two elements, you could create a prop to router that tells it when it's allowed to make it's side-effect.

This introduces a lot of coupling between these elements, and I wouldn't recommend it unless you absolutely need these two elements to have a side-effect that must be sequenced.

```<code>function App() {
    ...
    const [hasAlerted, setHasAlerted] = useState(false);
    useEffect(() => {
        alert("appJS Use Effect");
        initAuth();
        setHasAlerted(true);
    }, [])
    return (
        <React.Fragment>
                <Routers canAlert={hasAlerted} />
        </React.Fragment>
    );
}

export default function Routers({canAlert})) {
    useEffect(()=>{
        if (canAlert) {
            alert("useEffect RouterJS")
        }
    },[canAlert])
    return (
        <Router>
             ....
       </Router>

    )
}
</code>```

Quick Explanation

On the first render, hasAlerted will be false. The App will alert on after the first render. We will pass canAlert=false to the Routers component, so it will not alert on the first render.

Because we setHasAlerted(true) the tree will render again. On the 2nd render, hasAlerted will be true. The App will not alert, because it's useEffect dependencies have not changed. We will pass canAlert=true to the Routers component, so it will alert on the second render.

Again, I'd probably explore other solutions if you're able to.

Body:
i have a problem how can i trigger my useeffect method in my appjs file before the router

first of all what can i do to have useeffect trigger in app js

Appjs File

import GlobalContext from "./context/globalContext";
import Routers from "./router/index"
function App() {
    const {initAuth} = useContext(GlobalContext)
    alert("appjs")
    useEffect(() => {
        alert("appJS Use Effect")
        initAuth()
    }, [])
    return (
        <React.Fragment>
                <Routers/>
        </React.Fragment>
    );
}
export default App;

My Router

export default function Routers() {
    alert("RoutersJS")
    useEffect(()=>{
        alert("useEffect RouterJS")
    },[])
    return (
        <Router>
             ....
       </Router>

    )
}

Body:
Yousaf is correct that you cannot do this directly, or change the order of rendering. If there's a side-effect that absolutely must be sequenced correctly between the two elements, you could create a prop to router that tells it when it's allowed to make it's side-effect.

This introduces a lot of coupling between these elements, and I wouldn't recommend it unless you absolutely need these two elements to have a side-effect that must be sequenced.

function App() {
    ...
    const [hasAlerted, setHasAlerted] = useState(false);
    useEffect(() => {
        alert("appJS Use Effect");
        initAuth();
        setHasAlerted(true);
    }, [])
    return (
        <React.Fragment>
                <Routers canAlert={hasAlerted} />
        </React.Fragment>
    );
}

export default function Routers({canAlert})) {
    useEffect(()=>{
        if (canAlert) {
            alert("useEffect RouterJS")
        }
    },[canAlert])
    return (
        <Router>
             ....
       </Router>

    )
}

Quick Explanation

On the first render, hasAlerted will be false. The App will alert on after the first render. We will pass canAlert=false to the Routers component, so it will not alert on the first render.

Because we setHasAlerted(true) the tree will render again. On the 2nd render, hasAlerted will be true. The App will not alert, because it's useEffect dependencies have not changed. We will pass canAlert=true to the Routers component, so it will alert on the second render.

Again, I'd probably explore other solutions if you're able to.


问:
Cluster/blob detection
I come from cell biology world so please excuse my lack of knowledge beforehand.

I primarily use ImageJ for image processing in which we fit a 2D-Gaussian to detect clusters/blobs/puncta. See image below, for example.

I am trying to implement a similar pipeline in python and came across opencv. I'm using simple blob detector and it works well for nicely isolated clusters and not so well where multiple clusters are clustered together. Below, left image is raw image and right is after tresholding.

My detector is contouring a "multi-cluster" cluster as a single cluster. Is there a way to segment these multi-cluster clusters more intelligently? Ideally, I'd like to use the same 2D-Gaussian, but am open to anything at this point?

答:
Try contour detection and see if it works.

```<code>contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
out = image.copy()
out = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

for c in contours:
    cv2.polylines(out,[c],True,(255,0,0),1)
</code>```

Title: Cluster/blob detection

Body:
Try contour detection and see if it works.

contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
out = image.copy()
out = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

for c in contours:
    cv2.polylines(out,[c],True,(255,0,0),1)


问:
Python loop through list of csv and check for value?
I have five .csv's that have the same fields in the same order that need to be processed as such:

Get list of files

Make each file into a dataframe

Check if a column of letter-number combinations has a specific value (different for each file) eg: check if the number PT333 is in column1 for the file name data1:

```<code>column1   column2    column3
PT389     LA       image.jpg
PT372     NY       image2.jpg
</code>```

If the column has a specific value, print which value it has and the filename/variable name that i've assigned to that file, and then rename that dataframe to output1

I tried to do this, but I don't know how to make it loop and do the same thing for each file.
At the moment it returns the number, but I also want it to return the data frame name, and I also want it to loop through all the files (a to e) to check for all the values in the numbers list.

This is what I have:

```<code>import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

data = glob.glob('data*.csv')
data

# If you have tips on how to loop through these rather than
# have a line for each one, open to feedback
a = pd.read_csv(data[0], encoding='ISO-8859-1', error_bad_lines=False)
b = pd.read_csv(data[1], encoding='ISO-8859-1', error_bad_lines=False)
c = pd.read_csv(data[2], encoding='ISO-8859-1', error_bad_lines=False)
d = pd.read_csv(data[3], encoding='ISO-8859-1', error_bad_lines=False)
e = pd.read_csv(data[4], encoding='ISO-8859-1', error_bad_lines=False)
filenames = [a,b,c,d,e]
filelist= ['a','b','c','d','e']

# I am aware that this part is repetitive. Unsure how to fix this,
# I keep getting errors
# Any help appreciated
numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']
def type():
    for i in a.column1:
        if i == numbers[0]:
            print(numbers[0])
        elif i == numbers[1]:
            print(numbers[1])
        elif i == numbers[2]:
            print(numbers[2])
        elif i == numbers[3]:
            print(numbers[3])
        elif i == numbers[4]:
            print(numbers[4])
type()
</code>```

Also happy to take any constructive criticism as to how to repeat less code and make things smoother. TIA

答:
I would suggest changing the type function, and calling it slightly differently</p>

```<code>    def type(x):
        for i in x.column1:
            if i == numbers[0]:
                print(i, numbers[0])
            elif i == numbers[1]:
                print(i, numbers[1])
            elif i == numbers[2]:
                print(i, numbers[2])
            elif i == numbers[3]:
                print(i, numbers[3])
            elif i == numbers[4]:
                print(i, numbers[4])

    for j in filenames:
            type(j)
</code>```

Body:
I have five .csv's that have the same fields in the same order that need to be processed as such:

Get list of files

Make each file into a dataframe

Check if a column of letter-number combinations has a specific value (different for each file) eg: check if the number PT333 is in column1 for the file name data1:

column1   column2    column3
PT389     LA       image.jpg
PT372     NY       image2.jpg

If the column has a specific value, print which value it has and the filename/variable name that i've assigned to that file, and then rename that dataframe to output1

I tried to do this, but I don't know how to make it loop and do the same thing for each file.
At the moment it returns the number, but I also want it to return the data frame name, and I also want it to loop through all the files (a to e) to check for all the values in the numbers list.

This is what I have:

import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

data = glob.glob('data*.csv')
data

# If you have tips on how to loop through these rather than
# have a line for each one, open to feedback
a = pd.read_csv(data[0], encoding='ISO-8859-1', error_bad_lines=False)
b = pd.read_csv(data[1], encoding='ISO-8859-1', error_bad_lines=False)
c = pd.read_csv(data[2], encoding='ISO-8859-1', error_bad_lines=False)
d = pd.read_csv(data[3], encoding='ISO-8859-1', error_bad_lines=False)
e = pd.read_csv(data[4], encoding='ISO-8859-1', error_bad_lines=False)
filenames = [a,b,c,d,e]
filelist= ['a','b','c','d','e']

# I am aware that this part is repetitive. Unsure how to fix this,
# I keep getting errors
# Any help appreciated
numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']
def type():
    for i in a.column1:
        if i == numbers[0]:
            print(numbers[0])
        elif i == numbers[1]:
            print(numbers[1])
        elif i == numbers[2]:
            print(numbers[2])
        elif i == numbers[3]:
            print(numbers[3])
        elif i == numbers[4]:
            print(numbers[4])
type()

Also happy to take any constructive criticism as to how to repeat less code and make things smoother. TIA

Body:
I would suggest changing the type function, and calling it slightly differently

    def type(x):
        for i in x.column1:
            if i == numbers[0]:
                print(i, numbers[0])
            elif i == numbers[1]:
                print(i, numbers[1])
            elif i == numbers[2]:
                print(i, numbers[2])
            elif i == numbers[3]:
                print(i, numbers[3])
            elif i == numbers[4]:
                print(i, numbers[4])

    for j in filenames:
            type(j)


问:
jBPM DMN: Error compiling Java function * on node *: Error resolving external function as defined by
I am using the jBPM Business Central to create DMN rules for my project. In the DMN rule, I am invoking an external java function to perform certain actions. Once the DMN is modeled in Business central, I download it and include it to my project resources and execute the DMN with the drools DMN engine.

Here is decision that invokes the java function

And the Business central validation error

Is there any way to include the dependency for the java function in Business central? Because of this build error, I couldn't create tests for the DMN in business central. Can someone help me?

答:
You can use your project's Settings page to add the maven dependency:

Make sure you have the dependency installed first in Business Central maven repository.

For instance you can navigate to Admin (upper right clog icon) > Artifacts to upload manually your dependency:

If your project worked anyway using Drools DMN engine APIs managing correctly the dependency in the Maven pom.xml of your local project, and you were only looking to have the error cleared while modelling on Business Central, this should solve your issue. However in this case you might want to consider using the Kogito DMN editor, if the actual project is not meant to be built/run with Business Central.