问:
BeanShell command line interpreter

~ $ beanshell
BeanShell 2.1.1 - https://github.com/beanshell/beanshell
bsh %
```

↑ this is the command line interpreter I'm talking about.

how can i make it a user friendly interface like, bash / python

is it possible / is there anything like modules/packages which i can install to make it modern.

by modern, i mean features like,

arrow key support, autocompletion,maybe syntax highlighting, etc.

or is there any packages otherthan beanshell, which does same thing but better, like bpython for python/bash,zsh for sh

Title: BeanShell command line interpreter

Body:
~ $ beanshell
BeanShell 2.1.1 - https://github.com/beanshell/beanshell
bsh %

↑ this is the command line interpreter I'm talking about.

how can i make it a user friendly interface like, bash / python

is it possible / is there anything like modules/packages which i can install to make it modern.

by modern, i mean features like,

arrow key support, autocompletion,maybe syntax highlighting, etc.

or is there any packages otherthan beanshell, which does same thing but better, like bpython for python/bash,zsh for sh


来源: stackexchange

问:
Building PowerPoint Add-In: What to do if desired function cannot be done with Office JavaScript API?
I am currently building my first PowerPoint add-in, following instructions from the Office Add-ins documentation

The documentation suggests building add-in's with the Office JavaScript API. However, I am wondering what should I do if the feature I want is not possible with the API?

For example: I want to create a button in my add-in that applies 'send to front' (same as what can be done with the existing PowerPoint GUI) to the selected shape, but I couldn't find the equivalent API to do so.

The question / example also extends to any other complex features I want to have with my add-in that isn't doable with the Office Javascript API.

A potential solution I found is with VBA, and the functionalities do cover "nearly every operation that you can perform with a mouse, keyboard, or a dialog box can also be automated by using VBA"

However, I couldn't find any documentation on how to run VBA within a add-in built with the Office JavaScript API.

Is it just a matter of needing to build an add-in not using the API? Or is there a workaround?

Apologies upfront if this is a stupid question and there is a simple answer.

ContentLicense: CC BY-SA 4.0


问:
Declaring CameraCharactersitics in CameraX to check hardware level
Having issues with manual camera/sensor control (AE + AWB off) with CameraX via the Camera2Interop.

I'm attempting to ensure my test device is capiable of manual control of SENSOR_SENSITIVITY.  For when AE is set to off the image is way too dark, and when SENSOR_SENSITIVITY is at maximum it's better but still too dark and with noise.  That is, without boosted SENSOR_SENSITIVITY I can only get an image by pointing directly at light bulb, so I'm assuming that when I boost SENSOR_SENSITIVITY there is no analog boost, and it's only digitally boosting the signal which gives it noise at maximum.

In attempting to find examples of testing my device's SENSOR_SENSITIVITY range I found this code:

```<code>// Returns true if the device supports the required hardware level, or better.
boolean isHardwareLevelSupported(CameraCharacteristics c, int requiredLevel) {
    final int[] sortedHwLevels = {
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3
    };
    int deviceLevel = c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);

    Toast.makeText(this, deviceLevel, Toast.LENGTH_LONG).show();

    if (requiredLevel == deviceLevel) {
        return true;
    }

    for (int sortedlevel : sortedHwLevels) {
        if (sortedlevel == requiredLevel) {
            return true;
        } else if (sortedlevel == deviceLevel) {
            return false;
        }
    }
    return false; // Should never reach here
}
</code>```

However, I'm having issues calling it.  How do I declare CameraCharacteristics in the context of CameraX and for the purpose of this code?  This was my attempt based on example code:

```<code>CameraManager manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
//String mCameraId = manager.getCameraIdList();
CameraCharacteristics c = manager.getCameraCharacteristics(mCameraId);

isHardwareLevelSupported(c,3);
</code>```

The example code brought me to the issue of declaring and initializing mCameraId.

This was another attempt at checking:

```<code>Range<Integer> range = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
int max = range.getUpper();
int min = range.getLower();
</code>```

I'm probably missing something simple.  Most examples I find have been in the context of Camera2 or in Koltin which I was having issues translating to Java.

Body:
Having issues with manual camera/sensor control (AE + AWB off) with CameraX via the Camera2Interop.

I'm attempting to ensure my test device is capiable of manual control of SENSOR_SENSITIVITY.  For when AE is set to off the image is way too dark, and when SENSOR_SENSITIVITY is at maximum it's better but still too dark and with noise.  That is, without boosted SENSOR_SENSITIVITY I can only get an image by pointing directly at light bulb, so I'm assuming that when I boost SENSOR_SENSITIVITY there is no analog boost, and it's only digitally boosting the signal which gives it noise at maximum.

In attempting to find examples of testing my device's SENSOR_SENSITIVITY range I found this code:

// Returns true if the device supports the required hardware level, or better.
boolean isHardwareLevelSupported(CameraCharacteristics c, int requiredLevel) {
    final int[] sortedHwLevels = {
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL,
            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3
    };
    int deviceLevel = c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);

    Toast.makeText(this, deviceLevel, Toast.LENGTH_LONG).show();

    if (requiredLevel == deviceLevel) {
        return true;
    }

    for (int sortedlevel : sortedHwLevels) {
        if (sortedlevel == requiredLevel) {
            return true;
        } else if (sortedlevel == deviceLevel) {
            return false;
        }
    }
    return false; // Should never reach here
}

However, I'm having issues calling it.  How do I declare CameraCharacteristics in the context of CameraX and for the purpose of this code?  This was my attempt based on example code:

CameraManager manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
//String mCameraId = manager.getCameraIdList();
CameraCharacteristics c = manager.getCameraCharacteristics(mCameraId);

isHardwareLevelSupported(c,3);

The example code brought me to the issue of declaring and initializing mCameraId.

This was another attempt at checking:

Range<Integer> range = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
int max = range.getUpper();
int min = range.getLower();

I'm probably missing something simple.  Most examples I find have been in the context of Camera2 or in Koltin which I was having issues translating to Java.


问:
I2S to transmit real time waveform
I am starting with ESP32 board and programming it in C. I am working in an application that needs 4 dac. It has two 8-bit dac. I am thinking to use the i2s interface to send real time waveform and use an amplifier to decode i2s and feed a resistive load.

I guess there are some issues to have in mind:

Latency to send and decode 1 frame. My limit is 200 us.

The filters that audio amplifiers have. The ideal case for my application is not have filters, because I want the waveform as the data sent.

Anyone has idea about this consideration or have any further suggestion?

For now, I tested the two dac available in my ESP32 dev board. The minimum period to generate a sin wave is 100 us using both DAC.

Title: I2S to transmit real time waveform


问:
Disable Expect 100-continue HTTP header from Android app with no code Access
I have an Android app (Unity based) which can be a bit modified (assets / apk configs) but no access to the actual code / unity Project.

The app is sending HTTP requests to an API using header :
Expect 100-continue

Which servers does not support.

Is there a way to disable it from client, maybe using an Android env variable / global config we could set in the APK metadatas ?

Server side is a Apache/Passenger/Wsgi/Flask combo.
When the header is present, it cause all requests to timeout :

Apache logs being :

"Timeout on 100-Continue returned by -url"


问:
Getting around the over (partition by) clause in mySQL
I have been trying to run this query in order to get a rolling count of people vaccinated in different locations but have been receiving a syntax error and I am not sure what to do

Here's the query;

```<code>SELECT
    dea.continent,
    dea.location,
    dea.date,
    dea.population,
    vac.new_vaccinations,
    SUM(CONVERT(INT, vac.new_vaccinations)), OVER (PARTITION BY dea.location order by dea.location, dea.date)as RollingCountPeopleVaccinated
    FROM
    CovidDeaths dea
    JOIN CovidVaccinations vac
      ON
     dea.location= vac.location and
     dea.date= vac.date
     where dea.continent is not null
    ORDER BY
    1,2,3
</code>```

and the result:

Execution finished with errors.
Result: near "BY": syntax error
At line 161:

```<code>SELECT
    dear.continent,
    dea.location,
    dea.date,
    dea.population,
    vac.new_vaccinations,
    SUM(CONVERT(INT, vac.new_vaccinations)), OVER (PARTITION BY
</code>```

What does this error mean?

Body:
I have been trying to run this query in order to get a rolling count of people vaccinated in different locations but have been receiving a syntax error and I am not sure what to do

Here's the query;

SELECT
    dea.continent,
    dea.location,
    dea.date,
    dea.population,
    vac.new_vaccinations,
    SUM(CONVERT(INT, vac.new_vaccinations)), OVER (PARTITION BY dea.location order by dea.location, dea.date)as RollingCountPeopleVaccinated
    FROM
    CovidDeaths dea
    JOIN CovidVaccinations vac
      ON
     dea.location= vac.location and
     dea.date= vac.date
     where dea.continent is not null
    ORDER BY
    1,2,3

and the result:

Execution finished with errors.
Result: near "BY": syntax error
At line 161:

SELECT
    dear.continent,
    dea.location,
    dea.date,
    dea.population,
    vac.new_vaccinations,
    SUM(CONVERT(INT, vac.new_vaccinations)), OVER (PARTITION BY

What does this error mean?


问:
AttributeError: 'Adam' object has no attribute 'step'
Can anyone assist me in solving this error AttributeError: 'Adam' object has no attribute 'step' When Bert Model is trained with NER, this error occurs. I could not solve this problem, perhaps due to the change in libraries, since it mainly stems from the update parameters step().</p>
```<code>from transformers import AdamW
from transformers import get_linear_schedule_with_warmup
from transformers import BertTokenizer, BertForSequenceClassification
from transformers import DataCollatorForTokenClassification
from transformers import AutoModelForTokenClassification

epochs = 5
max_grad_norm = 1.0

for _ in trange(epochs, desc="Epoch"):
    # TRAIN loop
    model.train()
    tr_loss = 0
    nb_tr_examples, nb_tr_steps = 0, 0
    for step, batch in enumerate(train_dataloader):
        # add batch to gpu
        batch = tuple(t.to(device) for t in batch)
        b_input_ids, b_input_mask, b_labels = batch
        # forward pass
        token_classifier_output = model(b_input_ids,
                                        token_type_ids=None,
                                        attention_mask=b_input_mask,
                                        labels=b_labels)
        token_classifier_output.loss.backward()
        # track train loss
        tr_loss += token_classifier_output.loss.item()
        nb_tr_examples += b_input_ids.size(0)
        nb_tr_steps += 1
        # gradient clipping
        torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=max_grad_norm)
        # update parameters
        optimizer.step()
        model.zero_grad()
    # print train loss per epoch
    print("Train loss: {}".format(tr_loss/nb_tr_steps))

     31         # update parameters
---> 32         optimizer.step()
1 frames
/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py in __getattribute__(self, name)
    864     """Overridden to support hyperparameter access."""
    865     try:
--> 866       return super(OptimizerV2, self).__getattribute__(name)
    867     except AttributeError as e:
    868       # Needed to avoid infinite recursion with __setattr__.

AttributeError: 'Adam' object has no attribute 'step'
</code>```

Body:
Can anyone assist me in solving this error AttributeError: 'Adam' object has no attribute 'step' When Bert Model is trained with NER, this error occurs. I could not solve this problem, perhaps due to the change in libraries, since it mainly stems from the update parameters step().

from transformers import AdamW
from transformers import get_linear_schedule_with_warmup
from transformers import BertTokenizer, BertForSequenceClassification
from transformers import DataCollatorForTokenClassification
from transformers import AutoModelForTokenClassification

epochs = 5
max_grad_norm = 1.0

for _ in trange(epochs, desc="Epoch"):
    # TRAIN loop
    model.train()
    tr_loss = 0
    nb_tr_examples, nb_tr_steps = 0, 0
    for step, batch in enumerate(train_dataloader):
        # add batch to gpu
        batch = tuple(t.to(device) for t in batch)
        b_input_ids, b_input_mask, b_labels = batch
        # forward pass
        token_classifier_output = model(b_input_ids,
                                        token_type_ids=None,
                                        attention_mask=b_input_mask,
                                        labels=b_labels)
        token_classifier_output.loss.backward()
        # track train loss
        tr_loss += token_classifier_output.loss.item()
        nb_tr_examples += b_input_ids.size(0)
        nb_tr_steps += 1
        # gradient clipping
        torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=max_grad_norm)
        # update parameters
        optimizer.step()
        model.zero_grad()
    # print train loss per epoch
    print("Train loss: {}".format(tr_loss/nb_tr_steps))

     31         # update parameters
---> 32         optimizer.step()
1 frames
/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py in __getattribute__(self, name)
    864     """Overridden to support hyperparameter access."""
    865     try:
--> 866       return super(OptimizerV2, self).__getattribute__(name)
    867     except AttributeError as e:
    868       # Needed to avoid infinite recursion with __setattr__.

AttributeError: 'Adam' object has no attribute 'step'


问:
how to add function on button click in laravel
i was have my team who was working on my project and certainly some of the reason they quit from this project now am just facing an issue that is whatsapp function is not calling on button click even function are there in code i am not familiar with laravel so much just beginner knowledge i have of laravel...

so kindly please help me i will be really thank ful to you sir

hereis the code of button

```<code><div class="modal-footer">
                            <button class="btn btn-primary" data-bs-target="#exampleModalToggle"
                                data-bs-toggle="modal">Back to first</button>
                            <button class="btn btn-success" id="whatsapp-btn">Whatsapp</button>
                            <button class="btn" data-bs-dismiss="modal" aria-label="Close">Cancel</button>
                        </div>

**here is the function code**

// whatsapp btn
        $('#whatsapp-btn').on('click', function() {
            var message = '';
            $('.checkout-table tr').each(function(i, el) {
                var product = $(el).find('td:first-child').text();
                var qty = $(el).find('input').val();
                message += 'product=  ' + product + 'qty=  ' + qty + ' </br> ';
            })

            var order_type = $('#order_type').val();
            message += 'order type=  ' + order_type + '  ';
            message += '%0a name : ' + $('#name').val();
            message += '%0a email : ' + $('#email').val();
            message += '%0a phone : ' + $('#phone').val();
            message += '%0a instructions : ' + $('#instructions').val();
            var url = 'https://api.whatsapp.com/send?phone=+827667306&text=' + message;
            window.open(url, '_blank');
        })
</code>```

Body:
i was have my team who was working on my project and certainly some of the reason they quit from this project now am just facing an issue that is whatsapp function is not calling on button click even function are there in code i am not familiar with laravel so much just beginner knowledge i have of laravel...

so kindly please help me i will be really thank ful to you sir

hereis the code of button

                            <button class="btn btn-primary" data-bs-target="#exampleModalToggle"
                                data-bs-toggle="modal">Back to first</button>
                            <button class="btn btn-success" id="whatsapp-btn">Whatsapp</button>
                            <button class="btn" data-bs-dismiss="modal" aria-label="Close">Cancel</button>

**here is the function code**

// whatsapp btn
        $('#whatsapp-btn').on('click', function() {
            var message = '';
            $('.checkout-table tr').each(function(i, el) {
                var product = $(el).find('td:first-child').text();
                var qty = $(el).find('input').val();
                message += 'product=  ' + product + 'qty=  ' + qty + '
 ';
            })

            var order_type = $('#order_type').val();
            message += 'order type=  ' + order_type + '  ';
            message += '%0a name : ' + $('#name').val();
            message += '%0a email : ' + $('#email').val();
            message += '%0a phone : ' + $('#phone').val();
            message += '%0a instructions : ' + $('#instructions').val();
            var url = 'https://api.whatsapp.com/send?phone=+827667306&text=' + message;
            window.open(url, '_blank');
        })


问:
sudo password not working while in tmux session
When I open up the terminal on my Mac OSX Ventura and do sudo, my password works perfectly fine. However when I enter any tmux session and try sudo the password won't work. Keeps saying incorrect password. Can anyone please help me why it's behaving that way and what can I do to fix/investigate this?</p>


问:
Characters in inspector is not visible
unity2022.2.0b TMP3.2.0-pre.4

I recently updated my project from 2019LTS.
After that, characters entered in "string" and "textarea" in the inspector are not displayed.

Now, I get one of the following error messages:
1: NullReferenceException: Object reference not set to an instance of an object.
2: MissingReferenceException: The variable m_AtlasTextures of FontAsset doesn't exist anymore.

My language is Japanese.
I know I get similar errors when the TMP textures are full, but I don't use TMP for my project.
It can be fixed by restarting Unity, but it is troublesome because it happens frequently. Anyone know how to solve this?

images of the inspector

Here is the log.

```<code>NullReferenceException: Object reference not set to an instance of an object
UnityEngine.TextCore.Text.FontAsset.SetupNewAtlasTexture () (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAsset.TryAddCharacterInternal (System.UInt32 unicode, UnityEngine.TextCore.Text.Character& character, System.Boolean shouldGetFontFeatures) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAssetUtilities.GetCharacterFromFontAsset_Internal (System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset sourceFontAsset, System.Boolean includeFallbacks, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAssetUtilities.GetCharacterFromFontAsset_Internal (System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset sourceFontAsset, System.Boolean includeFallbacks, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAssetUtilities.GetCharacterFromFontAssets (System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset sourceFontAsset, System.Collections.Generic.List`1[T] fontAssets, System.Boolean includeFallbacks, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.GetTextElement (UnityEngine.TextCore.Text.TextGenerationSettings generationSettings, System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset fontAsset, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isUsingAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.SetArraySizes (UnityEngine.TextCore.Text.TextProcessingElement[] textProcessingArray, UnityEngine.TextCore.Text.TextGenerationSettings generationSettings, UnityEngine.TextCore.Text.TextInfo textInfo) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.Prepare (UnityEngine.TextCore.Text.TextGenerationSettings generationSettings, UnityEngine.TextCore.Text.TextInfo textInfo) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.GetPreferredValues (UnityEngine.TextCore.Text.TextGenerationSettings settings, UnityEngine.TextCore.Text.TextInfo textInfo) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextHandle.UpdatePreferredValues (UnityEngine.TextCore.Text.TextGenerationSettings tgs) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextHandle.ComputeTextWidth (UnityEngine.TextCore.Text.TextGenerationSettings tgs) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.UIElements.UITKTextHandle.ComputeTextWidth (System.String textToMeasure, System.Boolean wordWrap, System.Single width, System.Single height) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.TextUtilities.MeasureVisualElementTextSize (UnityEngine.UIElements.TextElement te, System.String textToMeasure, System.Single width, UnityEngine.UIElements.VisualElement+MeasureMode widthMode, System.Single height, UnityEngine.UIElements.VisualElement+MeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.TextElement.MeasureTextSize (System.String textToMeasure, System.Single width, UnityEngine.UIElements.VisualElement+MeasureMode widthMode, System.Single height, UnityEngine.UIElements.VisualElement+MeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.TextElement.DoMeasure (System.Single desiredWidth, UnityEngine.UIElements.VisualElement+MeasureMode widthMode, System.Single desiredHeight, UnityEngine.UIElements.VisualElement+MeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.VisualElement.Measure (UnityEngine.Yoga.YogaNode node, System.Single width, UnityEngine.Yoga.YogaMeasureMode widthMode, System.Single height, UnityEngine.Yoga.YogaMeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.VisualElement.<AssignMeasureFunction>b__423_0 (UnityEngine.Yoga.YogaNode node, System.Single f, UnityEngine.Yoga.YogaMeasureMode mode, System.Single f1, UnityEngine.Yoga.YogaMeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.Yoga.YogaNode.MeasureInternal (UnityEngine.Yoga.YogaNode node, System.Single width, UnityEngine.Yoga.YogaMeasureMode widthMode, System.Single height, UnityEngine.Yoga.YogaMeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.Yoga.Native.YGNodeMeasureInvoke (UnityEngine.Yoga.YogaNode node, System.Single width, UnityEngine.Yoga.YogaMeasureMode widthMode, System.Single height, UnityEngine.Yoga.YogaMeasureMode heightMode, System.IntPtr returnValueAddress) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEditor.InspectorWindow:RedrawFromNative()
</code>```

Title: Characters in inspector is not visible

Body:
unity2022.2.0b TMP3.2.0-pre.4

I recently updated my project from 2019LTS.
After that, characters entered in "string" and "textarea" in the inspector are not displayed.

Now, I get one of the following error messages:
1: NullReferenceException: Object reference not set to an instance of an object.
2: MissingReferenceException: The variable m_AtlasTextures of FontAsset doesn't exist anymore.

My language is Japanese.
I know I get similar errors when the TMP textures are full, but I don't use TMP for my project.
It can be fixed by restarting Unity, but it is troublesome because it happens frequently. Anyone know how to solve this?

images of the inspector

Here is the log.

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.TextCore.Text.FontAsset.SetupNewAtlasTexture () (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAsset.TryAddCharacterInternal (System.UInt32 unicode, UnityEngine.TextCore.Text.Character& character, System.Boolean shouldGetFontFeatures) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAssetUtilities.GetCharacterFromFontAsset_Internal (System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset sourceFontAsset, System.Boolean includeFallbacks, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAssetUtilities.GetCharacterFromFontAsset_Internal (System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset sourceFontAsset, System.Boolean includeFallbacks, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.FontAssetUtilities.GetCharacterFromFontAssets (System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset sourceFontAsset, System.Collections.Generic.List`1[T] fontAssets, System.Boolean includeFallbacks, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.GetTextElement (UnityEngine.TextCore.Text.TextGenerationSettings generationSettings, System.UInt32 unicode, UnityEngine.TextCore.Text.FontAsset fontAsset, UnityEngine.TextCore.Text.FontStyles fontStyle, UnityEngine.TextCore.Text.TextFontWeight fontWeight, System.Boolean& isUsingAlternativeTypeface) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.SetArraySizes (UnityEngine.TextCore.Text.TextProcessingElement[] textProcessingArray, UnityEngine.TextCore.Text.TextGenerationSettings generationSettings, UnityEngine.TextCore.Text.TextInfo textInfo) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.Prepare (UnityEngine.TextCore.Text.TextGenerationSettings generationSettings, UnityEngine.TextCore.Text.TextInfo textInfo) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextGenerator.GetPreferredValues (UnityEngine.TextCore.Text.TextGenerationSettings settings, UnityEngine.TextCore.Text.TextInfo textInfo) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextHandle.UpdatePreferredValues (UnityEngine.TextCore.Text.TextGenerationSettings tgs) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.TextCore.Text.TextHandle.ComputeTextWidth (UnityEngine.TextCore.Text.TextGenerationSettings tgs) (at <d848a5f0d57c4e96b3f27c1dd5805d00>:0)
UnityEngine.UIElements.UITKTextHandle.ComputeTextWidth (System.String textToMeasure, System.Boolean wordWrap, System.Single width, System.Single height) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.TextUtilities.MeasureVisualElementTextSize (UnityEngine.UIElements.TextElement te, System.String textToMeasure, System.Single width, UnityEngine.UIElements.VisualElement+MeasureMode widthMode, System.Single height, UnityEngine.UIElements.VisualElement+MeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.TextElement.MeasureTextSize (System.String textToMeasure, System.Single width, UnityEngine.UIElements.VisualElement+MeasureMode widthMode, System.Single height, UnityEngine.UIElements.VisualElement+MeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.TextElement.DoMeasure (System.Single desiredWidth, UnityEngine.UIElements.VisualElement+MeasureMode widthMode, System.Single desiredHeight, UnityEngine.UIElements.VisualElement+MeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.VisualElement.Measure (UnityEngine.Yoga.YogaNode node, System.Single width, UnityEngine.Yoga.YogaMeasureMode widthMode, System.Single height, UnityEngine.Yoga.YogaMeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.UIElements.VisualElement.<AssignMeasureFunction>b__423_0 (UnityEngine.Yoga.YogaNode node, System.Single f, UnityEngine.Yoga.YogaMeasureMode mode, System.Single f1, UnityEngine.Yoga.YogaMeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.Yoga.YogaNode.MeasureInternal (UnityEngine.Yoga.YogaNode node, System.Single width, UnityEngine.Yoga.YogaMeasureMode widthMode, System.Single height, UnityEngine.Yoga.YogaMeasureMode heightMode) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEngine.Yoga.Native.YGNodeMeasureInvoke (UnityEngine.Yoga.YogaNode node, System.Single width, UnityEngine.Yoga.YogaMeasureMode widthMode, System.Single height, UnityEngine.Yoga.YogaMeasureMode heightMode, System.IntPtr returnValueAddress) (at <2c62f5a99353486389ce268a5295ac09>:0)
UnityEditor.InspectorWindow:RedrawFromNative()


问:
ImageView positioned on an imageView
Hello I am developing an android application in java under android studio and I want my second image to be positioned at 50% of the height and 20% of the width (for example) of the first image and not the parent, so that the ratio of image overlay is respected with different sizes of screen. I can't find how to do it, do you have an idea?

This is the activity_main.xml :

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

    <EditText
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Your Data" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <TextView
        android:id="@+id/tetx"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <ImageView
        android:id="@+id/iut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".20"
        app:srcCompat="@drawable/iut" />

    <ImageView
        android:id="@+id/marker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".50"
        android:visibility="visible"
        app:srcCompat="@drawable/m2" />

</LinearLayout>
</code>```

I put the xml file but I plan to modify the percentages later in MainActivity.java so it's not disturbing if you have an idea that goes through java code.

Title: ImageView positioned on an imageView

Body:
Hello I am developing an android application in java under android studio and I want my second image to be positioned at 50% of the height and 20% of the width (for example) of the first image and not the parent, so that the ratio of image overlay is respected with different sizes of screen. I can't find how to do it, do you have an idea?

This is the activity_main.xml :

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

    <EditText
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Your Data" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <TextView
        android:id="@+id/tetx"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <ImageView
        android:id="@+id/iut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".20"
        app:srcCompat="@drawable/iut" />

    <ImageView
        android:id="@+id/marker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".50"
        android:visibility="visible"
        app:srcCompat="@drawable/m2" />

</LinearLayout>

I put the xml file but I plan to modify the percentages later in MainActivity.java so it's not disturbing if you have an idea that goes through java code.


问:
Nvim Randomly Exits
My nvim just suddenly closes on certain instances i.e., when i trigger autocomplete or delete something. It's very annoying and i couldn't find some helpful errors to troubleshoot upon checkings all of my logs in .cache/nvim/ there is nothing there that could help me identify the errors since none of the errors i was expecting occured in the current date.

Here is my nvim config for more details: https://github.com/oieeaaaa/dotfiles_v3/tree/master/nvim

Nvim version: v0.9.0

Title: Nvim Randomly Exits


问:
swiftui matchedgeometryeffect is not smooth
I have two views, one view has an HStack that displays a list of views, each containing an image and text. When one view is clicked, a detail view is displayed which will contain the image and text of the selected view.

The problem is the matchedgeometryeffect seems to fade in when transitioning between views. I tried different solution here on stackoverflow such as using .zIndex() and .transition(.scale(scale: 1)) but nothing worked for me.

Here is the behavior I get in simulator: video

Here is the code:

```<code>struct Test: View {
    var body: some View {

    VStack {
        if let selectedCard = selectedCard {
            VStack {
                cardView(card: selectedCard)
                    .onTapGesture {
                        withAnimation() {
                            self.selectedCard = nil
                        }
                    }
            }
        } else {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(topCardsAsTemplates) { topCardAsTemplate in
                        TopTemplatesCardView(card: topCardAsTemplate)
                            .padding()
                            .onTapGesture {
                                withAnimation() {
                                    selectedCard = topCardAsTemplate
                                }
                            }
                    }
                }
            }
        }
    }
}

@ViewBuilder
func TopTemplatesCardView(card: Card) -> some View {

    if card.uuid != selectedCard?.uuid {
        VStack {
            Image(systemName: "person.circle")
                .resizable()
                .matchedGeometryEffect(id: card.uuid.uuidString + "image", in: namespace)
                .scaledToFit()
                .frame(width: 80)

            Text(card.backgroundType.rawValue)
                .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace, properties: .position)
                .foregroundColor(.black)
 //                    .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace)

        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 20, style: .continuous)
                .matchedGeometryEffect(id: card.uuid.uuidString + "back", in: namespace)
                .frame(width: cardSize + 50, height: cardSize + 50)
                .background(.clear)
                .foregroundColor(.gray)
        )

    } else {

        Color.clear.frame(width: cardSize, height: cardSize)
    }
}

    @ViewBuilder
func cardView(card: Card) -> some View {

    VStack {
        Image(systemName: "person.circle")
            .resizable()
            .matchedGeometryEffect(id: card.uuid.uuidString + "image", in: namespace)
            .scaledToFit()
            .frame(width: 120)

        Text(card.backgroundType.rawValue)
            // .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace)
            .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace, properties: .position)
            .foregroundColor(.black)
    }
    .padding()
    .background(
        RoundedRectangle(cornerRadius: 20, style: .continuous)
            .matchedGeometryEffect(id: card.uuid.uuidString + "back", in: namespace)
            .frame(width: cardSize + 200 , height: cardSize + 200)
            .background(.clear)
            .foregroundColor(.gray)
    )
}
}
</code>```

How can I make the transition smoother so that the fading-in and out are not shown? Any suggestions please?

Edit:
After a lot of trial and error, adding .frame(maxWidth: .infinity, maxHeight: .infinity) to the HStack seems to solve the problem for me.
Here is how the HStack looks like now:

```<code>ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(topCardsAsTemplates) { topCardAsTemplate in
                    TopTemplatesCardView(card: topCardAsTemplate)
                        .padding()
                        .onTapGesture {
                            print("display card uuid: \(topCardAsTemplate.uuid.uuidString)")
                            withAnimation(.spring()) {
                                selectedCard = topCardAsTemplate
                            }
                        }
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
</code>```

Hope this helps other people.

Body:
I have two views, one view has an HStack that displays a list of views, each containing an image and text. When one view is clicked, a detail view is displayed which will contain the image and text of the selected view.

The problem is the matchedgeometryeffect seems to fade in when transitioning between views. I tried different solution here on stackoverflow such as using .zIndex() and .transition(.scale(scale: 1)) but nothing worked for me.

Here is the behavior I get in simulator: video

Here is the code:

struct Test: View {
    var body: some View {

    VStack {
        if let selectedCard = selectedCard {
            VStack {
                cardView(card: selectedCard)
                    .onTapGesture {
                        withAnimation() {
                            self.selectedCard = nil
                        }
                    }
            }
        } else {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(topCardsAsTemplates) { topCardAsTemplate in
                        TopTemplatesCardView(card: topCardAsTemplate)
                            .padding()
                            .onTapGesture {
                                withAnimation() {
                                    selectedCard = topCardAsTemplate
                                }
                            }
                    }
                }
            }
        }
    }
}

@ViewBuilder
func TopTemplatesCardView(card: Card) -> some View {

    if card.uuid != selectedCard?.uuid {
        VStack {
            Image(systemName: "person.circle")
                .resizable()
                .matchedGeometryEffect(id: card.uuid.uuidString + "image", in: namespace)
                .scaledToFit()
                .frame(width: 80)

            Text(card.backgroundType.rawValue)
                .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace, properties: .position)
                .foregroundColor(.black)
 //                    .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace)

        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 20, style: .continuous)
                .matchedGeometryEffect(id: card.uuid.uuidString + "back", in: namespace)
                .frame(width: cardSize + 50, height: cardSize + 50)
                .background(.clear)
                .foregroundColor(.gray)
        )

    } else {

        Color.clear.frame(width: cardSize, height: cardSize)
    }
}

    @ViewBuilder
func cardView(card: Card) -> some View {

    VStack {
        Image(systemName: "person.circle")
            .resizable()
            .matchedGeometryEffect(id: card.uuid.uuidString + "image", in: namespace)
            .scaledToFit()
            .frame(width: 120)

        Text(card.backgroundType.rawValue)
            // .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace)
            .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace, properties: .position)
            .foregroundColor(.black)
    }
    .padding()
    .background(
        RoundedRectangle(cornerRadius: 20, style: .continuous)
            .matchedGeometryEffect(id: card.uuid.uuidString + "back", in: namespace)
            .frame(width: cardSize + 200 , height: cardSize + 200)
            .background(.clear)
            .foregroundColor(.gray)
    )
}
}

How can I make the transition smoother so that the fading-in and out are not shown? Any suggestions please?

Edit:
After a lot of trial and error, adding .frame(maxWidth: .infinity, maxHeight: .infinity) to the HStack seems to solve the problem for me.
Here is how the HStack looks like now:

ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(topCardsAsTemplates) { topCardAsTemplate in
                    TopTemplatesCardView(card: topCardAsTemplate)
                        .padding()
                        .onTapGesture {
                            print("display card uuid: \(topCardAsTemplate.uuid.uuidString)")
                            withAnimation(.spring()) {
                                selectedCard = topCardAsTemplate
                            }
                        }
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }

Hope this helps other people.


问:
PropertyChangedCallback called before Binding/ViewModel updates
I am currently building a control library for WPF, WinUI3 and UWP.
I use custom ContentControls for my controls with DependencyProperties.
On some DependencyProperties (e.g. IsChecked) I have to use a PropertyChangedCallback to update some UI related stuff.

First I worked on WPF and evetyhing worked great since I am already used to WPF but I have some issues for UWP and WinUI3.

My Code

First of all Im going to share all my important code that might be related to the issue.

Both (in WPF and UWP) ViewModels and control code behinds are the exact same and Im binding both with a TwoWay binding. Please note that im using 'CommunityToolkit.Mvvm' which shouldnt make any difference through.

This is the DependencyProperty:

public bool IsChecked
{
    get => (bool)GetValue(IsCheckedProperty);
    set => SetValue(IsCheckedProperty, value);
}

public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register(
    "IsChecked", typeof(bool), typeof(ReCaptcha), new PropertyMetadata(false, OnIsCheckedChanged));
```
<p>This is the PropertyChangedCallback:</p>
<pre class="lang-cs prettyprint-override"><code>private static void OnIsCheckedChanged(
    DependencyObject sender,
    DependencyPropertyChangedEventArgs e)
{
    ReCaptcha owner = (ReCaptcha)sender;

    UpdateUI(owner, (bool)e.NewValue ? "True" : "False");

    owner.VerificationRequested?.Invoke(owner, new())
    owner.VerifcationRequestedCommand?.Execute(owner.VerificationRemovedCommandParameter)
}
</code>```

This is the ViewModel:

bool isChecked = false;

public bool IsChecked // IsChecked
{
    get => isChecked;
    set => SetProperty(ref isChecked, value);
}

[RelayCommand] // VerifyCommand
async Task VerifyAsync()
{
   // Do stuff with 'IsChecked'
}
```
<p>This is the XAML:</p>
```<ui:ReCaptcha
    IsChecked="{x:Bind viewModel.IsChecked, Mode=TwoWay}"
    VerificationRequestedCommand="{x:Bind viewModel.VerifyCommand}" />
```

My Issue

Okay. So the user presses something on the control and the DependencyProperty and the ViewModel property update (because of TwoWay binding).

BUT the PropertyChangedCallback (on the DependencyObject) gets called before the Binding (= the ViewModel property) is updated and before the setter of the ViewModel property is called. Since I am calling an event/command (which gets executed in the ViewModel) inside the PropertyChangedCallback the property (IsChecked) still has the old value at the time the event/command fires. This results in weird behaviours and breaks the application.

Calling order

I determinatedthe call order by setting break points wherever properties are updated and callbacks are called. This helped me to track down the problem:

Calling order in WPF (how I expect it to be)

[TRIGGER] User presses something on control

Setter of property 'IsChecked' on ViewModel gets called

PropertyChangedCallback on DependencyObject gets called

VerifyCommand gets invoked and executed ('IsChecked' has NEW value)

Calling order in UWP/WinUI3 (how I dont expect it to be)

[TRIGGER] User presses something on control

PropertyChangedCallback on DependencyObject gets called

VerifyCommand gets invoked and executed ('IsChecked' has OLD value)

Setter of property 'IsChecked' on ViewModel gets called

Furthermore information for UWP/WinUI3

When I hit the break point inside the PropertyChangedCallback on the DependencyObject and I take a look at the properties of the sender object (my custom control) I notice that the 'IsChecked' property has the new value but when I hit the break point inside the VerifyCommand (which comes after the PropertyChangedCallback break point) and take a look at my custom control in the XAML the 'IsChecked' property still has the old value. (Seen in the images bellow).

This leads me to think that something is broken with the binding, but since Im using the exact same binding in WPF (and its working), I don't know what to do.

 Break point in PropertyChangedCallback on DependencyObject.

 Break point in VerifyCommand on ViewModel/XAML.

Notes

I dont know if Im missing something completely, but Ive been stuck on this for many hours and this is my last option, so any help would be appreciated.
Ive tried my best to make the issue as clear as possible, but feel free to ask for any additional information I could provide.

I also tried researching online but there is almost no documentation about PropertyChangedCallbacks on UWP and definitely not about the call order.
I know this is a very specific use case, but I really want to keep the project structure as it is.

Im sorry if I described my problem unclearly and with incorrect grammar/spelling.
Thanks in advance.

I expect the same behavior in UWP/WinUI3 just like in WPF so my ViewModel first gets updated and then the PropertyChangedCallback gets called.

This is important since I have to use the property inside an event/command (in the ViewModel) that gets invoked by the PropertyChangedCallback.

Sample projects

I have created two small sample projects and uploaded them here if its still not clear what the problem is: https://github.com/IcySnex/PropertyChangedCallbackTests.
You can run both projects and take a look at the Debug Output. I have added a few Debug WriteLines so you can see when the callbacks are fired.

Body:
I am currently building a control library for WPF, WinUI3 and UWP.
I use custom ContentControls for my controls with DependencyProperties.
On some DependencyProperties (e.g. IsChecked) I have to use a PropertyChangedCallback to update some UI related stuff.

First I worked on WPF and evetyhing worked great since I am already used to WPF but I have some issues for UWP and WinUI3.

My Code

First of all Im going to share all my important code that might be related to the issue.

Both (in WPF and UWP) ViewModels and control code behinds are the exact same and Im binding both with a TwoWay binding. Please note that im using 'CommunityToolkit.Mvvm' which shouldnt make any difference through.

This is the DependencyProperty:

public bool IsChecked
{
    get => (bool)GetValue(IsCheckedProperty);
    set => SetValue(IsCheckedProperty, value);
}

public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register(
    "IsChecked", typeof(bool), typeof(ReCaptcha), new PropertyMetadata(false, OnIsCheckedChanged));

This is the PropertyChangedCallback:

private static void OnIsCheckedChanged(
    DependencyObject sender,
    DependencyPropertyChangedEventArgs e)
{
    ReCaptcha owner = (ReCaptcha)sender;

    UpdateUI(owner, (bool)e.NewValue ? "True" : "False");

    owner.VerificationRequested?.Invoke(owner, new())
    owner.VerifcationRequestedCommand?.Execute(owner.VerificationRemovedCommandParameter)
}

This is the ViewModel:

bool isChecked = false;

public bool IsChecked // IsChecked
{
    get => isChecked;
    set => SetProperty(ref isChecked, value);
}

[RelayCommand] // VerifyCommand
async Task VerifyAsync()
{
   // Do stuff with 'IsChecked'
}

This is the XAML:

<ui:ReCaptcha
    IsChecked="{x:Bind viewModel.IsChecked, Mode=TwoWay}"
    VerificationRequestedCommand="{x:Bind viewModel.VerifyCommand}" />

My Issue

Okay. So the user presses something on the control and the DependencyProperty and the ViewModel property update (because of TwoWay binding).

BUT the PropertyChangedCallback (on the DependencyObject) gets called before the Binding (= the ViewModel property) is updated and before the setter of the ViewModel property is called. Since I am calling an event/command (which gets executed in the ViewModel) inside the PropertyChangedCallback the property (IsChecked) still has the old value at the time the event/command fires. This results in weird behaviours and breaks the application.

Calling order

I determinatedthe call order by setting break points wherever properties are updated and callbacks are called. This helped me to track down the problem:

Calling order in WPF (how I expect it to be)

[TRIGGER] User presses something on control

Setter of property 'IsChecked' on ViewModel gets called

PropertyChangedCallback on DependencyObject gets called

VerifyCommand gets invoked and executed ('IsChecked' has NEW value)

Calling order in UWP/WinUI3 (how I dont expect it to be)

[TRIGGER] User presses something on control

PropertyChangedCallback on DependencyObject gets called

VerifyCommand gets invoked and executed ('IsChecked' has OLD value)

Setter of property 'IsChecked' on ViewModel gets called

Furthermore information for UWP/WinUI3

When I hit the break point inside the PropertyChangedCallback on the DependencyObject and I take a look at the properties of the sender object (my custom control) I notice that the 'IsChecked' property has the new value but when I hit the break point inside the VerifyCommand (which comes after the PropertyChangedCallback break point) and take a look at my custom control in the XAML the 'IsChecked' property still has the old value. (Seen in the images bellow).

This leads me to think that something is broken with the binding, but since Im using the exact same binding in WPF (and its working), I don't know what to do.

 Break point in PropertyChangedCallback on DependencyObject.

 Break point in VerifyCommand on ViewModel/XAML.

Notes

I dont know if Im missing something completely, but Ive been stuck on this for many hours and this is my last option, so any help would be appreciated.
Ive tried my best to make the issue as clear as possible, but feel free to ask for any additional information I could provide.

I also tried researching online but there is almost no documentation about PropertyChangedCallbacks on UWP and definitely not about the call order.
I know this is a very specific use case, but I really want to keep the project structure as it is.

Im sorry if I described my problem unclearly and with incorrect grammar/spelling.
Thanks in advance.

I expect the same behavior in UWP/WinUI3 just like in WPF so my ViewModel first gets updated and then the PropertyChangedCallback gets called.

This is important since I have to use the property inside an event/command (in the ViewModel) that gets invoked by the PropertyChangedCallback.

Sample projects

I have created two small sample projects and uploaded them here if its still not clear what the problem is: https://github.com/IcySnex/PropertyChangedCallbackTests.
You can run both projects and take a look at the Debug Output. I have added a few Debug WriteLines so you can see when the callbacks are fired.


问:
h2o.predict() issues for a GLM with categorical interactions on new data
To preface, this question is specific to h2o package version 3.36.0.3, I have not yet tested it on other versions but for my purpose 3.36.0.3 is unfortunately mandatory.

In this reproducible example we can see that each categorical variable used for interactions (state) must be present at least once in new data to generate predictions without an error. For convenience sake we can pretend that data sets good and bad are entirely new observations that the model has not seen.

In the training set, state takes on values of either AK, AL, AZ, or AR. For some reason, if one of these states are not present in the new data, h2o.predict() generates the error:

```<code>java.lang.RuntimeException: DistributedException from localhost: 'Index 6 out of bounds for length 3', caused by java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 3
</code>```

Predicting on this data set does work:

```<code>> good
  dependent_var numeric_var1 numeric_var2 state weight prediction
1            65            6          1.4    AK      1   65.35646
2            72            7          6.7    AZ      1   65.45639
3            70            6          4.9    AL      1   67.21862
4            76            7         51.2    AK      1   66.11350
5            69            6         12.3    AL      1   67.21862
6            71            8          3.3    AZ      1   65.45639
7            68            7         31.9    AR      1   66.34384
</code>```

Predicting on this data set does not, and returns the "java.lang.ArrayIndexOutOfBoundsException" error  since AR is not present in the data.

```<code>> bad
  dependent_var numeric_var1 numeric_var2 state weight
1            65            6          1.4    AK      1
2            72            7          6.7    AZ      1
3            70            6          4.9    AL      1
4            76            7         51.2    AK      1
5            69            6         12.3    AL      1
6            71            8          3.3    AZ      1
</code>```

I have some possible solutions to this, but they definitely aren't as convenient as I'd like.

Add rows to the new data set for every unique state in the training frame, remove rows after predicting. This works, but outside of this example I'd need to implement quite a few steps and checks to make it dynamic (i.e. 0 categorical interactions, >1 categorical interactions, and the corresponding unique values present in the training frame)

Modify the h2o model object to remove the variable & interaction variable that are not in use for new data. (can't seem to get this to work, and it might be hard to make dynamic outside of this example. Also probably not best practice to modify a model object)

Add new data to the original set and predict on everything, then filter out by some indicator. This is also not ideal since the data outside of this example is pretty big.

I'm not quite understanding why each categorical variable must be present in new data that is being predicted, since each prediction should be based on that specific row. Is this just a limitation of h2o, or am I missing some additional argument or some alternative function? Are any other ways to use categorical interactions for an h2o glm when new data doesn't encompass every category?

Code

```<code># require(remotes)
# install_version("h2o", version = "3.36.0.3", repos = "http://cran.us.r-project.org")
library(h2o) # version 3.36.0.3
library(dplyr)

data <- read.csv(system.file("extdata", "prostate.csv", package = "h2o"))

# creating fake factor variable for repr. example
data <- data %>% mutate(state = as.factor(state.abb[DPROS]),
                        weight = 1) %>%
  select(dependent_var = AGE,
         numeric_var1 = GLEASON,
         numeric_var2 = PSA,
         state,
         weight)

# initialize h2o
h2o.init()

# generating training frame
data_train <- data[1:300,] %>% as.h2o()

# specify model vars and interactions
model_interaction_pairs <- list(c('numeric_var1', 'state'))
model_vars <- c('numeric_var1','state', 'numeric_var2')

interaction_glm <- h2o.glm(y = "dependent_var",
                            x = model_vars,
                            training_frame = data_train,
                            interaction_pairs = model_interaction_pairs,
                            offset_column = "weight")

# taking the first 6 observations in the data set
bad <- head(data)
bad_h2o <- bad %>% as.h2o

# generates out of bounds error since AR isn't present in the data set.
bad <- bad %>%
  mutate(prediction = as.vector(h2o.predict(interaction_glm, bad_h2o)))

# taking the first 7 observations in the data set, now AR is included.
good <- head(data, 7)
good_h2o <- good %>% as.h2o

# no error since all states in train are present.
good <- good %>%
  mutate(prediction = as.vector(h2o.predict(interaction_glm, good_h2o)))

# to further illustrate:
unique(data[1:300,]$state) # states present in train
unique(good$state) # states present in first 7 observations
unique(bad$state) # states present in first 6 observations, AR left out.
</code>```

Potential solutions:

```<code># ugly fix 1 (works)

bad1 <- bind_rows(bad,data.table(unique(data[1:300,]$state)) %>% select(state = V1))

bad1_h2o <- bad1 %>% as.h2o()

bad1 %>% mutate(prediction = as.vector(h2o.predict(interaction_glm, bad1_h2o))) %>% filter(!is.na(dependent_var))

# # ugly fix 2 (failed)
#
# interaction_glm2 <- interaction_glm
# interaction_glm2@model[["domains"]][[1]] <- paste0(unique(bad$state))
# interaction_glm2@model[["domains"]][[2]] <- paste0(unique(bad$state))
# interaction_glm2@model[["coefficients_table"]] <- interaction_glm@model[["coefficients_table"]] %>% filter(!grepl("AR",names))
# interaction_glm2@model[["standardized_coefficient_magnitudes"]] <- interaction_glm@model[["standardized_coefficient_magnitudes"]] %>% filter(!grepl("AR",names))
# interaction_glm2@model[["coefficients"]] <- interaction_glm@model[["coefficients"]][c(-4, -8)]
# interaction_glm2@model[["model_summary"]][["number_of_predictors_total"]] <- interaction_glm@model[["model_summary"]][["number_of_predictors_total"]] - 2
# interaction_glm2@model[["model_summary"]][["number_of_active_predictors"]] <- interaction_glm@model[["model_summary"]][["number_of_active_predictors"]] - 2
#
# # doesn't work
# bad2 <- bad %>%
#   mutate(prediction = as.vector(h2o.predict(interaction_glm2, bad_h2o)))
</code>```

Body:
To preface, this question is specific to h2o package version 3.36.0.3, I have not yet tested it on other versions but for my purpose 3.36.0.3 is unfortunately mandatory.

In this reproducible example we can see that each categorical variable used for interactions (state) must be present at least once in new data to generate predictions without an error. For convenience sake we can pretend that data sets good and bad are entirely new observations that the model has not seen.

In the training set, state takes on values of either AK, AL, AZ, or AR. For some reason, if one of these states are not present in the new data, h2o.predict() generates the error:

java.lang.RuntimeException: DistributedException from localhost: 'Index 6 out of bounds for length 3', caused by java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 3

Predicting on this data set does work:

> good
  dependent_var numeric_var1 numeric_var2 state weight prediction
1            65            6          1.4    AK      1   65.35646
2            72            7          6.7    AZ      1   65.45639
3            70            6          4.9    AL      1   67.21862
4            76            7         51.2    AK      1   66.11350
5            69            6         12.3    AL      1   67.21862
6            71            8          3.3    AZ      1   65.45639
7            68            7         31.9    AR      1   66.34384

Predicting on this data set does not, and returns the "java.lang.ArrayIndexOutOfBoundsException" error  since AR is not present in the data.

> bad
  dependent_var numeric_var1 numeric_var2 state weight
1            65            6          1.4    AK      1
2            72            7          6.7    AZ      1
3            70            6          4.9    AL      1
4            76            7         51.2    AK      1
5            69            6         12.3    AL      1
6            71            8          3.3    AZ      1

I have some possible solutions to this, but they definitely aren't as convenient as I'd like.

Add rows to the new data set for every unique state in the training frame, remove rows after predicting. This works, but outside of this example I'd need to implement quite a few steps and checks to make it dynamic (i.e. 0 categorical interactions, >1 categorical interactions, and the corresponding unique values present in the training frame)

Modify the h2o model object to remove the variable & interaction variable that are not in use for new data. (can't seem to get this to work, and it might be hard to make dynamic outside of this example. Also probably not best practice to modify a model object)

Add new data to the original set and predict on everything, then filter out by some indicator. This is also not ideal since the data outside of this example is pretty big.

I'm not quite understanding why each categorical variable must be present in new data that is being predicted, since each prediction should be based on that specific row. Is this just a limitation of h2o, or am I missing some additional argument or some alternative function? Are any other ways to use categorical interactions for an h2o glm when new data doesn't encompass every category?

Code

# require(remotes)
# install_version("h2o", version = "3.36.0.3", repos = "http://cran.us.r-project.org")
library(h2o) # version 3.36.0.3
library(dplyr)

data <- read.csv(system.file("extdata", "prostate.csv", package = "h2o"))

# creating fake factor variable for repr. example
data <- data %>% mutate(state = as.factor(state.abb[DPROS]),
                        weight = 1) %>%
  select(dependent_var = AGE,
         numeric_var1 = GLEASON,
         numeric_var2 = PSA,
         state,
         weight)

# initialize h2o
h2o.init()

# generating training frame
data_train <- data[1:300,] %>% as.h2o()

# specify model vars and interactions
model_interaction_pairs <- list(c('numeric_var1', 'state'))
model_vars <- c('numeric_var1','state', 'numeric_var2')

interaction_glm <- h2o.glm(y = "dependent_var",
                            x = model_vars,
                            training_frame = data_train,
                            interaction_pairs = model_interaction_pairs,
                            offset_column = "weight")

# taking the first 6 observations in the data set
bad <- head(data)
bad_h2o <- bad %>% as.h2o

# generates out of bounds error since AR isn't present in the data set.
bad <- bad %>%
  mutate(prediction = as.vector(h2o.predict(interaction_glm, bad_h2o)))

# taking the first 7 observations in the data set, now AR is included.
good <- head(data, 7)
good_h2o <- good %>% as.h2o

# no error since all states in train are present.
good <- good %>%
  mutate(prediction = as.vector(h2o.predict(interaction_glm, good_h2o)))

# to further illustrate:
unique(data[1:300,]$state) # states present in train
unique(good$state) # states present in first 7 observations
unique(bad$state) # states present in first 6 observations, AR left out.

Potential solutions:

# ugly fix 1 (works)

bad1 <- bind_rows(bad,data.table(unique(data[1:300,]$state)) %>% select(state = V1))

bad1_h2o <- bad1 %>% as.h2o()

bad1 %>% mutate(prediction = as.vector(h2o.predict(interaction_glm, bad1_h2o))) %>% filter(!is.na(dependent_var))

# # ugly fix 2 (failed)
#
# interaction_glm2 <- interaction_glm
# interaction_glm2@model[["domains"]][[1]] <- paste0(unique(bad$state))
# interaction_glm2@model[["domains"]][[2]] <- paste0(unique(bad$state))
# interaction_glm2@model[["coefficients_table"]] <- interaction_glm@model[["coefficients_table"]] %>% filter(!grepl("AR",names))
# interaction_glm2@model[["standardized_coefficient_magnitudes"]] <- interaction_glm@model[["standardized_coefficient_magnitudes"]] %>% filter(!grepl("AR",names))
# interaction_glm2@model[["coefficients"]] <- interaction_glm@model[["coefficients"]][c(-4, -8)]
# interaction_glm2@model[["model_summary"]][["number_of_predictors_total"]] <- interaction_glm@model[["model_summary"]][["number_of_predictors_total"]] - 2
# interaction_glm2@model[["model_summary"]][["number_of_active_predictors"]] <- interaction_glm@model[["model_summary"]][["number_of_active_predictors"]] - 2
#
# # doesn't work
# bad2 <- bad %>%
#   mutate(prediction = as.vector(h2o.predict(interaction_glm2, bad_h2o)))


问:
dotlock protocol, how to deal with permission denied in /var/mail?
I'm writing a tool to deal with email in mbox format, and I want to properly implement dotlock. For obvious reasons, attempting to create a lockfile in /var/mail or /var/spool/mail results in a permission denied error.

Is there official documentation on dotlock protocol, and does it address this issue? I note that /usr/bin/mail is not SUID-root, so that's not the answer. Linux has the mail-lock program, but neither MacOS or FreeBSD have it.

Another way to ask this question: How does /usr/bin/mail lock the user's inbox?


问:
Move common gradle code into separate file works with groovy, kotlin gives "Unresolved reference"
I have a multi module project with several Android library modules. I pulled the common android gradle configurations into a separate file and apply it in each module.

gradle/androidDefaults.gradle.kts

```<code>android {
    compileSdk = 33
    ...
}
</code>```

Each android library modules includes it like this:

```<code>apply {
    from("${project.rootDir}/gradle/androidDefaults.gradle.kts")
}
</code>```

This works fine as long as androidDefaults is a Groovy file, but when I try to convert it to Kotlin, then i get an Unresolved reference error

```<code>e: myProjectDir/gradle/androidDefaults.gradle.kts:2:1: Unresolved reference: android
</code>```

I understand that, since it is a separate file, I need to somehow tell it what android is, but I am not quite sure how. I've tried to add the android or the kotlin DSL plugin in there, but that did not work either.

Any help would be appreciated.

```<code>$./gradlew --version

------------------------------------------------------------
Gradle 7.5
------------------------------------------------------------

Build time:   2022-07-14 12:48:15 UTC
Revision:     c7db7b958189ad2b0c1472b6fe663e6d654a5103

Kotlin:       1.6.21
Groovy:       3.0.10
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          11.0.16 (BellSoft 11.0.16+8-LTS)
OS:           Mac OS X 13.0 aarch64
</code>```

Body:
I have a multi module project with several Android library modules. I pulled the common android gradle configurations into a separate file and apply it in each module.

gradle/androidDefaults.gradle.kts

android {
    compileSdk = 33
    ...
}

Each android library modules includes it like this:

apply {
    from("${project.rootDir}/gradle/androidDefaults.gradle.kts")
}

This works fine as long as androidDefaults is a Groovy file, but when I try to convert it to Kotlin, then i get an Unresolved reference error

e: myProjectDir/gradle/androidDefaults.gradle.kts:2:1: Unresolved reference: android

I understand that, since it is a separate file, I need to somehow tell it what android is, but I am not quite sure how. I've tried to add the android or the kotlin DSL plugin in there, but that did not work either.

Any help would be appreciated.

$./gradlew --version

------------------------------------------------------------
Gradle 7.5
------------------------------------------------------------

Build time:   2022-07-14 12:48:15 UTC
Revision:     c7db7b958189ad2b0c1472b6fe663e6d654a5103

Kotlin:       1.6.21
Groovy:       3.0.10
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          11.0.16 (BellSoft 11.0.16+8-LTS)
OS:           Mac OS X 13.0 aarch64


问:
Why the div doesn't close?
I am trying when I click outside the div to close the div. Here is my code :

```<code>import { useRef, useState } from "react";
import "./styles.css";

const App = () => {
  const [showModal, setShowModal] = useState(false);
  const noderef = useRef(null);

  const handleClick = () => {
    console.log(showModal);
    if (!showModal) {
      console.log("test1");
      document.addEventListener("click", handleOutsideClick, true);
    } else {
      console.log("test2");
      document.removeEventListener("click", handleOutsideClick, true);
    }
    setShowModal(!showModal);
  };

  const handleOutsideClick = (e) => {
    if (!noderef.current.contains(e.target)) handleClick();
  };

  return (
    <div ref={noderef}>
      <button onClick={() => handleClick()}>Open Modal</button>
      {showModal ? (
        <div className="modal">
          I'm a modal!
          <button onClick={() => handleClick()}>close modal</button>
        </div>
      ) : null}
    </div>
  );
};

export default App;

</code>```

When I click on Open Modal it works also when I click on close modal. But when I click outside the div the div is still opened.

How can I do to fix that, it looks it is like there are two clicks

Here is the full project : My project

Title: Why the div doesn't close?

Body:
I am trying when I click outside the div to close the div. Here is my code :

import { useRef, useState } from "react";
import "./styles.css";

const App = () => {
  const [showModal, setShowModal] = useState(false);
  const noderef = useRef(null);

  const handleClick = () => {
    console.log(showModal);
    if (!showModal) {
      console.log("test1");
      document.addEventListener("click", handleOutsideClick, true);
    } else {
      console.log("test2");
      document.removeEventListener("click", handleOutsideClick, true);
    }
    setShowModal(!showModal);
  };

  const handleOutsideClick = (e) => {
    if (!noderef.current.contains(e.target)) handleClick();
  };

  return (

      <button onClick={() => handleClick()}>Open Modal</button>
      {showModal ? (

          I'm a modal!
          <button onClick={() => handleClick()}>close modal</button>

      ) : null}

  );
};

export default App;

When I click on Open Modal it works also when I click on close modal. But when I click outside the div the div is still opened.

How can I do to fix that, it looks it is like there are two clicks

Here is the full project : My project


问:
Reuse month columns in SwiftUI Chart
I have a chart which displays data over time (months in my case). The data for this chart is randomly generated by getting any date from now to 500 days in the past (chartDate), and a random number (sales). It generates 500 of these rows.

```<code>func dailySales2() -> [(chartDate: Date, year: String, sales: Int)] {
    var temp: [(chartDate: Date, year: String, sales: Int)] = []

    for _ in 1...500 {
        let dateT = Calendar.current.date(byAdding: .day, value: -Int.random(in: 1...500), to: Date())!
        temp.append((chartDate: dateT, year: dateT.formatted(.dateTime.year()), sales: Int.random(in: 100...500)))
    }

    return temp.sorted(by: { $0.chartDate < $1.chartDate })
}

Chart {
            ForEach(dailySales2(), id: \.chartDate) { chartD in
                BarMark(
                    x: .value("Day", chartD.chartDate, unit: .month),
                    y: .value("Sales", chartD.sales)
                )
                .foregroundStyle(by: .value("Year:", chartD.year))
            }
        }
        .chartXAxis {
            AxisMarks(values: .stride(by: .month)) {
                AxisValueLabel(format: .dateTime.month(.narrow), centered: true)
            }
        }
</code>```

This generates A S O N D J F M A M J J A S O N D columns (August 2021 - December 2021 and then January 2022 - December 2022). How do I go about only having one set of January - December columns and putting both years into these columns (separated by series)? Thanks.

Having 12 columns, one for each month, which any year uses.

Title: Reuse month columns in SwiftUI Chart

Body:
I have a chart which displays data over time (months in my case). The data for this chart is randomly generated by getting any date from now to 500 days in the past (chartDate), and a random number (sales). It generates 500 of these rows.

func dailySales2() -> [(chartDate: Date, year: String, sales: Int)] {
    var temp: [(chartDate: Date, year: String, sales: Int)] = []

    for _ in 1...500 {
        let dateT = Calendar.current.date(byAdding: .day, value: -Int.random(in: 1...500), to: Date())!
        temp.append((chartDate: dateT, year: dateT.formatted(.dateTime.year()), sales: Int.random(in: 100...500)))
    }

    return temp.sorted(by: { $0.chartDate < $1.chartDate })
}

Chart {
            ForEach(dailySales2(), id: \.chartDate) { chartD in
                BarMark(
                    x: .value("Day", chartD.chartDate, unit: .month),
                    y: .value("Sales", chartD.sales)
                )
                .foregroundStyle(by: .value("Year:", chartD.year))
            }
        }
        .chartXAxis {
            AxisMarks(values: .stride(by: .month)) {
                AxisValueLabel(format: .dateTime.month(.narrow), centered: true)
            }
        }

This generates A S O N D J F M A M J J A S O N D columns (August 2021 - December 2021 and then January 2022 - December 2022). How do I go about only having one set of January - December columns and putting both years into these columns (separated by series)? Thanks.

Having 12 columns, one for each month, which any year uses.


问:
How to join on an id and the closest date in Pandas?
I have two tables, x and y. x has customer_id and reporting_date and y contains customer_id and trigger_date.

For each row in x I want to join the row in y whose trigger_date is the nearest to the reporting_date in x. I have hard-coded my desired result as z in the example below, which should run in the terminal out-of-the-box.

```<code>import pandas as pd
import numpy as np

x = pd.DataFrame({
    'customer_id': [1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4],
    'reporting_date': [
        '2021-09-01',
        '2021-10-01',
        '2021-11-01',
        '2019-01-01',
        '2019-02-01',
        '2021-12-01',
        '2022-01-01',
        '2022-02-01',
        '2022-03-01',
        '2022-04-01',
        '2022-07-01',
        '2022-08-01',
        '2022-09-01'
    ],
    'payment_status': [0, 0, 2, 0, 2, 0, 0, 0, 0, 2, 0, 0, 2]
})

y = pd.DataFrame({
    'customer_id': [1, 1, 3, 3, 3, 4],
    'trigger_date': [
        '2019-08-21',
        '2021-09-17',
        '2020-01-01',
        '2022-01-03',
        '2022-03-08',
        '2022-10-01']})

# DESIRED RESULT IS z:
z = x.__deepcopy__()
z['nearest_trigger_date'] = [
    '2019-09-17',
    '2019-09-17',
    '2019-09-17',
    np.nan,
    np.nan,
    '2022-01-03',
    '2022-01-03',
    '2022-01-03',
    '2022-03-08',
    '2022-03-08',
    '2022-10-01',
    '2022-10-01',
    '2022-10-01' ]

x['reporting_date'] = x['reporting_date'].apply(pd.to_datetime)
y['trigger_date'] = y['trigger_date'].apply(pd.to_datetime)
z['nearest_trigger_date'] = z['nearest_trigger_date'].apply(pd.to_datetime)

</code>```

EDIT This is not a duplicate of Merging series of pandas dataframe into single dataframe. That is a concatenation, not a "merge" or "join". And pd.merge_asof only supports merging on one column.

Body:
I have two tables, x and y. x has customer_id and reporting_date and y contains customer_id and trigger_date.

For each row in x I want to join the row in y whose trigger_date is the nearest to the reporting_date in x. I have hard-coded my desired result as z in the example below, which should run in the terminal out-of-the-box.

import pandas as pd
import numpy as np

x = pd.DataFrame({
    'customer_id': [1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4],
    'reporting_date': [
        '2021-09-01',
        '2021-10-01',
        '2021-11-01',
        '2019-01-01',
        '2019-02-01',
        '2021-12-01',
        '2022-01-01',
        '2022-02-01',
        '2022-03-01',
        '2022-04-01',
        '2022-07-01',
        '2022-08-01',
        '2022-09-01'
    ],
    'payment_status': [0, 0, 2, 0, 2, 0, 0, 0, 0, 2, 0, 0, 2]
})

y = pd.DataFrame({
    'customer_id': [1, 1, 3, 3, 3, 4],
    'trigger_date': [
        '2019-08-21',
        '2021-09-17',
        '2020-01-01',
        '2022-01-03',
        '2022-03-08',
        '2022-10-01']})

# DESIRED RESULT IS z:
z = x.__deepcopy__()
z['nearest_trigger_date'] = [
    '2019-09-17',
    '2019-09-17',
    '2019-09-17',
    np.nan,
    np.nan,
    '2022-01-03',
    '2022-01-03',
    '2022-01-03',
    '2022-03-08',
    '2022-03-08',
    '2022-10-01',
    '2022-10-01',
    '2022-10-01' ]

x['reporting_date'] = x['reporting_date'].apply(pd.to_datetime)
y['trigger_date'] = y['trigger_date'].apply(pd.to_datetime)
z['nearest_trigger_date'] = z['nearest_trigger_date'].apply(pd.to_datetime)

EDIT This is not a duplicate of Merging series of pandas dataframe into single dataframe. That is a concatenation, not a "merge" or "join". And pd.merge_asof only supports merging on one column.


问:
Using word embeddings to train for document similarity or topic classification
This is just a general question since i started on a course but it is closed during christma/ny

I know that word embeddings are mathematical representation of words, my question if I had a dataset which had a large corpus representing the unique words in different documents. When it learn the word embeddings of this corpus can it then be used for classification tasks such as the probability that a given document is said topic

Further for my own curiosity and because i want to get into this industry, what would be a good NLP task to do to represent on my cv? i've got the hang of selenium, pytorch and opencv


问:
Can you override a computed property in a struct nested type / extension nested type?
Suppose there is some struct, with a nested struct that has some functionality I want to modify or extend. How do you override a computed property of a struct, when the computed property is inside a nested struct? Example:

```<code>public struct Foo {
  var c: Int
  init(c: Int) {
    self.c = c
  }
  // Suppose there's lots of implementation
}

extension Foo {
  struct FooContent {
    var a: Int
    public var b: Int { self.a + 1 }

    init(a: Int) {
      self.a = a
    }
  }
  // Suppose there's lots of implementation
}

var obj = Foo.FooContent(a: 1)
print(obj.b)
</code>```

Suppose I want to override b to be self.a + 2, and not touch any other functionality in Foo or FooContent. Is there a way to do this something along the lines of

```<code>extension Foo.FooContent {
    public var b: Int { self.a + 2 }
    // won't compile because b is already defined
}
</code>```

Seems like a big hole in the language design that structs + extension functionality can't be inherited. I figure I'm missing something.

Body:
Suppose there is some struct, with a nested struct that has some functionality I want to modify or extend. How do you override a computed property of a struct, when the computed property is inside a nested struct? Example:

public struct Foo {
  var c: Int
  init(c: Int) {
    self.c = c
  }
  // Suppose there's lots of implementation
}

extension Foo {
  struct FooContent {
    var a: Int
    public var b: Int { self.a + 1 }

    init(a: Int) {
      self.a = a
    }
  }
  // Suppose there's lots of implementation
}

var obj = Foo.FooContent(a: 1)
print(obj.b)

Suppose I want to override b to be self.a + 2, and not touch any other functionality in Foo or FooContent. Is there a way to do this something along the lines of

extension Foo.FooContent {
    public var b: Int { self.a + 2 }
    // won't compile because b is already defined
}

Seems like a big hole in the language design that structs + extension functionality can't be inherited. I figure I'm missing something.


问:
In memory Sqlite with Next.js -- is it possible?
I'm demoing a project and I need access to a database in my local environment. I don't want to connect over the internet to an internet-based provider.

To simulate this, however, I want to use sqlite. I installed sequelize, an ORM for sqlite and want to load a new instance of a database each time Next.js loads and populate it with some data (see below).

How would I run this code -- the populateUsers() function below?

I thought I could use getServerSideProps() in _app.js, but discovered recently this isn't possible. I only need to run this function once, when the app loads, and then of course on each successive re-load as it's an in-memory database.

```<code>import { Sequelize, QueryTypes } from "sequelize";

const sequelize = new Sequelize("sqlite::memory:");

export const isConnOk = async () => {
  try {
    await sequelize.authenticate();
    console.log("Connection has been established successfully.");
  } catch (error) {
    console.error("Unable to connect to the database:", error);
  }
};

export const execute = async (sql: string) => {
  const [results, metadata] = await sequelize.query(sql);

  return [results, metadata];
};

export const query = async (sql: string) => {
  const results = await sequelize.query(sql, { type: QueryTypes.SELECT });

  return results;
};

export const populateUsers = async () => {
  try {
    console.log("START: populating database");

    await execute(
      "create table users ( id integer, name varchar(50), username varchar(50), city_of_birth varchar(50) );"
    );

    await execute(
      "insert into users values ( '1', 'gary', 'garym', 'seattle' );"
    );

    await execute(
      "insert into users values ( '2', 'christine', 'chris', 'miami' );"
    );

    console.log("COMPLETE: database populated");
  } catch {
    console.log("FAILURE: did not populate database");
  }
};
</code>```

Body:
I'm demoing a project and I need access to a database in my local environment. I don't want to connect over the internet to an internet-based provider.

To simulate this, however, I want to use sqlite. I installed sequelize, an ORM for sqlite and want to load a new instance of a database each time Next.js loads and populate it with some data (see below).

How would I run this code -- the populateUsers() function below?

I thought I could use getServerSideProps() in _app.js, but discovered recently this isn't possible. I only need to run this function once, when the app loads, and then of course on each successive re-load as it's an in-memory database.

import { Sequelize, QueryTypes } from "sequelize";

const sequelize = new Sequelize("sqlite::memory:");

export const isConnOk = async () => {
  try {
    await sequelize.authenticate();
    console.log("Connection has been established successfully.");
  } catch (error) {
    console.error("Unable to connect to the database:", error);
  }
};

export const execute = async (sql: string) => {
  const [results, metadata] = await sequelize.query(sql);

  return [results, metadata];
};

export const query = async (sql: string) => {
  const results = await sequelize.query(sql, { type: QueryTypes.SELECT });

  return results;
};

export const populateUsers = async () => {
  try {
    console.log("START: populating database");

    await execute(
      "create table users ( id integer, name varchar(50), username varchar(50), city_of_birth varchar(50) );"
    );

    await execute(
      "insert into users values ( '1', 'gary', 'garym', 'seattle' );"
    );

    await execute(
      "insert into users values ( '2', 'christine', 'chris', 'miami' );"
    );

    console.log("COMPLETE: database populated");
  } catch {
    console.log("FAILURE: did not populate database");
  }
};


问:
Python Window Manipluation
I am currently working with a range of packages to automate the process of opening a file in a directory and saving it my code is looking like this:

```<code># Move mouse to maximize screen
</code>```

```<code>pydirectinput.moveTo(1451, 116)
pydirectinput.click()

time.sleep(2)

# Move mouse to 'New'
pydirectinput.moveTo(70, 70)
pydirectinput.click()

time.sleep(1)

# Move mouse to New's dropdowntest

pydirectinput.moveTo(134, 197)
pydirectinput.click()

#time.sleep(1)

# Write name of YTD
pyautogui.write('test')
pyautogui.press('enter')

#time.sleep(1)

pydirectinput.moveTo(507, 496)
pydirectinput.click()

#time.sleep(1)

# Press Up Arrow to get YTD
pyautogui.press('up')
time.sleep(1)
pyautogui.press('enter')

#Preses import
pydirectinput.moveTo(356, 198)
pydirectinput.click()

time.sleep(1)

pydirectinput.click()

# Go to uniform directory and find the file
pydirectinput.moveTo(922, 226)
pydirectinput.click()
pyautogui.press('backspace')
pyautogui.write(uniform_directory)

time.sleep(1)
pyautogui.press('enter')
time.sleep(1)
</code>```

Is there any other way to do this to what I have found is that it is the only way. I've done some digging and saw you can select specific dropdowns however this did not work and no one seemed to have the issue I was having with it so this was the alternative, I came up with. If anyone knows a better solution please let me know.

Title: Python Window Manipluation

Body:
I am currently working with a range of packages to automate the process of opening a file in a directory and saving it my code is looking like this:

# Move mouse to maximize screen

pydirectinput.moveTo(1451, 116)
pydirectinput.click()

time.sleep(2)

# Move mouse to 'New'
pydirectinput.moveTo(70, 70)
pydirectinput.click()

time.sleep(1)

# Move mouse to New's dropdowntest

pydirectinput.moveTo(134, 197)
pydirectinput.click()

#time.sleep(1)

# Write name of YTD
pyautogui.write('test')
pyautogui.press('enter')

#time.sleep(1)

pydirectinput.moveTo(507, 496)
pydirectinput.click()

#time.sleep(1)

# Press Up Arrow to get YTD
pyautogui.press('up')
time.sleep(1)
pyautogui.press('enter')

#Preses import
pydirectinput.moveTo(356, 198)
pydirectinput.click()

time.sleep(1)

pydirectinput.click()

# Go to uniform directory and find the file
pydirectinput.moveTo(922, 226)
pydirectinput.click()
pyautogui.press('backspace')
pyautogui.write(uniform_directory)

time.sleep(1)
pyautogui.press('enter')
time.sleep(1)

Is there any other way to do this to what I have found is that it is the only way. I've done some digging and saw you can select specific dropdowns however this did not work and no one seemed to have the issue I was having with it so this was the alternative, I came up with. If anyone knows a better solution please let me know.


问:
Call R script from Anylogic and return recults
I need to call a forecast model from R within Anlylogic, and return the resulting outputs in R. It is a specific timeseries that I have built in R, and just copying the coefficients to Anylogic is not efficient. I have seen a couple of older posts on similar questions, but I am not sure I can follow. Any advice would be very appreciated.

I have a regression forecast model that uses predictors to provide a forecast along with Prediction Intervals. I need these outputs to be updated by the different values of the predictors and then used in Anylogic.


问:
Different size assigned to multiple variables which are declared continually in one statement
Trying to figure out why continued declaration is not a good Idea I suddenly realized the size assigned to following variables are not the same:

```<code>char const* const ALPHA, BETA;

printf("sizeof(ALPHA): %lu\n", sizeof(ALPHA));
printf("sizeof(BETA): %lu\n", sizeof(BETA));
printf("sizeof(char): %lu\n", sizeof(char));
printf("sizeof(char const* const): %lu\n", sizeof(char const *const));
printf("sizeof(char const*) %lu\n", sizeof(char const *));
</code>```

output:

```<code>sizeof(ALPHA): 8
sizeof(BETA): 1
sizeof(char): 1
sizeof(char const* const): 8
sizeof(char const*) 8
</code>```

Apparently BETA should be of type char const* not char const* const! but why it has the size of 1? is it really a char? How?

I expected that both variables be of the same size: 8

Body:
Trying to figure out why continued declaration is not a good Idea I suddenly realized the size assigned to following variables are not the same:

char const* const ALPHA, BETA;

printf("sizeof(ALPHA): %lu\n", sizeof(ALPHA));
printf("sizeof(BETA): %lu\n", sizeof(BETA));
printf("sizeof(char): %lu\n", sizeof(char));
printf("sizeof(char const* const): %lu\n", sizeof(char const *const));
printf("sizeof(char const*) %lu\n", sizeof(char const *));

output:

sizeof(ALPHA): 8
sizeof(BETA): 1
sizeof(char): 1
sizeof(char const* const): 8
sizeof(char const*) 8

Apparently BETA should be of type char const* not char const* const! but why it has the size of 1? is it really a char? How?

I expected that both variables be of the same size: 8


问:
How to reassign mutable String?
Why does reassigning a mutable String results in compile error? Shouldn't mut allow mutating string?

fn main() {
    let mut guess = String::from("foo\n");
    guess = guess.trim();
    println!("Input: {}", guess);
}
```
<p>Gives</p>
```9 |     guess = guess.trim();
  |             ^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
  |             |
  |             expected struct `String`, found `&str`
```

Title: How to reassign mutable String?

Body:
Why does reassigning a mutable String results in compile error? Shouldn't mut allow mutating string?

fn main() {
    let mut guess = String::from("foo\n");
    guess = guess.trim();
    println!("Input: {}", guess);
}

Gives

9 |     guess = guess.trim();
  |             ^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
  |             |
  |             expected struct `String`, found `&str`


问:
Getting very weird 400 errors (Imgur API)
I know how this may read to you but I am seriously out of ideas on this one.

I've written something in Python that can download stuff from Imgur using their API. I have an Authorization clientID and everything, and this thing works.

But sometimes I am getting a 400 HTML response status code with empty text when requesting a direct link so I can save the file. According to the doc this error will come back at you when you're missing a required parameter or if a part of your request is incorrect; this feels like a weird error to come back at me, when other requests get through just fine. The weirder part is that I can send 100 requests in 100 seconds, all will come back with 400 None. But once I open the image in my browser and view it, the request suddently changes to 200, everything works and this link will never throw a 400 ever again.

My friend suggestet that maybe it had something to do with my IP adress (getting flagged as a spam bot or whatever), so I opened the URLs via my phone on cellular, but as soon as the image loaded on my phone, the requests were successful. Also, when I tried finding more links with this strange behaviour, I tested a bunch of images from the imgur front page, and all worked fine. Combining this with the fact that I got the problematic links from very old reddit threads leaves me with the only idea that it has something to do with the age of the files or rather their last view date.

The requests happened via a code similar to:

```<code>headers = {'Authorization': f"Client-ID <id>"}
url = f"https://api.imgur.com/3/image/{fileID}"
requests.get(url, headers=headers)
</code>```

I'm asking this here mainly because the Imgur API page says the best way to get help about the API is to post the problem here on stackoverflow. Maybe one of their engineers sees this and can answer my question or maybe someone else has an idea what may be going on here. In any case, I would be grateful for any useful input ^^

Body:
I know how this may read to you but I am seriously out of ideas on this one.

I've written something in Python that can download stuff from Imgur using their API. I have an Authorization clientID and everything, and this thing works.

But sometimes I am getting a 400 HTML response status code with empty text when requesting a direct link so I can save the file. According to the doc this error will come back at you when you're missing a required parameter or if a part of your request is incorrect; this feels like a weird error to come back at me, when other requests get through just fine. The weirder part is that I can send 100 requests in 100 seconds, all will come back with 400 None. But once I open the image in my browser and view it, the request suddently changes to 200, everything works and this link will never throw a 400 ever again.

My friend suggestet that maybe it had something to do with my IP adress (getting flagged as a spam bot or whatever), so I opened the URLs via my phone on cellular, but as soon as the image loaded on my phone, the requests were successful. Also, when I tried finding more links with this strange behaviour, I tested a bunch of images from the imgur front page, and all worked fine. Combining this with the fact that I got the problematic links from very old reddit threads leaves me with the only idea that it has something to do with the age of the files or rather their last view date.

The requests happened via a code similar to:

headers = {'Authorization': f"Client-ID <id>"}
url = f"https://api.imgur.com/3/image/{fileID}"
requests.get(url, headers=headers)

I'm asking this here mainly because the Imgur API page says the best way to get help about the API is to post the problem here on stackoverflow. Maybe one of their engineers sees this and can answer my question or maybe someone else has an idea what may be going on here. In any case, I would be grateful for any useful input ^^