问:
database firebase: when reading, there is no output
I'm trying to read the value from firebase realtime database, but there is no output.

```<code>var text = login;
    var encoded = btoa(text);
    const db = firebase.database();
    const func1 = db.ref('users/' + encoded + '/money');
    func1.on('value', (snapshot) => {
      var data = snapshot.val();
      console.log(data);
      document.getElementById('some-h1').innerHTML="<h1 class=\"summary\" id=\"some-h1\">" + data + "</h1>";
    }, (errorObject) => {
        console.log('The read failed: ' + errorObject.name);
      });
</code>```

As I said, there is no output, when the code is executed.

I'll be really thankful, if someone will reply with the solution.

I was trying to set the value of key from my database to be set as text, and I was expecting to show but there is nothing.

Body:
I'm trying to read the value from firebase realtime database, but there is no output.

var text = login;
    var encoded = btoa(text);
    const db = firebase.database();
    const func1 = db.ref('users/' + encoded + '/money');
    func1.on('value', (snapshot) => {
      var data = snapshot.val();
      console.log(data);
      document.getElementById('some-h1').innerHTML="
" + data + "
";
    }, (errorObject) => {
        console.log('The read failed: ' + errorObject.name);
      });

As I said, there is no output, when the code is executed.

I'll be really thankful, if someone will reply with the solution.

I was trying to set the value of key from my database to be set as text, and I was expecting to show but there is nothing.


来源: stackexchange

问:
How to write the down casting from Timestamp to Date in Swift
```<code>struct User: Codable,Identifiable,Hashable{
   var @DocumentID var id: String?
   var name: String
   var birthDay: Timestamp?
}

struct Profile: View {
   @Binding var user: User
   @State var birthDay: Date
   init(){
     self._birthDay = State(initialValue:  _user.wrappedValue.birthDay as! Timestamp
   }
}

</code>```

I don't know how to  write the down casting from Firestore's Timestamp to Date.
I got the error Cannot convert value of type 'Timestamp' to expected argument type 'Date' in self._birthDay = State(initialValue:  _user.wrappedValue.birthDay as! Timestamp .
If _user.wrappedValue.birthDay is nil, I want to set the current date.

I checked this
But this is possible for nil. I want to set the current date if it is nil.
And User's birthday is optional. So I want to set jest Date type.

I think I can write this

```<code>let timestamp = _user.wrappedValue.birthDay as! Timestamp
let date = timestamp.dateValue()
</code>```

But I don't know if the timestamp is nil how to set current date.

I tried writing the down casting. But I can't get success.
Especially I don't know how to write that in 1 statement.

ContentLicense: CC BY-SA 4.0

Body:
struct User: Codable,Identifiable,Hashable{
   var @DocumentID var id: String?
   var name: String
   var birthDay: Timestamp?
}

struct Profile: View {
   @Binding var user: User
   @State var birthDay: Date
   init(){
     self._birthDay = State(initialValue:  _user.wrappedValue.birthDay as! Timestamp
   }
}

I don't know how to  write the down casting from Firestore's Timestamp to Date.
I got the error Cannot convert value of type 'Timestamp' to expected argument type 'Date' in self._birthDay = State(initialValue:  _user.wrappedValue.birthDay as! Timestamp .
If _user.wrappedValue.birthDay is nil, I want to set the current date.

I checked this
But this is possible for nil. I want to set the current date if it is nil.
And User's birthday is optional. So I want to set jest Date type.

I think I can write this

let timestamp = _user.wrappedValue.birthDay as! Timestamp
let date = timestamp.dateValue()

But I don't know if the timestamp is nil how to set current date.

I tried writing the down casting. But I can't get success.
Especially I don't know how to write that in 1 statement.


问:
Find the best rigid transformation (Rotation + translation) for two 2d small PointSet (Python)
Consider two sets of points, A and B as shown below.

Ax = [-2.0, 20.0, -16.0, 6.0, 7.0, -9.0, 25.0, -26.0, -24.0, 11.0, 0.0, 20.0, -8.0, 21.0, -0.0, -21.0, -20.0, 13.0, -22.0, 19.0, -13.0]

Ay =  [-25.0, -14.0, -20.0, -20.0, 26.0, 24.0, -0.0, 0.0, 10.0, 19.0, 0.0, -6.0, -20.0, 7.0, 22.0, -7.0, 17.0, -19.0, -14.0, 15.0, 17.0]

Bx = [-3.0, -22.0, -12.0, 8.0, 19.0, 28.0]

By = [-16.0, -16.0, -14.0, -11.0, -9.0, -4.0]

I need to find the best rigid transform ( Rotation + Translation) to fit B(x,y) in A(x,y)
I have this
Orange is B(x,y), Blue is A(x,y)

I need the best fitting B in A.
I need that

I´ve tried Probreg rigid transformations and ICP algorithms but it didnt work well.
If anyone have any idea how can i do this it can be very helpfull.
Thanks!
I'm working with Python 3.7


问:
Does passing an argument to next() in express prevent all the following middleware from executing?
I recently found that passing an argument (like a string) to next() function in express prevents all the following middleware functions from executing and handles that argument as an error.

For example:

```<code>app.get("/test", (req, res, next) => {
    fs.readFile("./doesntExist", "utf-8", (err, data) => {
        console.log("1st middleware function");
        if (err) return next(err);
        next();
    })
})

app.get("/test", (req, res, next) => {
    // this is never executed because the above middleware always calls next(err)
    console.log("2nd middleware function");
})
</code>```

Is this the correct way of dealing with errors?

Should I instead use throw new Error(err)? Or maybe next(new Error(err))?

Also, do I have to return next()? Or is just calling next() enough?

Body:
I recently found that passing an argument (like a string) to next() function in express prevents all the following middleware functions from executing and handles that argument as an error.

For example:

app.get("/test", (req, res, next) => {
    fs.readFile("./doesntExist", "utf-8", (err, data) => {
        console.log("1st middleware function");
        if (err) return next(err);
        next();
    })
})

app.get("/test", (req, res, next) => {
    // this is never executed because the above middleware always calls next(err)
    console.log("2nd middleware function");
})

Is this the correct way of dealing with errors?

Should I instead use throw new Error(err)? Or maybe next(new Error(err))?

Also, do I have to return next()? Or is just calling next() enough?


问:
Cannot Resolve Symbol GetAccessControl in .NET Core 3.1
I am trying to write a function in .net core 3.1 Class Library, to check file user rights.

Unfortunately, .net core 3.1 does not recognize GetAccessControl.

I have attached NUGET

System.IO.FileSystem 4.3.0

Microsoft.Windows.Compatability 7.0.0

Nothing works so far.

```<code> public static bool CheckFileAccess(string path, string domainUser)
        {
            var result = false;
            try
            {
                using (FileStream file = new FileStream("path", FileMode.Open))
                {
                    var acl = File.GetAccessControl(file.Name);
                    // do something with the acl

                    var rules = acl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

                    foreach (FileSystemAccessRule rule in rules)
                    {
                        if (rule.IdentityReference.Value.Equals(domainUser, StringComparison.OrdinalIgnoreCase))
                        {
                            return true;
                        }
                    }
                }

                Console.WriteLine("User does not have access to the file.");
            }
            catch (UnauthorizedAccessException ex)
            {
                return result;
            }

            return result;
        }
</code>```

Body:
I am trying to write a function in .net core 3.1 Class Library, to check file user rights.

Unfortunately, .net core 3.1 does not recognize GetAccessControl.

I have attached NUGET

System.IO.FileSystem 4.3.0

Microsoft.Windows.Compatability 7.0.0

Nothing works so far.

 public static bool CheckFileAccess(string path, string domainUser)
        {
            var result = false;
            try
            {
                using (FileStream file = new FileStream("path", FileMode.Open))
                {
                    var acl = File.GetAccessControl(file.Name);
                    // do something with the acl

                    var rules = acl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

                    foreach (FileSystemAccessRule rule in rules)
                    {
                        if (rule.IdentityReference.Value.Equals(domainUser, StringComparison.OrdinalIgnoreCase))
                        {
                            return true;
                        }
                    }
                }

                Console.WriteLine("User does not have access to the file.");
            }
            catch (UnauthorizedAccessException ex)
            {
                return result;
            }

            return result;
        }


问:
AlertManager alerts - need the way to add into mail template how long alert already fired and sort alerts by this filed
When I add .StartsAt filed into AlertManager mail template I get the following representation in mail:

2023-01-12 00:03:03.584 +0000 UTC

But I need to display how long time each alert already fired and sort them by this field.
I know Go templates have function Since(), but unfortunately it isn't available in AlertManager mail templates.
As a workaround - how to sort on StartsAt field?


问:
angular mat Multi select drop-down selected change bind another drop-down
I have two dropdowns one multi select mat dropdown and one single select mat dropdown.
In first multiple select drop-down if i select or check a car company for example Audi then in second drop it should bind Audi models A4,A5 ,Q6. And if i select/check Audi and another check box for example GM it should bind A4,A5,Q6,Tahoe, Acadia,Canyon so I have multiple car companies and multiple car models how I can achieve this.

Tried different things but couldn't acheive.


问:
Sending notification using firebase Api but not receiving on the browser
I am trying to send notification using firebase api in asp.net core everything is working fine on local pc but on live project the response of the function shows that the notification has been sent properly but i am not receiving any on the browser but the strange part is that when i try to send notification to the same user my retreiving the token saved in the db from firebase console i received it on the browser.
Here is the code.
Everything is working just fine it retrieves the token from db against the username and send notification to the token and result also seems fine.

```<code>public async Task<IActionResult> SendNotification(NotificationModel model)
    {
        try
        {
            var response = new ResponseModel();
            if (string.IsNullOrEmpty(model.ToUsername))
            {

                response.Message = "an error occurred while processing your request";
                response.ResponseStatus = Core.Enums.ResponseStatus.Error;
                return BadRequest(response);
            }

            var tokens =  _deviceManager.GetDeviceTokens(model.ToUsername);
            if (tokens.Any())
            {
                var result  = await NotificationsManager.SendPushNotifications(model.Message,   model.Tittle, tokens);

                response.Data = model;
                response.Message = "Success";
                response.ResponseStatus = Core.Enums.ResponseStatus.Success;

                var errorsList = new List<KeyValuePair<string, string>>();
                for (int i = 0; i < result.Responses.Count; i++)
                {
                    var item = result.Responses[i];
                    errorsList.Add(new KeyValuePair<string, string>(i.ToString(), "Success:" + item.IsSuccess + ","  + "MessageId:"+ item.MessageId + "," +"Error:"+ item.Exception));
                }
                response.ErrorsList = errorsList;

                return Ok(response);
            }

            response.Message = "No User found with the given username or the user you are trying to send the notification has not enabled the notification";
            response.ResponseStatus = Core.Enums.ResponseStatus.Error;
            return BadRequest(response);
        }
        catch (Exception e)
        {
            var response = new ResponseModel();
            response.Message = "an error occurred while processing your request" + e.Message;
            response.ResponseStatus = Core.Enums.ResponseStatus.Error;
            return BadRequest(response); throw;
        }
    }
</code>```

This is the response i get from swagger api when i call this api:
{
"responseStatus": 200,
"errorsList": [
{
"key": "0",
"value": "Success:True,MessageId:projects/aurora-10684/messages/ff9a5a3f-def7-4120-b23f-  c9d871d25172,Error:"
}
],
"metaData": null,
"message": "Success",
"data": {
"message": "string",
"toUsername": "shahreyarbutt",
"tittle": "string"
}
}

i tried everything and everything is wokring on local but on the live project it sends the notification but fails to receive when sending from the swagger using my api but with firebase console it works fine.

Body:
I am trying to send notification using firebase api in asp.net core everything is working fine on local pc but on live project the response of the function shows that the notification has been sent properly but i am not receiving any on the browser but the strange part is that when i try to send notification to the same user my retreiving the token saved in the db from firebase console i received it on the browser.
Here is the code.
Everything is working just fine it retrieves the token from db against the username and send notification to the token and result also seems fine.

public async Task<IActionResult> SendNotification(NotificationModel model)
    {
        try
        {
            var response = new ResponseModel();
            if (string.IsNullOrEmpty(model.ToUsername))
            {

                response.Message = "an error occurred while processing your request";
                response.ResponseStatus = Core.Enums.ResponseStatus.Error;
                return BadRequest(response);
            }

            var tokens =  _deviceManager.GetDeviceTokens(model.ToUsername);
            if (tokens.Any())
            {
                var result  = await NotificationsManager.SendPushNotifications(model.Message,   model.Tittle, tokens);

                response.Data = model;
                response.Message = "Success";
                response.ResponseStatus = Core.Enums.ResponseStatus.Success;

                var errorsList = new List<KeyValuePair<string, string>>();
                for (int i = 0; i < result.Responses.Count; i++)
                {
                    var item = result.Responses[i];
                    errorsList.Add(new KeyValuePair<string, string>(i.ToString(), "Success:" + item.IsSuccess + ","  + "MessageId:"+ item.MessageId + "," +"Error:"+ item.Exception));
                }
                response.ErrorsList = errorsList;

                return Ok(response);
            }

            response.Message = "No User found with the given username or the user you are trying to send the notification has not enabled the notification";
            response.ResponseStatus = Core.Enums.ResponseStatus.Error;
            return BadRequest(response);
        }
        catch (Exception e)
        {
            var response = new ResponseModel();
            response.Message = "an error occurred while processing your request" + e.Message;
            response.ResponseStatus = Core.Enums.ResponseStatus.Error;
            return BadRequest(response); throw;
        }
    }

This is the response i get from swagger api when i call this api:
{
"responseStatus": 200,
"errorsList": [
{
"key": "0",
"value": "Success:True,MessageId:projects/aurora-10684/messages/ff9a5a3f-def7-4120-b23f-  c9d871d25172,Error:"
}
],
"metaData": null,
"message": "Success",
"data": {
"message": "string",
"toUsername": "shahreyarbutt",
"tittle": "string"
}
}

i tried everything and everything is wokring on local but on the live project it sends the notification but fails to receive when sending from the swagger using my api but with firebase console it works fine.


问:
Can't make greasemonkey click the Default View or Cinema View button
I am new to javascript and I tried to write a piece of code that would click a button depending on the width of the browser. If the size of the window is over 50% of my monitor I want it to press the button for the default view and when it is under 50% I want it to press the button for cinema view.

I have tried changing the "window.onload" to "window.addEventListener("load", function()" and I even added a timeout just to make sure the elements were loaded. This is my current code:

```<code>window.addEventListener("load", function(){
    setTimeout(function() {
        if (window.innerWidth > window.screen.width / 2) {
            // select the element with the title "Default mode (t)"
            var defaultModeButton = document.querySelector('button[title="Default mode (t)"]');
            // click the element
            defaultModeButton.click();
        }else{
            // select the element with the title "Cinema mode (t)"
            var cinemaModeButton = document.querySelector('button[title="Cinema mode (t)"]');
            // click the element
            cinemaModeButton.click();
        }
    }, 2000);
});
</code>```

What am I missing? Can somebody help me out?

Body:
I am new to javascript and I tried to write a piece of code that would click a button depending on the width of the browser. If the size of the window is over 50% of my monitor I want it to press the button for the default view and when it is under 50% I want it to press the button for cinema view.

I have tried changing the "window.onload" to "window.addEventListener("load", function()" and I even added a timeout just to make sure the elements were loaded. This is my current code:

window.addEventListener("load", function(){
    setTimeout(function() {
        if (window.innerWidth > window.screen.width / 2) {
            // select the element with the title "Default mode (t)"
            var defaultModeButton = document.querySelector('button[title="Default mode (t)"]');
            // click the element
            defaultModeButton.click();
        }else{
            // select the element with the title "Cinema mode (t)"
            var cinemaModeButton = document.querySelector('button[title="Cinema mode (t)"]');
            // click the element
            cinemaModeButton.click();
        }
    }, 2000);
});

What am I missing? Can somebody help me out?


问:
Is there an alternative to jest-environment-jsdom for jest tests using the window object
I'm writing jest unit tests of some angularjs code that expects the windows object. The unit tests are failing because of this error:

Reference Error: window is not defined

The default mode for jest is "node". If I want to use "jsdom" (which would add a window object), then I need to install jest-environment-jsdom. However, when trying to install jest-environment-jsdom, I encounter node-gyp errors. I looked up node-gyp installation help and found:

https://github.com/nodejs/node-gyp#on-windows

Which tells me that I need to install VS Build tools. This is a huge installation. I'm looking for an alternative solution that won't require other dependencies.


问:
How to calculate a total amount using jquery repeater
I am using jquery repeater to add a new amount, I would like to be able to add it up to get the total.

```<code><div class="repeater">
                                            <div data-repeater-list="detalle">
                                                <div data-repeater-item>

                                                <div class="row">

                                                <div class="col-md-2">
                                                        <label for="">Precio</label>
                                                        <input type="number" placeholder="0.00" class="form-control" step="0.01" min="0" name="precio"/>
                                                </div>
                                                <div class="col-md-2">
                                                    <label for="">Cantidad</label>
                                                    <input type="number" placeholder="0.00" class="form-control" name="precio"/>
                                                </div>
                                                <div class="col-md-2">
                                                    <label for="">Importe</label>
                                                    <input type="number" placeholder="0.00" class="form-control" step="0.01" min="0" name="precio"/>

                                                </div>

                                                <div class="col-md-2">
                                                    <br>

                                                    <a data-repeater-delete type="button" class="btn btn-primary" value="Delete"> Eliminar </a>

                                                </div>

                                                </div>

                                                </div>
                                            </div>
                                            <br>
                                            <a data-repeater-create class="btn btn-primary"  type="button"  >Agregar</a>
                                        </div>
</code>```

How can I add and display the result?

javascript

```<code>var repeater = $('.repeater').repeater({
            show: function() {
                $(this).slideDown();
            },
            hide: function (deleteElement) {
                $(this).slideUp(deleteElement);
            },

        });
</code>```

How can I calculate the total and print it?

Body:
I am using jquery repeater to add a new amount, I would like to be able to add it up to get the total.

                                                        Precio
                                                        <input type="number" placeholder="0.00" class="form-control" step="0.01" min="0" name="precio"/>

                                                    Cantidad
                                                    <input type="number" placeholder="0.00" class="form-control" name="precio"/>

                                                    Importe
                                                    <input type="number" placeholder="0.00" class="form-control" step="0.01" min="0" name="precio"/>

                                                     Eliminar

                                            Agregar

How can I add and display the result?

javascript

var repeater = $('.repeater').repeater({
            show: function() {
                $(this).slideDown();
            },
            hide: function (deleteElement) {
                $(this).slideUp(deleteElement);
            },

        });

How can I calculate the total and print it?


问:
Exclude folder from next JS build
I have a bulky folder full of backend & config code located in /src/config inside my Next JS app.

I don't need to ship any of this code to the client when building. Is there a best practice for excluding this folder from building in Next JS? Thanks

Title: Exclude folder from next JS build


问:
Pygame failing to load mp3 file
I am trying to load a mp3 file in pygame 2.1.2 (SDL 2.0.18, Python 3.9.13) but i am getting an error here is the code i am using:

```<code>self.jump_sound = pygame.mixer.Sound('C:/Users/IAMAUSER/OneDrive/Desktop/Pro/Pygame/audio/jump.mp3')
</code>```

I am using "self." because i am doing this in a class and yes i have imported pygame

Error i am getting:
Traceback (most recent call last): File "c:\Users\IAMAUSER\OneDrive\Desktop\Pro\Pygame\import pygame.py", line 139, in <module> player.add(Player()) File "c:\Users\IAMAUSER\OneDrive\Desktop\Pro\Pygame\import pygame.py", line 18, in __init__ self.jump_sound = pygame.mixer.Sound('C:/Users/IAMAUSER/OneDrive/Desktop/Pro/Pygame/audio/jump.mp3') pygame.error: Unable to open file 'C:/Users/IAMAUSER/OneDrive/Desktop/Pro/Pygame/audio/jump.mp3'

The player.add(Player()) is not the problem i think

I expected for it to load the sound so i could use
self.jump_sound.play()
to play the sound

Title: Pygame failing to load mp3 file

Body:
I am trying to load a mp3 file in pygame 2.1.2 (SDL 2.0.18, Python 3.9.13) but i am getting an error here is the code i am using:

self.jump_sound = pygame.mixer.Sound('C:/Users/IAMAUSER/OneDrive/Desktop/Pro/Pygame/audio/jump.mp3')

I am using "self." because i am doing this in a class and yes i have imported pygame

Error i am getting:
Traceback (most recent call last): File "c:\Users\IAMAUSER\OneDrive\Desktop\Pro\Pygame\import pygame.py", line 139, in <module> player.add(Player()) File "c:\Users\IAMAUSER\OneDrive\Desktop\Pro\Pygame\import pygame.py", line 18, in __init__ self.jump_sound = pygame.mixer.Sound('C:/Users/IAMAUSER/OneDrive/Desktop/Pro/Pygame/audio/jump.mp3') pygame.error: Unable to open file 'C:/Users/IAMAUSER/OneDrive/Desktop/Pro/Pygame/audio/jump.mp3'

The player.add(Player()) is not the problem i think

I expected for it to load the sound so i could use
self.jump_sound.play()
to play the sound


问:
How to handle data that has a digit typo in a number
I have to analyze my data. It is data from World Bank. It has data for all 195 countries. Each country has 15 rows with data for 15 years. At some countries there is a problem with mistyping information. There are input errors in the "Population" column. The person who entered the data sometimes made a mistake with a number, and instead of 36435443, he entered 3643544. As a result, in some years, a 10-fold drop is seen.

I will attach a screen to the graph showing the population growth of Afghanistan for the years 2000 - 2015

I tried to make an algorithm that detects outliers using std, this is code:

```<code>
# Load data into a pandas DataFrame
gdp_data = afg_data.copy()

# Take the natural logarithm of the data
gdp_data['log_gdp'] = np.log(gdp_data['Population'])

# Create a new column for Z-Scores
gdp_data['z_score'] = np.abs(gdp_data['log_gdp'] - gdp_data['log_gdp'].mean()) / gdp_data['log_gdp'].std()

# Identify outliers
outliers = gdp_data[gdp_data['z_score'] > 1]
outliers
</code>```

And this is result: (red is considered outlier)

Body:
I have to analyze my data. It is data from World Bank. It has data for all 195 countries. Each country has 15 rows with data for 15 years. At some countries there is a problem with mistyping information. There are input errors in the "Population" column. The person who entered the data sometimes made a mistake with a number, and instead of 36435443, he entered 3643544. As a result, in some years, a 10-fold drop is seen.

I will attach a screen to the graph showing the population growth of Afghanistan for the years 2000 - 2015

I tried to make an algorithm that detects outliers using std, this is code:

# Load data into a pandas DataFrame
gdp_data = afg_data.copy()

# Take the natural logarithm of the data
gdp_data['log_gdp'] = np.log(gdp_data['Population'])

# Create a new column for Z-Scores
gdp_data['z_score'] = np.abs(gdp_data['log_gdp'] - gdp_data['log_gdp'].mean()) / gdp_data['log_gdp'].std()

# Identify outliers
outliers = gdp_data[gdp_data['z_score'] > 1]
outliers

And this is result: (red is considered outlier)


问:
How add FAB to bottom navigation bar with Compose in Material3?
Every tutorial or example of what I want to achieve uses isFloatingActionButtonDocked = true in a Scaffold. This is not present in Material3 Scaffold and I presume its part of what achieves the the bottom result

I cannot find any information on how to achieve this nor I see any control of the FAB except modifier.

I tried add padding and offset it , but it would not make the gap around it and the menu.


问:
Custom loss with weights when using BatchDataset in Keras
I have a Keras model for which I have features, labels and an additional array which I want to use it as weights for a custom loss function. I am ingesting the data using 2 BatchDataset structures as follows:

One is containing the features and labels:

```<code>train_ds.element_spec
(TensorSpec(shape=(None, None, 100), dtype=tf.float32, name=None),
 TensorSpec(shape=(None, 100), dtype=tf.float32, name=None))
</code>```

The additional BatchDataset with the weights for the loss function

```<code>train_weights.element_spec
TensorSpec(shape=(None, 100), dtype=tf.float32, name=None)
</code>```

I am training the model this way:

```<code>model.fit(train_ds, epochs=10, batch_size=512, shuffle=True)
</code>```

The custom loss function loss function which uses the additional data is like this:

```<code>def custom_loss(y_true, y_pred, weights):
    loss = (y_true - y_pred)*weights
    return loss

model.compile(loss=custom_loss, optimizer=optimizer, metrics=["mae"])
</code>```

Is it possible to use the train_ds and train_weights BatchDatasets I have at the moment to define this custom loss function and use it for training?

Body:
I have a Keras model for which I have features, labels and an additional array which I want to use it as weights for a custom loss function. I am ingesting the data using 2 BatchDataset structures as follows:

One is containing the features and labels:

train_ds.element_spec
(TensorSpec(shape=(None, None, 100), dtype=tf.float32, name=None),
 TensorSpec(shape=(None, 100), dtype=tf.float32, name=None))

The additional BatchDataset with the weights for the loss function

train_weights.element_spec
TensorSpec(shape=(None, 100), dtype=tf.float32, name=None)

I am training the model this way:

model.fit(train_ds, epochs=10, batch_size=512, shuffle=True)

The custom loss function loss function which uses the additional data is like this:

def custom_loss(y_true, y_pred, weights):
    loss = (y_true - y_pred)*weights
    return loss

model.compile(loss=custom_loss, optimizer=optimizer, metrics=["mae"])

Is it possible to use the train_ds and train_weights BatchDatasets I have at the moment to define this custom loss function and use it for training?


问:
Change permalink for variants in wordpress
I want to change the permalink for my variants in wordpress.

The structure of my permalink is like this:

```<code>http://mysite.local/product/attribute-name/attribute/
</code>```

What I would like is:

```<code>http://mysite.local/product/product-slug/attribute/
</code>```

product slug is like: test-product-brand-name, so from the wp_posts.post_name

Can I do this somehow? I am using Woocommerce and Divi.

It's ok if you can tell me a filter or action name for this, I could change it programmatically, just I did not found any hook or filter for this.

Body:
I want to change the permalink for my variants in wordpress.

The structure of my permalink is like this:

http://mysite.local/product/attribute-name/attribute/

What I would like is:

http://mysite.local/product/product-slug/attribute/

product slug is like: test-product-brand-name, so from the wp_posts.post_name

Can I do this somehow? I am using Woocommerce and Divi.

It's ok if you can tell me a filter or action name for this, I could change it programmatically, just I did not found any hook or filter for this.


问:
Resolving a Spring Boot property of type map, as a property in log4j2-spring.xml
When using log4j2 with Spring Boot it is possible to load Spring properties into the log4j2-spring.xml configuration using properties like so:

application.yml:

```<code>someProperty: prop
</code>```

log4j2-spring.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2.xml -->

<Configuration>
     <Properties>
          <Property name="someProperty">${spring:someProperty}</Property>
     <Properties>
     ...
</Configuration>
</code>```

My problem occurs when I try to do this with something more complicated than a simple string. Specifically a map. I can see from the log4j2 documentation that log4j2 does support properties of type map.

I tried the following:

application.yml:

```<code>someMapProperty:
     key0: val0
     key1: val1
</code>```

log4j2-spring.xml:

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

<Configuration>
     <Properties>
          <Property name="someMapProperty">${spring:someMapProperty}</Property>
     <Properties>
     ...
</Configuration>
</code>```

This property does not work, and on further inspection I see that it does not resolve and the property stays as the literal value "${spring:someMapProperty}"

There is very little information to find about this on both Spring's and log4j2's documentation, and I'm starting to doubt if it is even possible.

Has anybody done something similar before and knows what I'm doing wrong, or does somebody know definitively that it is not possible?

Spring-Boot version: 2.7.1

log4j-spring-boot version: 2.17.2

Body:
When using log4j2 with Spring Boot it is possible to load Spring properties into the log4j2-spring.xml configuration using properties like so:

application.yml:

someProperty: prop

log4j2-spring.xml:

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

<Configuration>
     <Properties>
          <Property name="someProperty">${spring:someProperty}</Property>
     <Properties>
     ...
</Configuration>

My problem occurs when I try to do this with something more complicated than a simple string. Specifically a map. I can see from the log4j2 documentation that log4j2 does support properties of type map.

I tried the following:

application.yml:

someMapProperty:
     key0: val0
     key1: val1

log4j2-spring.xml:

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

<Configuration>
     <Properties>
          <Property name="someMapProperty">${spring:someMapProperty}</Property>
     <Properties>
     ...
</Configuration>

This property does not work, and on further inspection I see that it does not resolve and the property stays as the literal value "${spring:someMapProperty}"

There is very little information to find about this on both Spring's and log4j2's documentation, and I'm starting to doubt if it is even possible.

Has anybody done something similar before and knows what I'm doing wrong, or does somebody know definitively that it is not possible?

Spring-Boot version: 2.7.1

log4j-spring-boot version: 2.17.2


问:
Digital Ocean API - App / Private Git Branch Not Found
I am trying to automate the creation of new app service on the Digital Ocean platform.

But i get the following error : data: { id: 'not_found', message: 'Git branch not found' }

Using the following api:
https://docs.digitalocean.com/reference/api/api-reference/#operation/apps_create

My GitHub repo is a private instance, I had connected github with Digital Ocean.

My App Spec

```<code>  "project_id": '2a56888d-5c27-45b9-af1a-a2464e1f2d11',
        "spec": {
          "name": "test",
          "region": "nyc",
          "services": [
            {
              "name": "api",
              "github": {
                "branch": "main",
                "deploy_on_push": true,
                "repo": "xxx/xxxx"
              },
              "run_command": "node node.js",
              "environment_slug": "node-js",
              "instance_count": 1,
              "instance_size_slug": "basic-xxs",
              "routes": [
                {
                  "path": "/"
                }
              ]
            }
          ]
        }
</code>```

Body:
I am trying to automate the creation of new app service on the Digital Ocean platform.

But i get the following error : data: { id: 'not_found', message: 'Git branch not found' }

Using the following api:
https://docs.digitalocean.com/reference/api/api-reference/#operation/apps_create

My GitHub repo is a private instance, I had connected github with Digital Ocean.

My App Spec

  "project_id": '2a56888d-5c27-45b9-af1a-a2464e1f2d11',
        "spec": {
          "name": "test",
          "region": "nyc",
          "services": [
            {
              "name": "api",
              "github": {
                "branch": "main",
                "deploy_on_push": true,
                "repo": "xxx/xxxx"
              },
              "run_command": "node node.js",
              "environment_slug": "node-js",
              "instance_count": 1,
              "instance_size_slug": "basic-xxs",
              "routes": [
                {
                  "path": "/"
                }
              ]
            }
          ]
        }


问:
Running a pre-made script with adb shell commands
3 yrs ago i wrote this code and i used to execute it easily on the android screen. Now I feel defeated since i cannot remember anything on how to run this SCRIPT using adb shell so that it creates a loop inside my Android Samsung's phone screen to make a certain loop. Can you please help
this is the code

```<code>#Enter your adb location >
cd /c/adb
array=(
        "Text"
"test2"
"test3"
"test4"
"test5"

        )
for element in ${array[@]}
do
echo Add: $element
./adb shell input text $element
sleep 2
./adb shell input tap 112 402
sleep 2
./adb shell input tap 388 546
sleep 2
done

echo "Finished"
</code>```

I tried so hard but in the end it didnt even matter

Body:
3 yrs ago i wrote this code and i used to execute it easily on the android screen. Now I feel defeated since i cannot remember anything on how to run this SCRIPT using adb shell so that it creates a loop inside my Android Samsung's phone screen to make a certain loop. Can you please help
this is the code

#Enter your adb location >
cd /c/adb
array=(
        "Text"
"test2"
"test3"
"test4"
"test5"

        )
for element in ${array[@]}
do
echo Add: $element
./adb shell input text $element
sleep 2
./adb shell input tap 112 402
sleep 2
./adb shell input tap 388 546
sleep 2
done

echo "Finished"

I tried so hard but in the end it didnt even matter


问:
How to subset my Seurat object to only look at variable features while also keeping specific genes
I am relatively new to bioinformatics and am trying to work with an absolutely massive dataset that comes as a single Seurat object of about 90gb. My computer keeps crashing every time I try to even load this thing into RStudio. I have uploaded this seurat object onto my university's cluster but cannot get the additional packages I would need to do this analysis to work in the cluster.

I am now hoping to subset this Seurat object on the cluster to only look at the genes considered variable features in order to cut down on file size so I complete the rest of the analysis locally. If possible, I would like to also ensure that a couple of specific genes (whether they are considered variable features or not) are kept in the sub-setted suerat object so I can keep them in my analysis. What steps should I take to do this? Thanks so much for your help!


问:
`shouldOverrideUrlLoading` and `webView.loadUrl()` and initial`clientWidth` issue
I get a web page A, and it will jump to page B by using window.location.replace(pageBUrl) API.

Page A is opened in an Android app's WebView. If I customized the WebViewClient, and override shouldOverrideUrlLoading method. Then if I use webView.loadUrl(url) and return true in that method, I will get wrong initial document.documentBody.clientWidth in page B. (The wrong clientWidth equals devicePixelRatio multiply device width.) This will cause page B showing too large.

But if I using return false in shouldOverrideUrlLoading, everything will be OK. And if I load page B directly, everything will be OK, too.

So, I want to figure out:

What's the difference between webView.loadUrl and return false in shouldOverrideUrlLoading?

How can page B get correct initial clientWidth without changing WebView actions (this means I will still use webView.loadUrl(url) and return true in shouldOverrideUrlLoading)?

Notice:

This issue is only occurred in some Android devices (eg. Samsung, OPPO, Xiaomi).

Page A is implemented by using Vue2, page B is not belongs to us.

Page A and Page B are all support same viewport.


问:
Strange appearance of hand pointer in Rstudio
I've installed a new Rstudio (2022.07.2+576) and various packages I needed for my research. Folowing the installation the regular white hand pointer changed its appearance to the one attached, black hand. I'm a bit worried whether I installed something harmful that caused this change. Does anyone encounter this kind of pointer in Rstudio?

I tried to play with the background theme and remive a few packages, but ot didn't help.

Thank you!


问:
MongoDB cascade aggregation lookup
The user form contains multiple fields that are objects with CurrentValue and AvailableValues.

I need to do filtering in MongoDB for the given user request, but also return available values, top-down. This means that if e.g. Product Name is "P1", then all the following fields must have values only available for P1 products. Second field is e.g. Angle with value 45, then all the following fields must have values only available for P1 products with angle 45, and so on.

Is there a way for this to be done in a single MongoDB Aggregation Pipeline query?

I have implemented multiple queries - first I filter based on the first value and return available values for the second field. Then filter again for the second value and so on.

Title: MongoDB cascade aggregation lookup


问:
Why can't you define the instance structure of a derivable type in GObject

What I'm trying to imitate with GObject

Here's a simple C++ example:

#include <iostream>

using std::cout;
using std::endl;

class Matrix {
    public:
    Matrix (int rows, int cols) {
        this->rows = rows;
        this->cols = cols;
        this->coeffs = 0;
    };
    int rows, cols;
    double *coeffs;
};
class SymmetricMatrix final : public Matrix {
    public:
    SymmetricMatrix (int size) : Matrix (size, size) {
        this->size = size;
        this->nb_coeffs = size*(size-1)/2;
        this->coeffs = new double[this->nb_coeffs]();
    };
    int size, nb_coeffs;
    void print_self () {
        for (int i=0; i<this->nb_coeffs; i++) {
            cout << this->coeffs[i] << " ";
        }
        cout << endl;
    };
};

int main () {
    SymmetricMatrix S (6);
    S.print_self ();
    cout << S.cols << endl; // Access parent's public member variable !
    return 0;
}
```
<h2>What I've got for now</h2>
<p>I want to copy the C++ class structure but using GObject.</p>
<p><strong>The problem is:</strong> I don't understand how I can define and inherit public variables for a derivable base class. Indeed, since the <code>G_DECLARE_DERIVABLE_TYPE</code> already defines one, I can't redefine it... <strong>Why is it one should not be able to do this ?</strong></p>
<p>Here's what I have for now[^1]. As far as I understand, it isn't possible because GObject is not C++ and the general paradigms aren't the same.</p>
<p><em>tmatrix.h</em></p>
```#ifndef TMATRIX_H
#define TMATRIX_H

#include <glib-object.h>

#define T_TYPE_MATRIX t_matrix_get_type()
G_DECLARE_DERIVABLE_TYPE (TMatrix, t_matrix, T, MATRIX, GObject)

struct _TMatrixClass {
    GObjectClass parent_class;
};

// struct _TMatrix {
//  GObject parent_instance;
//  gint nrows;
//  gint ncols;
//  gdouble *coeffs;
// };

/* Public function */
TMatrix *t_matrix_new (int ncols, int nrows);
#endif
```
<p><em>tmatrix.c</em></p>
```#include "tmatrix.h"

G_DEFINE_TYPE (TMatrix, t_matrix, G_TYPE_OBJECT)

void t_matrix_class_init (TMatrixClass *class) {}
void t_matrix_init (TMatrix *instance) {}

TMatrix *t_matrix_new (gint ncols, gint nrows) {
    TMatrix *matrix = g_object_new (T_TYPE_MATRIX, NULL);
    // matrix->cols = ncols;
    // matrix->rows = nrows
    return matrix;
}
```
<p><em>tsymmetricmatrix.h</em></p>
```#ifndef TSYMETRICMATRIX_H
#define TSYMETRICMATRIX_H

#include "tmatrix.h"
#include <glib-object.h>

struct _TSymmetricMatrix {
    TMatrix parent_object;
    // Public members
    gint size;
};

#define T_TYPE_SYMMETRIC_MATRIX t_symmetric_matrix_get_type ()
G_DECLARE_FINAL_TYPE (TSymmetricMatrix, t_symmetric_matrix, T, SYMMETRIC_MATRIX, TMatrix)

/*Public class methods*/
void t_symmetric_matrix_print (TSymmetricMatrix *self);

/*Namespace public functions*/
TSymmetricMatrix *t_symmetric_matrix_new (gint size);

#endif
```
<p><em>tsymmetricmatrix.c</em></p>
```#include "tsymmetricmatrix.h"

G_DEFINE_FINAL_TYPE (TSymmetricMatrix, t_symmetric_matrix, T_TYPE_MATRIX)

void t_symmetric_matrix_class_init (TSymmetricMatrixClass *class) {}
void t_symmetric_matrix_init (TSymmetricMatrix *instance) {}
void t_symmetric_matrix_print (TSymmetricMatrix *self) {
    // print code
}
TSymmetricMatrix *t_symmetric_matrix_new (gint size) {
    TSymmetricMatrix *matrix = g_object_new (T_TYPE_SYMMETRIC_MATRIX, NULL);
    //
    // I don't know what to do next ...
    return matrix;
}
```
<p><em>main.c</em></p>
```#include "tmatrix.h"
#include "tsymmetricmatrix.h"

int main () {
    TSymmetricMatrix *A = t_symmetric_matrix_new (3);
    t_symmetric_matrix_print(A);
    return 0;
}

```

[^1]:Note: I know I should be using properties for setting/getting class variables. This is really just for the sake of learning.

Body:
What I'm trying to imitate with GObject

Here's a simple C++ example:

#include <iostream>

using std::cout;
using std::endl;

class Matrix {
    public:
    Matrix (int rows, int cols) {
        this->rows = rows;
        this->cols = cols;
        this->coeffs = 0;
    };
    int rows, cols;
    double *coeffs;
};
class SymmetricMatrix final : public Matrix {
    public:
    SymmetricMatrix (int size) : Matrix (size, size) {
        this->size = size;
        this->nb_coeffs = size*(size-1)/2;
        this->coeffs = new double[this->nb_coeffs]();
    };
    int size, nb_coeffs;
    void print_self () {
        for (int i=0; i<this->nb_coeffs; i++) {
            cout << this->coeffs[i] << " ";
        }
        cout << endl;
    };
};

int main () {
    SymmetricMatrix S (6);
    S.print_self ();
    cout << S.cols << endl; // Access parent's public member variable !
    return 0;
}

What I've got for now

I want to copy the C++ class structure but using GObject.

The problem is: I don't understand how I can define and inherit public variables for a derivable base class. Indeed, since the G_DECLARE_DERIVABLE_TYPE already defines one, I can't redefine it... Why is it one should not be able to do this ?

Here's what I have for now[^1]. As far as I understand, it isn't possible because GObject is not C++ and the general paradigms aren't the same.

tmatrix.h

#ifndef TMATRIX_H
#define TMATRIX_H

#include <glib-object.h>

#define T_TYPE_MATRIX t_matrix_get_type()
G_DECLARE_DERIVABLE_TYPE (TMatrix, t_matrix, T, MATRIX, GObject)

struct _TMatrixClass {
    GObjectClass parent_class;
};

// struct _TMatrix {
//  GObject parent_instance;
//  gint nrows;
//  gint ncols;
//  gdouble *coeffs;
// };

/* Public function */
TMatrix *t_matrix_new (int ncols, int nrows);
#endif

tmatrix.c

#include "tmatrix.h"

G_DEFINE_TYPE (TMatrix, t_matrix, G_TYPE_OBJECT)

void t_matrix_class_init (TMatrixClass *class) {}
void t_matrix_init (TMatrix *instance) {}

TMatrix *t_matrix_new (gint ncols, gint nrows) {
    TMatrix *matrix = g_object_new (T_TYPE_MATRIX, NULL);
    // matrix->cols = ncols;
    // matrix->rows = nrows
    return matrix;
}

tsymmetricmatrix.h

#ifndef TSYMETRICMATRIX_H
#define TSYMETRICMATRIX_H

#include "tmatrix.h"
#include <glib-object.h>

struct _TSymmetricMatrix {
    TMatrix parent_object;
    // Public members
    gint size;
};

#define T_TYPE_SYMMETRIC_MATRIX t_symmetric_matrix_get_type ()
G_DECLARE_FINAL_TYPE (TSymmetricMatrix, t_symmetric_matrix, T, SYMMETRIC_MATRIX, TMatrix)

/*Public class methods*/
void t_symmetric_matrix_print (TSymmetricMatrix *self);

/*Namespace public functions*/
TSymmetricMatrix *t_symmetric_matrix_new (gint size);

#endif

tsymmetricmatrix.c

#include "tsymmetricmatrix.h"

G_DEFINE_FINAL_TYPE (TSymmetricMatrix, t_symmetric_matrix, T_TYPE_MATRIX)

void t_symmetric_matrix_class_init (TSymmetricMatrixClass *class) {}
void t_symmetric_matrix_init (TSymmetricMatrix *instance) {}
void t_symmetric_matrix_print (TSymmetricMatrix *self) {
    // print code
}
TSymmetricMatrix *t_symmetric_matrix_new (gint size) {
    TSymmetricMatrix *matrix = g_object_new (T_TYPE_SYMMETRIC_MATRIX, NULL);
    //
    // I don't know what to do next ...
    return matrix;
}

main.c

#include "tmatrix.h"
#include "tsymmetricmatrix.h"

int main () {
    TSymmetricMatrix *A = t_symmetric_matrix_new (3);
    t_symmetric_matrix_print(A);
    return 0;
}

[^1]:Note: I know I should be using properties for setting/getting class variables. This is really just for the sake of learning.


问:
I can't add a new Row to an inline crud table once i get live data
I am trying to create an inline create and edit function on a table in angular, when i click on 'add', a new row with empty input fields is supposed to be created. works well on mock data but wont create on real data.</p>
```<code>
<table class="table">
      <tr>
        <th colspan="5" class="bg-slate-400 py-2 ">Commodity and Offtaker Price Informations</th>
      </tr>
        <tr>
          <th scope="col">OID</th>
          <th scope="col">Description</th>
          <th scope="col">Price</th>
          <th scope="col">UOM</th>
          <th>
            <button
                     type="button"
                     title="Add Commodity"
                     class="btn bg-green-400 text-white hover:bg-green-800 cursor-pointer"
                     (click)="addRow()"
                     >
                      <i class="pi pi-plus"></i>
            </button>
          </th>
        </tr>
 <table>

</code>```
```<code>  addRow(){
    this.ICommodity.unshift({
      offtakerPriceOID: + 1,
      commodityDescription: '',
      unitPrice: 0,
      unitOfMeasure: ''
    })
    this.itemSelected = this.commodity[+1];
  }

</code>```

Body:
I am trying to create an inline create and edit function on a table in angular, when i click on 'add', a new row with empty input fields is supposed to be created. works well on mock data but wont create on real data.

        Commodity and Offtaker Price Informations

          OID
          Description
          Price
          UOM

            <button
                     type="button"
                     title="Add Commodity"
                     class="btn bg-green-400 text-white hover:bg-green-800 cursor-pointer"
                     (click)="addRow()"
                     >

            </button>

  addRow(){
    this.ICommodity.unshift({
      offtakerPriceOID: + 1,
      commodityDescription: '',
      unitPrice: 0,
      unitOfMeasure: ''
    })
    this.itemSelected = this.commodity[+1];
  }


问:
in_app_purchase how to check validity of restored purchase
On startup I call restorePurchases() to get the previous bought subscriptions.

This works fine but I also get subscriptions which where canceled by the user before!
They have status PurchaseStatus.restored and pendingCompletePurchase is true even though I called completePurchase().

How do I know if the purchase is still valid and not canceled by the user?

```<code>
Future<void> initializeProAccountPurchase(context) async {
    available = await IAPService.checkIAPAvailability();

    if (available) {
      await IAPService.restorePurchases().onError((error, stackTrace) =>
          {print("error restore"), print(error.userInfo)});
      await getProAccountDetails({'subs_item_purchase', 'pro_account'});
    }
  }

</code>```

Body:
On startup I call restorePurchases() to get the previous bought subscriptions.

This works fine but I also get subscriptions which where canceled by the user before!
They have status PurchaseStatus.restored and pendingCompletePurchase is true even though I called completePurchase().

How do I know if the purchase is still valid and not canceled by the user?

Future<void> initializeProAccountPurchase(context) async {
    available = await IAPService.checkIAPAvailability();

    if (available) {
      await IAPService.restorePurchases().onError((error, stackTrace) =>
          {print("error restore"), print(error.userInfo)});
      await getProAccountDetails({'subs_item_purchase', 'pro_account'});
    }
  }


问:
React-native app not auto starting on boot
I want to load my app after the phone reboots. For this I am using this in manifest file:

```<code>
    <receiver android:name="com.app.BootReceiver" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
      </intent-filter>
    </receiver>
</code>```

and I have BootReceiver Class which is :

```<code>
    package com.app;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;

    public class BootReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
           Intent myIntent = new Intent(context, MainActivity.class);
           myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           context.startActivity(myIntent);
       }
    }

</code>```

It works when I run my application on an attached device with  npx react-native run-android command.
But when I create a release build APK to test it on a device it doesn't work. On the same device if I attach it to computer and install the app using react-native run-android, app automatically gets started after phone restart

What am I missing here??

I want to reload my app automatically if it was already running in the background after the phone reboots

Body:
I want to load my app after the phone reboots. For this I am using this in manifest file:

    <receiver android:name="com.app.BootReceiver" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
      </intent-filter>
    </receiver>

and I have BootReceiver Class which is :

    package com.app;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;

    public class BootReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
           Intent myIntent = new Intent(context, MainActivity.class);
           myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           context.startActivity(myIntent);
       }
    }

It works when I run my application on an attached device with  npx react-native run-android command.
But when I create a release build APK to test it on a device it doesn't work. On the same device if I attach it to computer and install the app using react-native run-android, app automatically gets started after phone restart

What am I missing here??

I want to reload my app automatically if it was already running in the background after the phone reboots


问:
auto remove android app old version before update
Is there a possibility to set up a new version of my android application so that when Play Market updates my application it(Play Market) first fully uninstalls the old app version of my application and then installs the new version?</p>


问:
How to avoid regex catastrophic backtracking on identifying links in a long string?
For context, the Python script I work with must analyze a constant stream of moderately sized strings (anywhere from 100 to 1000 characters) to identify whether they contain links and how many characters the string is if links were removed. After a good few iterations of various regex code found online, the most reliable and effective method of identifying the links I have tested is the following:

```<code>(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))
</code>```

A generalized version of the script I am running can be found below:

```<code>link_identifiers = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|("
                        r"\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,"
                        r"<>?«»“”‘’]))"

for string in string_stream:
    # Find all links within the string text and sum the total character count
    links = re.findall(link_identifiers, string, re.IGNORECASE)
    link_char = sum(len(link[0]) for link in links)

    # Report the text count without links
    print(len(string) - link_char)
</code>```

However, this format causes an immense amount of CPU usage due to catastrophic backtracking on the link_identifiers regex code. The strings within string_stream often contain uncommon link formats such as URL shorteners and custom domains, so simply checking for the common "com/gov/org" is not sufficient.

My application requires that code be as minimal as possible when it comes to RAM and CPU usage. How can I design a regex link identifier that is comprehensive but does not use immense resources?

Thank you.

Body:
For context, the Python script I work with must analyze a constant stream of moderately sized strings (anywhere from 100 to 1000 characters) to identify whether they contain links and how many characters the string is if links were removed. After a good few iterations of various regex code found online, the most reliable and effective method of identifying the links I have tested is the following:

(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))

A generalized version of the script I am running can be found below:

link_identifiers = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|("
                        r"\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,"
                        r"<>?«»“”‘’]))"

for string in string_stream:
    # Find all links within the string text and sum the total character count
    links = re.findall(link_identifiers, string, re.IGNORECASE)
    link_char = sum(len(link[0]) for link in links)

    # Report the text count without links
    print(len(string) - link_char)

However, this format causes an immense amount of CPU usage due to catastrophic backtracking on the link_identifiers regex code. The strings within string_stream often contain uncommon link formats such as URL shorteners and custom domains, so simply checking for the common "com/gov/org" is not sufficient.

My application requires that code be as minimal as possible when it comes to RAM and CPU usage. How can I design a regex link identifier that is comprehensive but does not use immense resources?

Thank you.


问:
Orscoreci R function question, confidence interval for odds ratio
I was given the next exercise:

In a Retrospective case-control study we measure the Association between lung cancer and smoking.

709 cases and 709 controls were selected, and the exposition was measured as a binary whether the subject ever was a smoker.

```<code>Predictor  Disease1 Disease2 Total
  Exposed1      688      650  1338
  Exposed2       21       59    80
  Total         709      709  1418
</code>```

I was requested to calculate the OR and its 95% confidence interval.
First, I did it by hand and I got the next results:

```<code>ln(odds ratio)+- z alpha/2(SE):
ln(2.97)+-1.96(0.2599)

-> 1.089+1.96(0.2599) = 1.5984
-> 1.089-1.96(0.2599) = 0.5795
</code>```

Confidence intervals:

(exp(0.5795), exp(1.5984)) = (e^0.5795, e^1.5984) = (1.78 , 4.94)

So far, all clear, now, I need to do it in R, the instructor told me I had to use the function orscoreci in this way:

```<code>library('PropCIs')
orscoreci(688, 709, 650, 709, conf.level = 0.95)
</code>```

My question is: Why should I use the total values 709, 709 instead of 21, 59 in the function if I did not consider these totals when I calculated the result by hand?

Thanks! :)

Exercise result by hand: (1.78 , 4.94)
Exercise result on R: (1.78 , 4.94)

Question related to the orscoreci function in R. How the function works.

Body:
I was given the next exercise:

In a Retrospective case-control study we measure the Association between lung cancer and smoking.

709 cases and 709 controls were selected, and the exposition was measured as a binary whether the subject ever was a smoker.

Predictor  Disease1 Disease2 Total
  Exposed1      688      650  1338
  Exposed2       21       59    80
  Total         709      709  1418

I was requested to calculate the OR and its 95% confidence interval.
First, I did it by hand and I got the next results:

ln(odds ratio)+- z alpha/2(SE):
ln(2.97)+-1.96(0.2599)

-> 1.089+1.96(0.2599) = 1.5984
-> 1.089-1.96(0.2599) = 0.5795

Confidence intervals:

(exp(0.5795), exp(1.5984)) = (e^0.5795, e^1.5984) = (1.78 , 4.94)

So far, all clear, now, I need to do it in R, the instructor told me I had to use the function orscoreci in this way:

library('PropCIs')
orscoreci(688, 709, 650, 709, conf.level = 0.95)

My question is: Why should I use the total values 709, 709 instead of 21, 59 in the function if I did not consider these totals when I calculated the result by hand?

Thanks! :)

Exercise result by hand: (1.78 , 4.94)
Exercise result on R: (1.78 , 4.94)

Question related to the orscoreci function in R. How the function works.


问:
Why are environment variables stored inside env file not visible inside the docker-compose service command?
I have a local.env file:

```<code>POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=devdb
POSTGRES_URL=postgres
</code>```

and i have a docker-compose file which should use these variables:

```<code>version: '3.8'

services:
    postgres:
        image: postgres:12
        restart: always
        ports:
            - '5432:5432'
        volumes:
            - ./db_data:/var/lib/postgresql/data
        env_file:
            - local.env
        healthcheck:
            test: [ "CMD", "pg_isready", "-q", "-d", "devdb", "-U","postgres" ]
            timeout: 45s
            interval: 10s
            retries: 10
    migrate:
        image: migrate/migrate
        restart: on-failure
        depends_on:
          postgres:
            condition: service_healthy
        env_file:
            - local.env
        volumes:
            - ./server/migrations:/migrations
        command:
            [ "-database",  "postgres://postgres:postgres@postgres:5432/devdb?sslmode=disable" , "-path", "/migrations", "up" ]

</code>```

The command inside the migrate service works correctly in this form. Now I want to take these variables from the local.env file and I change it to:

```<code>[ "-database",  "postgres://$$POSTGRES_USER:$$POSTGRES_PASSWORD@$$POSTGRES_IP:$$POSTGRES_PORT/$$POSTGRES_DB?sslmode=disable" , "-path", "/migrations", "up" ]
</code>```

And after that at the start of the launch I get the error :

```<code>error: parse "postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_IP:$POSTGRES_PORT/$POSTGRES_DB?sslmode=disable": invalid port ":$POSTGRES_PORT" after host
</code>```

That is, as I understand it, these values are not replaced with values from the file.I tried to use ${} instead of $$, but the result is the same.

What am I doing wrong? or is it a mistake in something else?

Body:
I have a local.env file:

POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=devdb
POSTGRES_URL=postgres

and i have a docker-compose file which should use these variables:

version: '3.8'

services:
    postgres:
        image: postgres:12
        restart: always
        ports:
            - '5432:5432'
        volumes:
            - ./db_data:/var/lib/postgresql/data
        env_file:
            - local.env
        healthcheck:
            test: [ "CMD", "pg_isready", "-q", "-d", "devdb", "-U","postgres" ]
            timeout: 45s
            interval: 10s
            retries: 10
    migrate:
        image: migrate/migrate
        restart: on-failure
        depends_on:
          postgres:
            condition: service_healthy
        env_file:
            - local.env
        volumes:
            - ./server/migrations:/migrations
        command:
            [ "-database",  "postgres://postgres:postgres@postgres:5432/devdb?sslmode=disable" , "-path", "/migrations", "up" ]

The command inside the migrate service works correctly in this form. Now I want to take these variables from the local.env file and I change it to:

[ "-database",  "postgres://$$POSTGRES_USER:$$POSTGRES_PASSWORD@$$POSTGRES_IP:$$POSTGRES_PORT/$$POSTGRES_DB?sslmode=disable" , "-path", "/migrations", "up" ]

And after that at the start of the launch I get the error :

error: parse "postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_IP:$POSTGRES_PORT/$POSTGRES_DB?sslmode=disable": invalid port ":$POSTGRES_PORT" after host

That is, as I understand it, these values are not replaced with values from the file.I tried to use ${} instead of $$, but the result is the same.

What am I doing wrong? or is it a mistake in something else?


问:
Quasar Router routes not found
I'm using for the first time quasar router, I already know how to use Vue router and this one should be almost the same, and it quite is but the problem is it doesn't work, I have created a Login Page and tried to insert the route in routes.ts file but now i can't access the main page neither the login one, and when I look in the console I get this error: "Failed to fetch dynamically imported module: http://localhost:9000/src/layouts/MainLayout.vue".
Here's the code:

Routes.ts

```<code>import { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    // Main Page
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/QuestionsPage.vue') },
    ],
  },

  {
    path: '/login',
    component: () => import('pages/LoginPage.vue'),
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;
</code>```

In case you need the login page and the main one:

```<code><script setup lang="ts"></script>

<template>
  <q-page padding>
    <h1>Login</h1>
  </q-page>
</template>

</code>```
```<code><script setup>
console.log('test');
</script>

<template>
  <q-page padding>
    <h1>Main Page</h1>
  </q-page>
</template>
</code>```

File structure:

Title: Quasar Router routes not found

Body:
I'm using for the first time quasar router, I already know how to use Vue router and this one should be almost the same, and it quite is but the problem is it doesn't work, I have created a Login Page and tried to insert the route in routes.ts file but now i can't access the main page neither the login one, and when I look in the console I get this error: "Failed to fetch dynamically imported module: http://localhost:9000/src/layouts/MainLayout.vue".
Here's the code:

Routes.ts

import { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    // Main Page
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/QuestionsPage.vue') },
    ],
  },

  {
    path: '/login',
    component: () => import('pages/LoginPage.vue'),
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;

In case you need the login page and the main one:

<template>
  <q-page padding>

Login

  </q-page>
</template>

<template>
  <q-page padding>

Main Page

  </q-page>
</template>

File structure:


问:
how i can fix my problem with Relative protocol?
i had set (ON) Relative protocol from WP rocket by mistake and i had problem now because i change it from off to on,
is there any idea how to solve it ?

any help please ?
thanks
Best Regards
Tawfiq


问:
ansible-galaxy command not using http_proxy
I have a strange problem. For some reason, ansible-galaxy command is not using my defined http proxy.

I am getting the following error:

```<code>sudo ansible-galaxy collection install community.docker
[sudo] password for <user>:
 [WARNING]: - collection was NOT installed successfully: Failed to get data from the API server (https://galaxy.ansible.com/api/): Failed to connect to galaxy.ansible.com at port 443: [Errno 110]
Connection timed out

ERROR! - you can use --ignore-errors to skip failed roles and finish processing the list.
</code>```

I defined multiple variables to make sure proxy is triggered.
http_proxy
https_proxy
HTTP_PROXY
HTTPS_PROXY

Through wireshark analysis I can see that command ansible-galaxy collection install community.docker is trying to reach galaxy.ansible.com directly (resolving to: 104.206.0.234). It should go via proxy.

I also analyzed curl google.com and I can confirm that this traffic is going through http proxy, so the proxy is 100% working correctly.

```<code>**ansible version**
ansible 2.5.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/<user>/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.17 (default, Jul  1 2022, 15:56:32) [GCC 7.5.0]

</code>```

Body:
I have a strange problem. For some reason, ansible-galaxy command is not using my defined http proxy.

I am getting the following error:

sudo ansible-galaxy collection install community.docker
[sudo] password for <user>:
 [WARNING]: - collection was NOT installed successfully: Failed to get data from the API server (https://galaxy.ansible.com/api/): Failed to connect to galaxy.ansible.com at port 443: [Errno 110]
Connection timed out

ERROR! - you can use --ignore-errors to skip failed roles and finish processing the list.

I defined multiple variables to make sure proxy is triggered.
http_proxy
https_proxy
HTTP_PROXY
HTTPS_PROXY

Through wireshark analysis I can see that command ansible-galaxy collection install community.docker is trying to reach galaxy.ansible.com directly (resolving to: 104.206.0.234). It should go via proxy.

I also analyzed curl google.com and I can confirm that this traffic is going through http proxy, so the proxy is 100% working correctly.

**ansible version**
ansible 2.5.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/<user>/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.17 (default, Jul  1 2022, 15:56:32) [GCC 7.5.0]


问:
How to get all urls list from the database | MySQL and Next JS
I want to take all the urls from my database but i don't know what is the right code to do it.
I've been struggling for 2 days to search but can't figure out how to do it.

This is in my current code in index.js in server folder.
In this file i alse make login and register, just watch tutorial from youtube, don't really know how it works of the dependecies, just a little bit.

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const passport = require("passport");
const expressSession = require("express-session");
const cookieParser = require("cookie-parser");
const bcrypt = require("bcrypt");
const db = require("./db");

const app = express();

app.get("/getUrls", (req, res) => {
    const url = req.body.url;

    const query = "SELECT * FROM db_indexer.urls";
    res.send(query);
});
```
<p>and this is in the front end code.</p>
<pre class="lang-js prettyprint-override"><code>import axios from "axios";
import React, { useEffect, useState } from "react";

export default function processUrl() {

    const [urls, setUrls] = useState([]);

    useEffect(() => {
        getUrls();
    }, []);

    const getUrls = () => {
        axios({
            method: "GET",
            withCredentials: true,
            url: "http://localhost:3001/getUrls",
        })
            .then((res) => {
                setUrls(res.data.url);
            })
            .catch((err) => console.log(err));
    };

    return (
        <div>
            <section className="text-black body-font">
                <div className="container px-5 py-24 mx-auto">
                    <div className="lg:w-2/3 w-full mx-auto overflow-auto">
                        <table className="table-auto w-full text-left whitespace-no-wrap">
                            <thead className="text-center">
                                <tr>
                                    <th className=" px-20 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl">
                                        Status
                                    </th>
                                    <th className="w-full py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">
                                        Links
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                {urls.map((result, id) => {
                                    return (
                                        <tr className="results" key={id}>
                                            <td className="px-4 py-3 text-emerald-500 text-center">
                                                Success
                                            </td>
                                            <td className="px-4 py-3">

                                                    {result.url}

                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    );
}
</code>```

anyway my database looks like this
enter image description here

any solution or if you can fixed my code, it would really help me :)

edit : my error like this
enter image description here

Body:
I want to take all the urls from my database but i don't know what is the right code to do it.
I've been struggling for 2 days to search but can't figure out how to do it.

This is in my current code in index.js in server folder.
In this file i alse make login and register, just watch tutorial from youtube, don't really know how it works of the dependecies, just a little bit.

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const passport = require("passport");
const expressSession = require("express-session");
const cookieParser = require("cookie-parser");
const bcrypt = require("bcrypt");
const db = require("./db");

const app = express();

app.get("/getUrls", (req, res) => {
    const url = req.body.url;

    const query = "SELECT * FROM db_indexer.urls";
    res.send(query);
});

and this is in the front end code.

import axios from "axios";
import React, { useEffect, useState } from "react";

export default function processUrl() {

    const [urls, setUrls] = useState([]);

    useEffect(() => {
        getUrls();
    }, []);

    const getUrls = () => {
        axios({
            method: "GET",
            withCredentials: true,
            url: "http://localhost:3001/getUrls",
        })
            .then((res) => {
                setUrls(res.data.url);
            })
            .catch((err) => console.log(err));
    };

    return (

                                        Status

                                        Links

                                {urls.map((result, id) => {
                                    return (

                                                Success

                                                    {result.url}

                                    );
                                })}

    );
}

anyway my database looks like this
enter image description here

any solution or if you can fixed my code, it would really help me :)

edit : my error like this
enter image description here


问:
ASP.NET MVC CrystalReportViewer - Exception with max number report processing
We had problem with usages of CrystalReportViewer for ASP.NET MVC (webforms control from SAP). Sometimes we get this exception:

CrystalDecisions.Shared.CrystalReportsException: Report could not be loaded.

System.Runtime.InteropServices.COMException: The maximum number of report processing requests set by your system administrator has been reached.

Notes - WebForm page:

```<code><CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" HasRefreshButton="True" />
</code>```

In C# is only set ReportSource and then is stored to the ASP.NET MVC session.

We save in code object ReportDocument (CrystalReportViewer.ReportSource) to the ASP.NET MVC session.

After session ends we call ReportDocument.Close() and ReportDocument.Dispose().

But still are information about reports somehow in memory and user got exception with max number of reports. Only what helps is on ISS recycle application pool or set some high number in Windows registry (\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Report Application Server\Server\PrintJobLimit).

Do someone know how should be ReportDocument/ReportViewer properly cleared ?

Body:
We had problem with usages of CrystalReportViewer for ASP.NET MVC (webforms control from SAP). Sometimes we get this exception:

CrystalDecisions.Shared.CrystalReportsException: Report could not be loaded.

System.Runtime.InteropServices.COMException: The maximum number of report processing requests set by your system administrator has been reached.

Notes - WebForm page:

<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" HasRefreshButton="True" />

In C# is only set ReportSource and then is stored to the ASP.NET MVC session.

We save in code object ReportDocument (CrystalReportViewer.ReportSource) to the ASP.NET MVC session.

After session ends we call ReportDocument.Close() and ReportDocument.Dispose().

But still are information about reports somehow in memory and user got exception with max number of reports. Only what helps is on ISS recycle application pool or set some high number in Windows registry (\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Report Application Server\Server\PrintJobLimit).

Do someone know how should be ReportDocument/ReportViewer properly cleared ?


问:
Deployment issue in Websphere Portal
I'm facing some deployment issues on the Websphere Portal version 8.5 running on a clustered environment.
The deployment happens through by calling the xmlaccess.sh script. The deployment is working fine but it is taking too much time.
There are a few xmls which are being imported by the xmlaccess and it connects to the url: http://serverhost:10039/wps/config

webmodule.delete

webmodule.import

portal-content.delete

portal-content.import

The webmodule.import & portal-content.import is taking ~20mins each. Total time 45mins.

The server has federated LDAP repository but there is no issue on the LDAP as the application uses the same LDAP server for login and it's very responsive.

We have increased the jvm heap size to:
Initial Heap Memory - 4096m
Maximum Heap Memory - 8192m
The dmgr has a initial and maximum heap memory of 3072m.

Also there are no exceptions in the sysout logs during the deployment. I have enabled the trace option but still not finding any issue.

Also noticed one thing, when opening the websphere portal admin console, the response is very slow. The page is taking ~1m to load.

The hardware configs for the server are -
OS - Solaris
Ram - 16 GB
4CORE CPU

Increased the heap memory on jvms and dmgr.
Set java.net.preferIPv4Stack=true for the jvms, dmgr and node agents.

Title: Deployment issue in Websphere Portal


问:
layout.sectionHeadersPinToVisibleBounds in UICollectionViewDiffableDataSource
I want to keep the header in a UICollectionViewDiffableDataSource, as I understand I can do it with layout.sectionHeadersPinToVisibleBounds, but it's not usable with my collectionView layout

```<code>  private func createLayout() -> UICollectionViewLayout {

        return UICollectionViewCompositionalLayout { section, layoutEnvironment in
            var config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
            config.headerMode = section == 0 ? .none : .firstItemInSection
            config.backgroundColor = .darkGrayBackground
            config.showsSeparators = false
            let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment)
            section.interGroupSpacing = 30
            self.addHeader(to: section)
            return section
        }
    }

    private func addHeader(to section: NSCollectionLayoutSection) {
        let headerFooterSize = NSCollectionLayoutSize(
          widthDimension: .fractionalWidth(1.0),
          heightDimension: .estimated(20)
        )
        let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
          layoutSize: headerFooterSize,
          elementKind: UICollectionView.elementKindSectionHeader,
          alignment: .top
        )
        section.boundarySupplementaryItems = [sectionHeader]
    }
</code>```

and

```<code>        collectionView = UICollectionView(frame: bounds, collectionViewLayout: createLayout())
</code>```

I even can't access to it via

```<code>    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.sectionHeadersPinToVisibleBounds = true // never called
    }
</code>```

Could anyone help me on this? Thank you so much

Body:
I want to keep the header in a UICollectionViewDiffableDataSource, as I understand I can do it with layout.sectionHeadersPinToVisibleBounds, but it's not usable with my collectionView layout

  private func createLayout() -> UICollectionViewLayout {

        return UICollectionViewCompositionalLayout { section, layoutEnvironment in
            var config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
            config.headerMode = section == 0 ? .none : .firstItemInSection
            config.backgroundColor = .darkGrayBackground
            config.showsSeparators = false
            let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment)
            section.interGroupSpacing = 30
            self.addHeader(to: section)
            return section
        }
    }

    private func addHeader(to section: NSCollectionLayoutSection) {
        let headerFooterSize = NSCollectionLayoutSize(
          widthDimension: .fractionalWidth(1.0),
          heightDimension: .estimated(20)
        )
        let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
          layoutSize: headerFooterSize,
          elementKind: UICollectionView.elementKindSectionHeader,
          alignment: .top
        )
        section.boundarySupplementaryItems = [sectionHeader]
    }

and

        collectionView = UICollectionView(frame: bounds, collectionViewLayout: createLayout())

I even can't access to it via

    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.sectionHeadersPinToVisibleBounds = true // never called
    }

Could anyone help me on this? Thank you so much


问:
How to iterate through an ArrayList containing Objects using JSTL?
I want to iterate through a ArrayList containing Objects using JSTL.

So what I currently have is:

```<code>ArrayList<Animals> allAnimals = DatabaseF.findAnimals();
request.setAttribute("animals", allAnimals)

for (int i = 0; i < allAnimals.size(); i++) {
allAnimals.get(i).getName();

</code>```

now my JSTL

```<code><c:forEach items="${ animals }" var="i">
    <tr>
      <td>${ animals.get(i).getName() }</td>
    </tr>
</c:forEach>
</code>```

How does that work? I want to display all the different animal names in a table, but instead I just get the same animal name from index 0.

Body:
I want to iterate through a ArrayList containing Objects using JSTL.

So what I currently have is:

ArrayList<Animals> allAnimals = DatabaseF.findAnimals();
request.setAttribute("animals", allAnimals)

for (int i = 0; i < allAnimals.size(); i++) {
allAnimals.get(i).getName();

now my JSTL

<c:forEach items="${ animals }" var="i">

      ${ animals.get(i).getName() }

</c:forEach>

How does that work? I want to display all the different animal names in a table, but instead I just get the same animal name from index 0.


问:
Plugin [id: 'com.android.application', version: '7.3.1', apply: false] was not found in any of the following sources:
I'm facing below error when I try to sync my new project:

Plugin [id: 'com.android.application', version: '7.3.1', apply: false] was not found in any of the following sources:

Try:
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Exception is:
org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'com.android.application', version: '7.3.1', apply: false] was not found in any of the following sources:

Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
Plugin Repositories (could not resolve plugin artifact 'com.android.application:com.android.application.gradle.plugin:7.3.1')
Searched in the following repositories:
Gradle Central Plugin Repository
Google

I have installed android studio with below version:

Android Studio Dolphin | 2021.3.1 Patch 1
Build #AI-213.7172.25.2113.9123335, built on September 30, 2022
Runtime version: 11.0.13+0-b1751.21-8125866 amd64

I tried many solutions from stackoverflow but none of them working.

I have connected with office VPN network is this blocking gradle build ? If yes Please let me know how can I resolve this.


问:
Sockets: how does sockets work on mobile app?
I've never worked on mobile app project.

In web app we can create a server with origin http://localhost:3000 and the client can connect to server with http://localhost:4000/sockets for example.

On mobile app how does it work ? Each app on mobile phone are not located on specific http url...


问:
Doing one massive export
I have 23 data frames listed as followed sorted into 3 seperate lists link to project https://posit.cloud/content/4971864

```<code>final_dfs_2015= list(July_2015F,August_2015F, Sept_2015F,Oct_2015F,Dec_2015f)

final_dfs_2016= list(Jan_2016f, Feb_2016F, March_2016f,April_2016f,May_2016f,June_2016f,July_2016f,Aug_2016f, Sept_2016f, Oct_2016f, Nov_2016f, Dec_2016f)

final_dfs_2017= list(Jan_2017f, Feb_2017f,March_2017f,Apri_2017f,May_2017f,June_2017f)
</code>```

id also like to add the file name as the name of each graph if possible
I am using

```<code>barplot(height=Sept_2015F$Frequency,
  names=Sept_2015F$arrival_date_day_of_month, col="#69b3a2")
</code>```

to create plots however something i want to learn is how would i combine the lists if possible with the barplot and some form of exporting to mass export plots all at once
all dataframes have the same 2 columns "arrival_date_day_of_month, frequency"

Im not sure what kind of export to use and how to combine all the things i want to do at once with the data if anyone has any sources on that overall idea id love to read on them.

Title: Doing one massive export

Body:
I have 23 data frames listed as followed sorted into 3 seperate lists link to project https://posit.cloud/content/4971864

final_dfs_2015= list(July_2015F,August_2015F, Sept_2015F,Oct_2015F,Dec_2015f)

final_dfs_2016= list(Jan_2016f, Feb_2016F, March_2016f,April_2016f,May_2016f,June_2016f,July_2016f,Aug_2016f, Sept_2016f, Oct_2016f, Nov_2016f, Dec_2016f)

final_dfs_2017= list(Jan_2017f, Feb_2017f,March_2017f,Apri_2017f,May_2017f,June_2017f)

id also like to add the file name as the name of each graph if possible
I am using

barplot(height=Sept_2015F$Frequency,
  names=Sept_2015F$arrival_date_day_of_month, col="#69b3a2")

to create plots however something i want to learn is how would i combine the lists if possible with the barplot and some form of exporting to mass export plots all at once
all dataframes have the same 2 columns "arrival_date_day_of_month, frequency"

Im not sure what kind of export to use and how to combine all the things i want to do at once with the data if anyone has any sources on that overall idea id love to read on them.


问:
Fill NA based on another two columns but each NA row is calculated differently in different orders
I have a data, a sample of which is shown below:

```<code>rng = pd.DatetimeIndex(np.tile(pd.date_range(start='2010-01-31', end='2010-06-30', freq='M'), 2))
group = np.concatenate(((np.tile('A', 3)), (np.tile('B',3)), (np.tile('A', 3)), (np.tile('B', 3))))
base = [0.4, np.nan, np.nan, 0.6, np.nan, np.nan, 0.5, np.nan, np.nan, 0.5, np.nan, np.nan]
growth = [0.1, np.nan, np.nan, 0.2, np.nan, np.nan, 0.3, np.nan, np.nan, 0.4, np.nan, np.nan]
df = pd.DataFrame({'date': rng, 'group': group, 'base': base, 'growth': growth})
</code>```

for the first nan for each group, I want it to be calculated as 0.4*(1+0.1) for A and 0.6*(1+0.2) for B. For the second nan for each group, I want it to be calculated as 0.4*(1+0.1)*(1+0.1) for A and 0.6*(1+0.2)*(1+0.2) for B. For the third nan for each group, I want it be calculated as 0.5*(1+0.3) for A and 0.5*(1+0.4) for B. For the last nan for each group, I want it to be calculated as 0.5*(1+0.3)*(1+0.3) for A and 0.5*(1+0.4)*(1+0.4) for each group.

Below is what I did. I thought I was close, but not sure about the last few steps.

```<code>df['base2'] = df.groupby(['group'])['base'].apply(lambda x: x.ffill())
df['growth2'] = df.groupby(['group'])['growth'].apply(lambda x: x.ffill())
df['result'] = df.groupby('date')['base2'].apply(lambda x: x.cumprod()+1)
</code>```

Body:
I have a data, a sample of which is shown below:

rng = pd.DatetimeIndex(np.tile(pd.date_range(start='2010-01-31', end='2010-06-30', freq='M'), 2))
group = np.concatenate(((np.tile('A', 3)), (np.tile('B',3)), (np.tile('A', 3)), (np.tile('B', 3))))
base = [0.4, np.nan, np.nan, 0.6, np.nan, np.nan, 0.5, np.nan, np.nan, 0.5, np.nan, np.nan]
growth = [0.1, np.nan, np.nan, 0.2, np.nan, np.nan, 0.3, np.nan, np.nan, 0.4, np.nan, np.nan]
df = pd.DataFrame({'date': rng, 'group': group, 'base': base, 'growth': growth})

for the first nan for each group, I want it to be calculated as 0.4*(1+0.1) for A and 0.6*(1+0.2) for B. For the second nan for each group, I want it to be calculated as 0.4*(1+0.1)*(1+0.1) for A and 0.6*(1+0.2)*(1+0.2) for B. For the third nan for each group, I want it be calculated as 0.5*(1+0.3) for A and 0.5*(1+0.4) for B. For the last nan for each group, I want it to be calculated as 0.5*(1+0.3)*(1+0.3) for A and 0.5*(1+0.4)*(1+0.4) for each group.

Below is what I did. I thought I was close, but not sure about the last few steps.

df['base2'] = df.groupby(['group'])['base'].apply(lambda x: x.ffill())
df['growth2'] = df.groupby(['group'])['growth'].apply(lambda x: x.ffill())
df['result'] = df.groupby('date')['base2'].apply(lambda x: x.cumprod()+1)


问:
mega api how get a full path
I'm using mega.py to upload a file and works fine but i'd like to know if there is a way to a get a mega directory as a full path (string) to use with others services

```<code>from mega import Mega
mega = Mega()
m = mega.login('email','password')
folder = m.find('my_mega_folder')
m.upload('myfile.doc', folder[0])
</code>```

i'd like to get path to use instead of upload()

Title: mega api how get a full path

Body:
I'm using mega.py to upload a file and works fine but i'd like to know if there is a way to a get a mega directory as a full path (string) to use with others services

from mega import Mega
mega = Mega()
m = mega.login('email','password')
folder = m.find('my_mega_folder')
m.upload('myfile.doc', folder[0])

i'd like to get path to use instead of upload()


问:
/CETCOMPAT, DLL's and EXE's
We are looking into updating our application with /CETCOMPAT liker flag. After reading some articles (like Developer Guidance for Hardware-enforced Stack Protection and Understanding Hardware-enforced Stack Protection) and spending some time with running dumpbin /headers against various Windows OS DLL’s and EXE’s, as well as Office, Edge and SQL Server binaries, it is still not clear to us whether we should use this linker flag on just DLL projects or EXE projects as well. What are the rules?</p>

Title: /CETCOMPAT, DLL's and EXE's