问:
Remove invalid imap mail messages from the Summary buffer in gnus
When accessing IMAP mail (with nnimap) in GNUS, the Summary buffer often lists messages or that are actually no longer present in the group.

Selecting any of these messages/articles results in an 'Article canceled or expired' error message.  Quiting and restarting gnus doesn't change this (or refreshing with C-u M-g).

I can remove these articles from the Summary list by quiting gnus, and removing the ~/News directory and .newsrc.eld file, and then restarting gnus.

Is there anyway of getting the same result without reverting to deleting the files and directories?

答: You could try upgrading your version of Gnus. I used to have this problem a lot (along with every other user, it seems) and Lars did a massive rewrite of the IMAP code sometime this spring which seems to have fixed the problem here.</p>

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
How can we run a standard Python script in Azure and save files to a Data Lake?
I have a Python script that runs perfectly fine on my laptop. I am trying to move it to Azure, and run it there. Ideally, I would like to do some basic screen scraping, some basic transformation, and then save the data files in the Data Lake or maybe the Storage Explorer (the lake is probably better). So, I setup 'Create Automation Account' and 'Run As Account'. Now, I am trying to run the code (hit Start button) in an Azure 'Runbook' and I am getting this error message.

```<code>Failed
Traceback (most recent call last):  File "C:\Temp\3fgngmon.o45\7e326422-ff39-4a2c-93f9-4afafd46205c", line 2, in <module>    from bs4 import BeautifulSoupModuleNotFoundError: No module named 'bs4'
</code>```

Here is my sample code.

```<code>import requests
from bs4 import BeautifulSoup
from urllib.parse import unquote
import csv
import io

all_links = [
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/ochsner-clinic-foundation",
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/ohio-state-university-hospital",
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/orlando-health",
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/st.-joseph%E2%80%99s-hospital-(tampa)",
]

for item in all_links:
    item = item.replace('tree/', '')

    try:
        file_name = unquote(item.split('/')[-1])
        DOWNLOAD_URL = f'https://raw.githubusercontent.com{item}/data-latest.tsv'
        r_tsv = requests.get(DOWNLOAD_URL)

        if r_tsv.status_code == 404:
            print(f"Not found - {DOWNLOAD_URL}")
        else:
            print(f"Downloaded - {DOWNLOAD_URL}")
            data = list(csv.reader(io.StringIO(r_tsv.text), delimiter='\t'))
            DOWNLOAD_PATH = fr'C:\Users\ryans\Desktop\hospital_data\{file_name}.csv'

            with open(DOWNLOAD_PATH, 'w', newline='') as f_output:
                csv_output = csv.writer(f_output)
                csv_output.writerows(data)
    except Exception as e:
        print(e)
</code>```

Somehow, I think I need to do a pip install. Not sure how to do it. Also, I need to change the save path to the Data Lake (or Storage Explorer). Not sure how to do this either. How can I get this up and running?

答:
You need to import the beautiful soup package into your automation account.

In your Automation account, select Python packages under Shared Resources. Click + Add a Python package.

ContentLicense: CC BY-SA 4.0

Body:
I have a Python script that runs perfectly fine on my laptop. I am trying to move it to Azure, and run it there. Ideally, I would like to do some basic screen scraping, some basic transformation, and then save the data files in the Data Lake or maybe the Storage Explorer (the lake is probably better). So, I setup 'Create Automation Account' and 'Run As Account'. Now, I am trying to run the code (hit Start button) in an Azure 'Runbook' and I am getting this error message.

Failed
Traceback (most recent call last):  File "C:\Temp\3fgngmon.o45\7e326422-ff39-4a2c-93f9-4afafd46205c", line 2, in <module>    from bs4 import BeautifulSoupModuleNotFoundError: No module named 'bs4'

Here is my sample code.

import requests
from bs4 import BeautifulSoup
from urllib.parse import unquote
import csv
import io

all_links = [
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/ochsner-clinic-foundation",
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/ohio-state-university-hospital",
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/orlando-health",
    "/vsoch/hospital-chargemaster/tree/0.0.2/data/st.-joseph%E2%80%99s-hospital-(tampa)",
]

for item in all_links:
    item = item.replace('tree/', '')

    try:
        file_name = unquote(item.split('/')[-1])
        DOWNLOAD_URL = f'https://raw.githubusercontent.com{item}/data-latest.tsv'
        r_tsv = requests.get(DOWNLOAD_URL)

        if r_tsv.status_code == 404:
            print(f"Not found - {DOWNLOAD_URL}")
        else:
            print(f"Downloaded - {DOWNLOAD_URL}")
            data = list(csv.reader(io.StringIO(r_tsv.text), delimiter='\t'))
            DOWNLOAD_PATH = fr'C:\Users\ryans\Desktop\hospital_data\{file_name}.csv'

            with open(DOWNLOAD_PATH, 'w', newline='') as f_output:
                csv_output = csv.writer(f_output)
                csv_output.writerows(data)
    except Exception as e:
        print(e)

Somehow, I think I need to do a pip install. Not sure how to do it. Also, I need to change the save path to the Data Lake (or Storage Explorer). Not sure how to do this either. How can I get this up and running?


问:
React Native working with NativeBase: WARN NativeBase: The contrast ratio of 1:1 for darkText on transparent
I'm programming a React Native App using NativeBase.io

In my app where I use NativeBase I am getting the following error.....how do I fix this?

Here is the error:

WARN  NativeBase: The contrast ratio of 1:1 for darkText on
transparent falls below the WCAG recommended absolute minimum contrast
ratio of 3:1.
https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast
InputBase@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:193716:28
RCTView View
@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:150602:25
Box@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:191721:24
InputAdvance@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:193858:33
Input@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:193651:24
RCTView View
@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:150602:25
Box@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:191721:24
UserListScreen@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:223372:50
StaticContainer@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:234421:17
EnsureSingleNavigator@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:230142:24
SceneView@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:234305:22
RCTView View RCTView View
Background@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:236500:21
Screen@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:237782:108
RNSScreen
AnimatedComponent@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:67782:80
AnimatedComponentWrapper
Screen@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:238098:36
MaybeScreen@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:237954:24
RNSScreenContainer
ScreenContainer@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:238211:31
MaybeScreenContainer@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:237923:23
RCTView View
SafeAreaProviderCompat@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:237712:24
BottomTabView@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:226059:30
@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:234075:24
BottomTabNavigator@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:225921:32
EnsureSingleNavigator@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:230142:24
BaseNavigationContainer@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:229651:28
ThemeProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:235690:21
NavigationContainerInner@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:235550:26
SSRProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:193075:25
ToastProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:204142:24
PortalProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:201313:50
HybridProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:214396:24
RNCSafeAreaProvider
SafeAreaProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:154679:24
NativeBaseConfigProviderProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:148509:27
ThemeProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:145479:38
NativeBaseProvider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:214282:33
Provider@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:216267:21
App@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:108372:54
RCTView View RCTView View
AppContainer@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:75251:36
DanceConnectyCube(RootComponent)@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.DanceConnectyCube:82468:28
undefined

答:
I ran into this with an outline button. The warning "The contrast ratio of 1:1 for darkText on transparent" is referring to the background color of the button.

Here's a dark-on-white, light-on-black outline button that works in both light and dark modes, without hard-coding color values (other than black and white):

```<code>import { useContrastText } from 'native-base';

const bgLight = "white";
const bgDark = "black";
const lightContrastColor = useContrastText(bgLight);
const darkContrastColor = useContrastText(bgDark);

<Button
    variant="outline"
    colorScheme="light"
    _light={{ bg: bgLight, borderColor: lightContrastColor, _text: { color: lightContrastColor } }}
    _dark={{ bg: bgDark, borderColor: darkContrastColor, _text: { color: darkContrastColor } }}
    onPress={() => null}>Lorem Ipsum</Button>
</code>```

Body:
I ran into this with an outline button. The warning "The contrast ratio of 1:1 for darkText on transparent" is referring to the background color of the button.

Here's a dark-on-white, light-on-black outline button that works in both light and dark modes, without hard-coding color values (other than black and white):

import { useContrastText } from 'native-base';

const bgLight = "white";
const bgDark = "black";
const lightContrastColor = useContrastText(bgLight);
const darkContrastColor = useContrastText(bgDark);

<Button
    variant="outline"
    colorScheme="light"
    _light={{ bg: bgLight, borderColor: lightContrastColor, _text: { color: lightContrastColor } }}
    _dark={{ bg: bgDark, borderColor: darkContrastColor, _text: { color: darkContrastColor } }}
    onPress={() => null}>Lorem Ipsum</Button>


问:
How do I add characters in dates to make them look normal without affecting the rest of the line?
I have a file with tons of lines using a semicolon (;) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line

20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff

I want the end result to look like

2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff

I have tried the solution How Do I add Multiple characters using SED? (My first Poorly Made question) and change date format from DD/MM/YYYY to YYYY-MM-DD with sed doesn't make sense to me.

```<code>sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
    -e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
    < input > output
</code>```

This solution makes sense, but affects the rest of the line.

Body:
I have a file with tons of lines using a semicolon (;) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line

20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff

I want the end result to look like

2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff

I have tried the solution How Do I add Multiple characters using SED? (My first Poorly Made question) and change date format from DD/MM/YYYY to YYYY-MM-DD with sed doesn't make sense to me.

sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
    -e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
    < input > output

This solution makes sense, but affects the rest of the line.

Body:
Use capture-groups with fixed number of digits.

sed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1-\2-\3 \4:\5:\6/g' input > output


问:
Eclipse RCP - automatically shrink text in a TableViwer cell
I'm developing my first Eclipse RCP application and I would like to know how can I force JFace TableViewer component to auto-shrink the text within a table cell. Right now, if I pass through the model a property which contains multi-line text, the text is displayed as is, which causes every row in a table to have different height:

What I want is just a single line, optimally if that line (if its too long to fit the cell) would be converted to something like 'Im a very very long lin...' and if the size of the window changes the line becomes 'Im a very very long line living in a...' where the full property is eg. 'Im a very very long line living in a table cell\r\n and some other text'.

答:
Finally I do as David suggested:</p>

```<code>col.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public void update(ViewerCell cell) {
            String desc = ((Product) cell.getElement()).getDescription();
            desc = desc.replaceAll("\\r\\n|\\r|\\n", " ");
            cell.setText(desc);
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Finally I do as David suggested:

col.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public void update(ViewerCell cell) {
            String desc = ((Product) cell.getElement()).getDescription();
            desc = desc.replaceAll("\\r\\n|\\r|\\n", " ");
            cell.setText(desc);
        }
    });


问:
How to print only 1 copy of document when using "Process" in c#
I am trying to print a pdf in a c# console application, by starting a process.
Instead of printing only 1 copy of the document it prints multiple copies (3, 4, 5 or 6 unpredictable). This is my code...

```<code>var p = new Process
{
    StartInfo = new ProcessStartInfo
    {
        CreateNoWindow = true,
        Verb = "PrintTo",
        Arguments = printerName,
        FileName = filePath
    }
};
p.Start();
</code>```

Please can you tell me what I'm doing wrong?

答:
You can do that with this code.

```<code> private void SendToPrinter(string prepDok)
    {
        ProcessStartInfo info = new ProcessStartInfo();
        info.Verb = "print";
        info.FileName = prepDok;
        info.CreateNoWindow = false;
        info.WindowStyle = ProcessWindowStyle.Hidden;

        System.Windows.Forms.PrintDialog pd = new System.Windows.Forms.PrintDialog();
        pd.PrinterSettings.Copies = 1;
        Process p = new Process();
        p.StartInfo = info;
        p.StartInfo.Arguments = pd.PrinterSettings.PrinterName;
        p.Start();
        p.CloseMainWindow();

        Thread.Sleep(4000);
        if (!p.WaitForExit(5000))
        {
            if (!p.HasExited)
            {
                p.Kill();
            }
        }

    }
</code>```

This will set the number of copies to one and print dialog won't be shown.

Body:
I am trying to print a pdf in a c# console application, by starting a process.
Instead of printing only 1 copy of the document it prints multiple copies (3, 4, 5 or 6 unpredictable). This is my code...

var p = new Process
{
    StartInfo = new ProcessStartInfo
    {
        CreateNoWindow = true,
        Verb = "PrintTo",
        Arguments = printerName,
        FileName = filePath
    }
};
p.Start();

Please can you tell me what I'm doing wrong?

Body:
You can do that with this code.

 private void SendToPrinter(string prepDok)
    {
        ProcessStartInfo info = new ProcessStartInfo();
        info.Verb = "print";
        info.FileName = prepDok;
        info.CreateNoWindow = false;
        info.WindowStyle = ProcessWindowStyle.Hidden;

        System.Windows.Forms.PrintDialog pd = new System.Windows.Forms.PrintDialog();
        pd.PrinterSettings.Copies = 1;
        Process p = new Process();
        p.StartInfo = info;
        p.StartInfo.Arguments = pd.PrinterSettings.PrinterName;
        p.Start();
        p.CloseMainWindow();

        Thread.Sleep(4000);
        if (!p.WaitForExit(5000))
        {
            if (!p.HasExited)
            {
                p.Kill();
            }
        }

    }

This will set the number of copies to one and print dialog won't be shown.


问:
How to control the order of facet gird rows and/or columns in xarray?
I am trying to change the order of variables I use to make a facet grid in xarray. For example, I have [a,b,c,d] as column names. I want to reorder it to [c,d,a,b]. Unfortunately, unlike seaborn, I could not find parameters such as col_order or row_order in xarray plot function (

https://xarray.pydata.org/en/stable/generated/xarray.plot.FacetGrid.html

Update:
To help myself better explain what I need, I took the example below from the user guide of xarray:
In the following example, I need to change the place of months. I mean, for example, I want to put the month 7 as the first column and 2nd month as the 5th and so on and so forth.

```<code>import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
ds = xr.tutorial.open_dataset("air_temperature.nc").rename({"air": "Tair"})

# we will add a gradient field with appropriate attributes
ds["dTdx"] = ds.Tair.differentiate("lon") / 110e3 / np.cos(ds.lat * np.pi / 180)
ds["dTdy"] = ds.Tair.differentiate("lat") / 105e3
ds.dTdx.attrs = {"long_name": "$∂T/∂x$", "units": "°C/m"}
ds.dTdy.attrs = {"long_name": "$∂T/∂y$", "units": "°C/m"}
monthly_means = ds.groupby("time.month").mean()
# xarray's groupby reductions drop attributes. Let's assign them back so we get nice labels.
monthly_means.Tair.attrs = ds.Tair.attrs
fg = monthly_means.Tair.plot(
    col="month",
    col_wrap=4,  # each row has a maximum of 4 columns
)
plt.show()
</code>```

Any help is highly appreciated.

答:
xarray will respect the shape of your data, so you can rearrange the data prior to plotting:

In [2]: ds = xr.tutorial.open_dataset("air_temperature.nc")

In [3]: ds_mon = ds.groupby("time.month").mean()

In [4]: # order the data by month, descending
   ...: ds_mon.air.sel(month=list(range(12, 0, -1))).plot(
   ...:     col="month", col_wrap=4,
   ...: )

Out[4]: <xarray.plot.facetgrid.FacetGrid at 0x16b9a7700>
```

Body:
I am trying to change the order of variables I use to make a facet grid in xarray. For example, I have [a,b,c,d] as column names. I want to reorder it to [c,d,a,b]. Unfortunately, unlike seaborn, I could not find parameters such as col_order or row_order in xarray plot function (

https://xarray.pydata.org/en/stable/generated/xarray.plot.FacetGrid.html

Update:
To help myself better explain what I need, I took the example below from the user guide of xarray:
In the following example, I need to change the place of months. I mean, for example, I want to put the month 7 as the first column and 2nd month as the 5th and so on and so forth.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
ds = xr.tutorial.open_dataset("air_temperature.nc").rename({"air": "Tair"})

# we will add a gradient field with appropriate attributes
ds["dTdx"] = ds.Tair.differentiate("lon") / 110e3 / np.cos(ds.lat * np.pi / 180)
ds["dTdy"] = ds.Tair.differentiate("lat") / 105e3
ds.dTdx.attrs = {"long_name": "$∂T/∂x$", "units": "°C/m"}
ds.dTdy.attrs = {"long_name": "$∂T/∂y$", "units": "°C/m"}
monthly_means = ds.groupby("time.month").mean()
# xarray's groupby reductions drop attributes. Let's assign them back so we get nice labels.
monthly_means.Tair.attrs = ds.Tair.attrs
fg = monthly_means.Tair.plot(
    col="month",
    col_wrap=4,  # each row has a maximum of 4 columns
)
plt.show()

Any help is highly appreciated.


问:
How do I deserialize a binary AMQP message received with protobuf-net?
I am just learning C# and am using it with Godot. We are trying to send a binary Protobuf-encoded message from a client over AMQP and receive it with the C# script running in Godot.

I am at the point where the message is received and I am trying to deserialize it. The message body is a 44-byte array, but the protobuf-net deserialize doesn't take a byte array. The message body is of type object but it definitely contains a byte array.

    byte[] binaryBody = (byte[])message.Body;
    CommandBuffer commandBuffer;
    commandBuffer = Serializer.Deserialize<CommandBuffer>(binaryBody);
```
<p>This results in an error:</p>
```The call is ambiguous between the following methods or properties: 'Serializer.Deserialize<T>(ReadOnlyMemory<byte>, T, object)' and 'Serializer.Deserialize<T>(ReadOnlySpan<byte>, T, object)' [srt-godot-test]csharp(CS0121)
```
<p>Trying to convert <code>binaryBody</code> to a <code>MemoryStream</code> results in all kind of a mess and a protobuf that cannot be properly decoded:</p>
<pre class="lang-csharp prettyprint-override"><code>    MemoryStream st = new MemoryStream();
    st.Write(binaryBody, 0, binaryBody.Length);
</code>```

It seems like I should just be able to deserialize binaryBody somehow, but I cannot figure out what to do here.

答:
I found this post:
Protobuf-net Serialize/Deserialize to/from byte arrays

Which lead me to the MemoryStream page:
https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream.-ctor?redirectedfrom=MSDN&view=net-6.0#System_IO_MemoryStream__ctor_System_Byte___

And I noticed this option:
https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream.-ctor?view=net-6.0#system-io-memorystream-ctor(system-byte()-system-boolean)

Which resulted in this code:

  void GameEventReceived(IReceiverLink receiver, Message message)
  {
    GD.Print("Event received!");
    // accept the message so that it gets removed from the queue
    receiver.Accept(message);

    byte[] binaryBody = (byte[])message.Body;

    MemoryStream st = new MemoryStream(binaryBody, false);

    // prep a command buffer for processing the message
    CommandBuffer commandBuffer;
    commandBuffer = Serializer.Deserialize<CommandBuffer>(st);
  }
```

The key was creating the MemoryStream directly from the bytestring.

Body:
I am just learning C# and am using it with Godot. We are trying to send a binary Protobuf-encoded message from a client over AMQP and receive it with the C# script running in Godot.

I am at the point where the message is received and I am trying to deserialize it. The message body is a 44-byte array, but the protobuf-net deserialize doesn't take a byte array. The message body is of type object but it definitely contains a byte array.

    byte[] binaryBody = (byte[])message.Body;
    CommandBuffer commandBuffer;
    commandBuffer = Serializer.Deserialize<CommandBuffer>(binaryBody);

This results in an error:

The call is ambiguous between the following methods or properties: 'Serializer.Deserialize<T>(ReadOnlyMemory<byte>, T, object)' and 'Serializer.Deserialize<T>(ReadOnlySpan<byte>, T, object)' [srt-godot-test]csharp(CS0121)

Trying to convert binaryBody to a MemoryStream results in all kind of a mess and a protobuf that cannot be properly decoded:

    MemoryStream st = new MemoryStream();
    st.Write(binaryBody, 0, binaryBody.Length);

It seems like I should just be able to deserialize binaryBody somehow, but I cannot figure out what to do here.

Body:
I found this post:
Protobuf-net Serialize/Deserialize to/from byte arrays

Which lead me to the MemoryStream page:
https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream.-ctor?redirectedfrom=MSDN&view=net-6.0#System_IO_MemoryStream__ctor_System_Byte___

And I noticed this option:
https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream.-ctor?view=net-6.0#system-io-memorystream-ctor(system-byte()-system-boolean)

Which resulted in this code:

  void GameEventReceived(IReceiverLink receiver, Message message)
  {
    GD.Print("Event received!");
    // accept the message so that it gets removed from the queue
    receiver.Accept(message);

    byte[] binaryBody = (byte[])message.Body;

    MemoryStream st = new MemoryStream(binaryBody, false);

    // prep a command buffer for processing the message
    CommandBuffer commandBuffer;
    commandBuffer = Serializer.Deserialize<CommandBuffer>(st);
  }

The key was creating the MemoryStream directly from the bytestring.


问:
alpha blending is not working as it supposed to be
I create a new DirectX project and rendered 2 color components and now when I am passing the transparency from shader it is not changing anything, I am new to c++ and DirectX and I used the standard template from visual studio to create a project

project link: https://github.com/AbhishekSharma-SEG/TestAlphaBlending

Blend State

```<code>D3D11_BLEND_DESC blendDesc;
blendDesc.RenderTarget[0].BlendEnable = true;

blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_COLOR;
blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_COLOR;
blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;

blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;;

blendDesc.IndependentBlendEnable = false;
blendDesc.AlphaToCoverageEnable = false;

auto hr = m_d3dDevice->CreateBlendState(&blendDesc, &AlphaEnableBlendingState);
if (SUCCEEDED(hr))
{
    blendDesc.RenderTarget[0].BlendEnable = false;
    m_d3dDevice->CreateBlendState(&blendDesc, &AlphaDisableBlendingState);
    TurnOnAlphaBlending();
}
}
void DX::DeviceResources::TurnOnAlphaBlending()
{
    float input[4] = { 0,0,0,0 };
    m_d3dContext->OMSetBlendState(AlphaEnableBlendingState, input, 1);
}
void DX::DeviceResources::TurnOffAlphaBlending()
{
    float input[4] = { 0,0,0,0 };
    m_d3dContext->OMSetBlendState(AlphaDisableBlendingState, input, 1);
}
</code>```

Swapchain Desc

```<code>// Otherwise, create a new one using the same adapter as the existing Direct3D device.
DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH;
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};

swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width);      // Match the size of the window.
swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;              // This is the most common swap chain format.
swapChainDesc.Stereo = false;
swapChainDesc.SampleDesc.Count = 1;                             // Don't use multi-sampling.
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 2;                                  // Use double-buffering to minimize latency.
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;    // All Microsoft Store apps must use _FLIP_ SwapEffects.
swapChainDesc.Flags = 0;
swapChainDesc.Scaling = scaling;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
</code>```

Shader

```<code>struct PixelShaderInput
{
    float4 pos : SV_POSITION;
    float3 color : COLOR0;
};

float4 main(PixelShaderInput input) : SV_TARGET
{
    return float4(input.color, 0.2f);
}
</code>```

output

I am unable to find what is wrong, several tutorials and the site only told about setting up the blend state and I tried most of the settings they told me to apply but it is not working also I don't know why but the yellow component is supposed to be behind because renders call for yellow one occurs first but it is printing it above red one if anyone can help, please and thanks

new output after alpha mode ignore and setting blend mode as per straight

Edit: Fixed

so after some digging, I found that I m not using the depth stencil state which is causing this issue after using that it resolves, and obviously thanks to @chukWalbourn suggestion I was able to set up the write configuration for blending now it working perfectly fine here are the  change that helped in it

```<code>//Describe our Depth/Stencil Buffer
CD3D11_DEPTH_STENCIL_DESC depthStencilStateDesc;

depthStencilStateDesc.DepthEnable = false;
depthStencilStateDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilStateDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilStateDesc.StencilEnable = true;
depthStencilStateDesc.StencilReadMask = 0xFF;
depthStencilStateDesc.StencilWriteMask = 0xFF;
depthStencilStateDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilStateDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilStateDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilStateDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

DX::ThrowIfFailed(
    m_d3dDevice->CreateDepthStencilState(
        &depthStencilStateDesc,
        &m_d3dDepthStencilState
    )
);

m_d3dContext->OMSetDepthStencilState(m_d3dDepthStencilState.Get(), 1);
</code>```

答:
The DXGI swap-chain alpha mode should be set to DXGI_ALPHA_MODE_IGNORE for UWP or DXGI_ALPHA_MODE_UNSPECIFIED for Win32 when using it as a Direct3D render target. This is only there for some Direct2D / DirectComposition-related scenarios.

For straight-alpha, use:

```<code>D3D11_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].SrcBlend =
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend =
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOp =
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
</code>```

For premultiplied alpha use:

```<code>D3D11_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].SrcBlend =
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlend =
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOp =
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
</code>```

For 'additive' blend use:

```<code>D3D11_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].SrcBlend =
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend =
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].BlendOp =
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
</code>```

You may want to take a look at DirectX Tool Kit.

Body:
I create a new DirectX project and rendered 2 color components and now when I am passing the transparency from shader it is not changing anything, I am new to c++ and DirectX and I used the standard template from visual studio to create a project

project link: https://github.com/AbhishekSharma-SEG/TestAlphaBlending

Blend State

D3D11_BLEND_DESC blendDesc;
blendDesc.RenderTarget[0].BlendEnable = true;

blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_COLOR;
blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_COLOR;
blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;

blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;;

blendDesc.IndependentBlendEnable = false;
blendDesc.AlphaToCoverageEnable = false;

auto hr = m_d3dDevice->CreateBlendState(&blendDesc, &AlphaEnableBlendingState);
if (SUCCEEDED(hr))
{
    blendDesc.RenderTarget[0].BlendEnable = false;
    m_d3dDevice->CreateBlendState(&blendDesc, &AlphaDisableBlendingState);
    TurnOnAlphaBlending();
}
}
void DX::DeviceResources::TurnOnAlphaBlending()
{
    float input[4] = { 0,0,0,0 };
    m_d3dContext->OMSetBlendState(AlphaEnableBlendingState, input, 1);
}
void DX::DeviceResources::TurnOffAlphaBlending()
{
    float input[4] = { 0,0,0,0 };
    m_d3dContext->OMSetBlendState(AlphaDisableBlendingState, input, 1);
}

Swapchain Desc

// Otherwise, create a new one using the same adapter as the existing Direct3D device.
DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH;
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};

swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width);      // Match the size of the window.
swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;              // This is the most common swap chain format.
swapChainDesc.Stereo = false;
swapChainDesc.SampleDesc.Count = 1;                             // Don't use multi-sampling.
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 2;                                  // Use double-buffering to minimize latency.
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;    // All Microsoft Store apps must use _FLIP_ SwapEffects.
swapChainDesc.Flags = 0;
swapChainDesc.Scaling = scaling;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;

Shader

struct PixelShaderInput
{
    float4 pos : SV_POSITION;
    float3 color : COLOR0;
};

float4 main(PixelShaderInput input) : SV_TARGET
{
    return float4(input.color, 0.2f);
}

output

I am unable to find what is wrong, several tutorials and the site only told about setting up the blend state and I tried most of the settings they told me to apply but it is not working also I don't know why but the yellow component is supposed to be behind because renders call for yellow one occurs first but it is printing it above red one if anyone can help, please and thanks

new output after alpha mode ignore and setting blend mode as per straight

Edit: Fixed

so after some digging, I found that I m not using the depth stencil state which is causing this issue after using that it resolves, and obviously thanks to @chukWalbourn suggestion I was able to set up the write configuration for blending now it working perfectly fine here are the  change that helped in it

//Describe our Depth/Stencil Buffer
CD3D11_DEPTH_STENCIL_DESC depthStencilStateDesc;

depthStencilStateDesc.DepthEnable = false;
depthStencilStateDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilStateDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilStateDesc.StencilEnable = true;
depthStencilStateDesc.StencilReadMask = 0xFF;
depthStencilStateDesc.StencilWriteMask = 0xFF;
depthStencilStateDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilStateDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilStateDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilStateDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilStateDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

DX::ThrowIfFailed(
    m_d3dDevice->CreateDepthStencilState(
        &depthStencilStateDesc,
        &m_d3dDepthStencilState
    )
);

m_d3dContext->OMSetDepthStencilState(m_d3dDepthStencilState.Get(), 1);

Body:
The DXGI swap-chain alpha mode should be set to DXGI_ALPHA_MODE_IGNORE for UWP or DXGI_ALPHA_MODE_UNSPECIFIED for Win32 when using it as a Direct3D render target. This is only there for some Direct2D / DirectComposition-related scenarios.

For straight-alpha, use:

D3D11_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].SrcBlend =
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend =
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOp =
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

For premultiplied alpha use:

D3D11_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].SrcBlend =
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].DestBlend =
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOp =
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

For 'additive' blend use:

D3D11_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].SrcBlend =
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend =
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].BlendOp =
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

You may want to take a look at DirectX Tool Kit.


问:
replicate rows by n times in python
I have a dataframe that the first column are strings, the 2nd column are the numbers that I want to replicate each string.

```<code>df = pd.DataFrame({'String':['a','b', 'c', 'd', 'e', 'f', 'g'],
        'Times':[2, 3, 5, 3, 2, 4, 5]})
df
</code>```

String
Times

a
2

b
3

c
5

d
3

e
2

f
4

g
5

How can I create a data frame into this in python? (stopped at d but you know the pattern). Thanks!

String
Times

a
1

a
2

b
1

b
2

b
3

c
1

c
2

c
3

c
4

c
5

答:
A bit messy, but seems to do what you want:

new_df = pd.DataFrame(df.String.str.repeat(df.Times).apply(list).explode().reset_index(drop=True))

new_df["Times"] = new_df.groupby("String").cumcount() + 1
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>   String  Times
0       a      1
1       a      2
2       b      1
3       b      2
4       b      3
5       c      1
6       c      2
7       c      3
8       c      4
9       c      5
10      d      1
11      d      2
12      d      3
13      e      1
14      e      2
15      f      1
16      f      2
17      f      3
18      f      4
19      g      1
20      g      2
21      g      3
22      g      4
23      g      5
</code>```

Title: replicate rows by n times in python

Body:
I have a dataframe that the first column are strings, the 2nd column are the numbers that I want to replicate each string.

df = pd.DataFrame({'String':['a','b', 'c', 'd', 'e', 'f', 'g'],
        'Times':[2, 3, 5, 3, 2, 4, 5]})
df

String
Times

a
2

b
3

c
5

d
3

e
2

f
4

g
5

How can I create a data frame into this in python? (stopped at d but you know the pattern). Thanks!

String
Times

a
1

a
2

b
1

b
2

b
3

c
1

c
2

c
3

c
4

c
5

Body:
A bit messy, but seems to do what you want:

new_df = pd.DataFrame(df.String.str.repeat(df.Times).apply(list).explode().reset_index(drop=True))

new_df["Times"] = new_df.groupby("String").cumcount() + 1

Output:

   String  Times
0       a      1
1       a      2
2       b      1
3       b      2
4       b      3
5       c      1
6       c      2
7       c      3
8       c      4
9       c      5
10      d      1
11      d      2
12      d      3
13      e      1
14      e      2
15      f      1
16      f      2
17      f      3
18      f      4
19      g      1
20      g      2
21      g      3
22      g      4
23      g      5


问:
WPF touch events
I have a WPF app. In this app context menus are defined in XAML inside border elements. Unfortunately I don't have a Windows device with touch functionality.

1)
If these elements are operated by touch and the user presses a little longer on one of the border elements, does the context menu open automatically? Or do I have to open the context menu myself depending on the time between the TouchDown event and the TouchUp event?

2)
My app is so far operated by clicking with the mouse on TextBlock and Border elements. These do not have a Click event. Therefore I react on their MouseLeftButtonUp events. If these elements are now operated by touch, do I have to react to touch events or are MouseLeftButtonUp events already triggered automatically?

答:
Some touch inputs will trigger mouse events if conditions are met. But it will be hard to figure out these interactions without actual touch device. Said that, the answers are:

1 Touch press and hold will be translated to right click by the OS. So yes, context menu will open.

2 No, you need to implement custom click event utilizing touch events.

Title: WPF touch events


问:
The for loop loops only once and some variables are getting wierd numbers
I made this program for percentages. You enter percentages one by one and it calculates the average after each input. It calculates the jump between percentages, the overall jump, the sum of all percentages(Score gotten), and the percentage of the total score(If all the percentages were 100). The problem is that it runs the for loop only once; the jumps between the averages are weird numbers. When there are 4 iterations the variables that were previously ok at lesser iterations also start to get weird numbers.</p>
```<code>#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    int A;
    printf("Enter how many numbers are there: ");
    scanf("%d", &A);
    int C[A + 1], E[A + 1], F[A + 1];
    int B, D;
    for(B = 1; B <= A; B++)
    {
        printf("Enter a number. This statement will loop %d times: ", A);
        scanf("%d", &C[B]);
        for(D = 1; D <= B; D++)
        {
            C[0] = C[0] + C[D];
            E[0] = C[0] + C[D - 1];
        }
        E[B] = C[0] / B;
        E[0] = E[0] / (B - 1);
        F[B] = E[B] - E[0];
    }
    F[0] = E[A] - C[1];
    E[0] = (C[0] * 100)/ (100 * A);
    for(B = 1; B <= A; B++)
    {
        printf("Your score: %d,      Your average up to here: %d,      Increase/Decrease in
        average: %d\n", C[B], E[B], F[B]);
    }
    printf("Your overall jump/fall in average: %d,          your total score: %d,       The
    percentage you got: %d", F[0], C[0], E[0]);
    return 0;
}
</code>```

答:
well you have a division by zero

```<code>E[0] = E[0] / (B - 1);
</code>```

when b = 1. I am sure you get an error message telling you that

Body:
I made this program for percentages. You enter percentages one by one and it calculates the average after each input. It calculates the jump between percentages, the overall jump, the sum of all percentages(Score gotten), and the percentage of the total score(If all the percentages were 100). The problem is that it runs the for loop only once; the jumps between the averages are weird numbers. When there are 4 iterations the variables that were previously ok at lesser iterations also start to get weird numbers.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    int A;
    printf("Enter how many numbers are there: ");
    scanf("%d", &A);
    int C[A + 1], E[A + 1], F[A + 1];
    int B, D;
    for(B = 1; B <= A; B++)
    {
        printf("Enter a number. This statement will loop %d times: ", A);
        scanf("%d", &C[B]);
        for(D = 1; D <= B; D++)
        {
            C[0] = C[0] + C[D];
            E[0] = C[0] + C[D - 1];
        }
        E[B] = C[0] / B;
        E[0] = E[0] / (B - 1);
        F[B] = E[B] - E[0];
    }
    F[0] = E[A] - C[1];
    E[0] = (C[0] * 100)/ (100 * A);
    for(B = 1; B <= A; B++)
    {
        printf("Your score: %d,      Your average up to here: %d,      Increase/Decrease in
        average: %d\n", C[B], E[B], F[B]);
    }
    printf("Your overall jump/fall in average: %d,          your total score: %d,       The
    percentage you got: %d", F[0], C[0], E[0]);
    return 0;
}

Body:
well you have a division by zero

E[0] = E[0] / (B - 1);

when b = 1. I am sure you get an error message telling you that


问:
How to store data into model using fromJson in flutter firebase?
Currently I'm working on a flutter project. I'm trying to create a function that gets snapshot from Firebase document and stores it into userData model using fromJson function.

Here's my User.dart

```<code>class UserData {
  // final String uid;
  final String usn;
  final String fullName;
  final int? sem;
  final String branch;
  final String section;

  UserData({
    required this.usn,
    required this.fullName,
    required this.sem,
    required this.branch,
    required this.section,
  });

  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
        usn: json['usn'],
        fullName: json['fullName'],
        sem: json['sem'],
        branch: json['branch'],
        section: json['section']);
  }

  Map<String, dynamic> toMap() {
    return {
      'usn': usn,
      'fullName': fullName,
      'sem': sem,
      'branch': branch,
      'section': section
    };
  }
}
</code>```

In my database.dart
I want to create a Stream function in it to map to fromJson
Here's what I have tried

```<code> Stream<UserData?> curUserData() {
    return _db.collection('users').doc(user.uid).snapshots()
    .map((DocumentSnapshot snapshot) => UserData.fromJson(snapshot.data()));
  }
</code>```

Can anyone rectify the function?

I am getting error from above function.

答:
This example is for my case with cloud_firestore: ^3.1.7:

```<code>getLastStageNumber() async {

    QuerySnapshot querySnapshot = await stagesRef
        .orderBy('stage_number', descending: true)
        .limit(1)
        .get();
    StageMod stageMod;
    if (querySnapshot.docs.isNotEmpty) {
      stageMod = StageMod.fromJson(
          querySnapshot.docs.first.data()! as Map<String, dynamic>);
      lastStageNumber = stageMod.stageNumber;
    }
  }
</code>```

Body:
Currently I'm working on a flutter project. I'm trying to create a function that gets snapshot from Firebase document and stores it into userData model using fromJson function.

Here's my User.dart

class UserData {
  // final String uid;
  final String usn;
  final String fullName;
  final int? sem;
  final String branch;
  final String section;

  UserData({
    required this.usn,
    required this.fullName,
    required this.sem,
    required this.branch,
    required this.section,
  });

  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
        usn: json['usn'],
        fullName: json['fullName'],
        sem: json['sem'],
        branch: json['branch'],
        section: json['section']);
  }

  Map<String, dynamic> toMap() {
    return {
      'usn': usn,
      'fullName': fullName,
      'sem': sem,
      'branch': branch,
      'section': section
    };
  }
}

In my database.dart
I want to create a Stream function in it to map to fromJson
Here's what I have tried

 Stream<UserData?> curUserData() {
    return _db.collection('users').doc(user.uid).snapshots()
    .map((DocumentSnapshot snapshot) => UserData.fromJson(snapshot.data()));
  }

Can anyone rectify the function?

I am getting error from above function.

Body:
This example is for my case with cloud_firestore: ^3.1.7:

getLastStageNumber() async {

    QuerySnapshot querySnapshot = await stagesRef
        .orderBy('stage_number', descending: true)
        .limit(1)
        .get();
    StageMod stageMod;
    if (querySnapshot.docs.isNotEmpty) {
      stageMod = StageMod.fromJson(
          querySnapshot.docs.first.data()! as Map<String, dynamic>);
      lastStageNumber = stageMod.stageNumber;
    }
  }


问:
T24 Telnet Connection on TCP Port Using Python
How can we interact with temenos t24 TCServer on TCP port using Python libraries like telnet or socket? Has anyone worked on this area?

答:
You can connect by telnet and then post "tRun tSS [ofs source]"
where ofs source is an id from OFS.SOURCE T24 application (in older T24 command: "tSS [ofs source]" without "tRun"). It allows you to send OFS messages. With OFS you can do almost everything you want in T24 ;)</p>


问:
Java: Rationale of the Object class not being declared abstract
Why wasn't the java.lang.Object class declared to be abstract ?

Surely for an Object to be useful it needs added state or behaviour, an Object class is an abstraction, and as such it should have been declared abstract ...  why did they choose not to ?

答: You never know when you might want to use a simple Object as a placeholder. Think of it as like having a zero in a numerical system (and null doesn't work for this, since null represents the absence of data).</p>

OwnerDisplayName: Ande Turner

LastEditorDisplayName: Ande

OwnerDisplayName: Alan Daniels


问:
Would this class have a Strict Weak Ordering
Say I had class/struct Foo

```<code>struct Foo {
    int a, b;
    bool operator< (Foo const& r){
        return a < r.a;
    }
    bool operator== (Foo const& r){
        return a==r.a&&b==r.b;
    }
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };
</code>```

Now bar == baz is false but so are bar < baz and baz < bar.

Note that here the ordering completely ignores b but b is part of the equality relation.

答: Classes don't have weak ordering per se. A strict weak order is a binary function, like operator<(Foo, Foo). Once you realize that, it's obvious why function F can't influence whether function G is a SWO - it's an independent property of G.  That's why operator== can't influence whether operator< is a SWO.

Body:
Say I had class/struct Foo

struct Foo {
    int a, b;
    bool operator< (Foo const& r){
        return a < r.a;
    }
    bool operator== (Foo const& r){
        return a==r.a&&b==r.b;
    }
};
Foo bar = { 5, 1 };
Foo baz = { 5, 2 };

Now bar == baz is false but so are bar < baz and baz < bar.

Note that here the ordering completely ignores b but b is part of the equality relation.


问:
How can you tell Angular to send the Origin header?
I have an Angular application that connects with my server.  For internal reasons I want to be able to send the origin domain to the server as it can be accessed from a couple places, for example:

https://domain1.com/app
https://domain2.com/app

In order to do that I would like my Angular app to set the Origin header.  I have an interceptor and I tried to do something like this:

return next.handle(req.clone({setHeaders: {Origin: environment.origin}}));

However, it throws an error that says Refused to set unsafe header "Origin".  I understand why, but how can I tell Angular to include this header and set it to the current domain (or just set it how it normally would)?  I don't need it set to anything special, I just need it included.

答:
I believe the header you should set instead is Referer. The usage description of this header fits your scenario really well.

You could also track the access patterns on your server using a fully custom header too.


答:
We cannot set the header Origin from the Front end as its technically forbidden to do it from angular. Most browsers follow same origin policy where its not allowed to cross-communicate with different domain and these restriction is eased only if the domain is allowed access from the server.

But the CORS  issue can be resolved only through server side by setting 'Access-Control-Allow-Origin' to whatever domain you want to enable the access. Some example by using Nodejs

const app = express();
app.use(function (req, res, next) {

```<code>// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://domain1.com/app');

/
next();
</code>```

});

Title: How can you tell Angular to send the Origin header?

Body:
I have an Angular application that connects with my server.  For internal reasons I want to be able to send the origin domain to the server as it can be accessed from a couple places, for example:

https://domain1.com/app
https://domain2.com/app

In order to do that I would like my Angular app to set the Origin header.  I have an interceptor and I tried to do something like this:

return next.handle(req.clone({setHeaders: {Origin: environment.origin}}));

However, it throws an error that says Refused to set unsafe header "Origin".  I understand why, but how can I tell Angular to include this header and set it to the current domain (or just set it how it normally would)?  I don't need it set to anything special, I just need it included.

Body:
We cannot set the header Origin from the Front end as its technically forbidden to do it from angular. Most browsers follow same origin policy where its not allowed to cross-communicate with different domain and these restriction is eased only if the domain is allowed access from the server.

But the CORS  issue can be resolved only through server side by setting 'Access-Control-Allow-Origin' to whatever domain you want to enable the access. Some example by using Nodejs

const app = express();
app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://domain1.com/app');

/
next();

});


答:
Another method could be:</p>
```<code>df.assign(Times = df.Times.apply(lambda x: range(1, x + 1))).explode('Times')
Out[]:
  String Times
0      a     1
0      a     2
1      b     1
1      b     2
1      b     3
2      c     1
2      c     2
2      c     3
2      c     4
2      c     5
</code>```

Title: replicate rows by n times in python

Body:
Another method could be:

df.assign(Times = df.Times.apply(lambda x: range(1, x + 1))).explode('Times')
Out[]:
  String Times
0      a     1
0      a     2
1      b     1
1      b     2
1      b     3
2      c     1
2      c     2
2      c     3
2      c     4
2      c     5


问:
Upload file using HttpWebRequest -- Couldn't upload?
Here is the code - upload file to uri.
I can't upload it. Is anything wrong? </p>

```<code>string fileToUpload = @"F:\\upload_file.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:8080/upload.txt"); //Given URI is exists
req.Method = "POST";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);
byte[] inData = new byte[rdr.Length];

// Get data from upload file to inData
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);

// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();

req.GetResponse();
// after uploading close stream
reqStream.Close();
</code>```

答:
At first glance I think there may be something wrong with the file your selecting the @ should be used to define a specific string. No escape characters are needed. Vice-versa with the string below in your web request.

So you should correct it either to @"F:\upload_file.txt"; or "F:\\upload_file.txt";

Body:
Here is the code - upload file to uri.
I can't upload it. Is anything wrong?

string fileToUpload = @"F:\\upload_file.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:8080/upload.txt"); //Given URI is exists
req.Method = "POST";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);
byte[] inData = new byte[rdr.Length];

// Get data from upload file to inData
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);

// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();

req.GetResponse();
// after uploading close stream
reqStream.Close();


问:
Perlin noise in python
I have searched everywhere for an answer for this question but no luck. I want to figure out how to take the image generated by python's noise library and export it. does anybody know how?</p>

答:
Convert your data list to a numpy array then use PIL library to save the numpy array to a grayscale image:

```<code># Install PIL: pip install pillow (probably already installed)
from PIL import Image
import numpy as np
from perlin_noise import PerlinNoise

noise = PerlinNoise(octaves=10, seed=1)
xpix, ypix = 100, 100
pic = [[noise([i/xpix, j/ypix]) for j in range(xpix)] for i in range(ypix)]

image = Image.fromarray(np.array(pic) * 255, 'L')
image.save('output.png')
</code>```

Title: Perlin noise in python

Body:
Convert your data list to a numpy array then use PIL library to save the numpy array to a grayscale image:

# Install PIL: pip install pillow (probably already installed)
from PIL import Image
import numpy as np
from perlin_noise import PerlinNoise

noise = PerlinNoise(octaves=10, seed=1)
xpix, ypix = 100, 100
pic = [[noise([i/xpix, j/ypix]) for j in range(xpix)] for i in range(ypix)]

image = Image.fromarray(np.array(pic) * 255, 'L')
image.save('output.png')


问:
LINQPad: How do I add a property to each row being dumped?
In LINQPad, I frequently want to Dump some SQL table, but add a property to each row. I usually default to the simple:

Publishers
.Select(p => new { p, AppCount = p.Apps.Count() })
```
<p>But of course this results in messy output, because each item is formatted as a vertical table, with an extra column containing the added property. I could create a new object, but that's very verbose, and you lose the table traversal links:</p>
<pre class="lang-cs prettyprint-override"><code>Publishers
.Select(p => new { p.PublisherId, p.Name, p.Added, ..., AppCount = p.Apps.Count() })
</code>```

What I'd love is some sort of merge syntax, which creates a dynamic object to dump with the added property:

Publishers
.Select(p => p.Merge(new { AppCount = p.Apps.Count() })
```

I've tried a few different ways to accomplish that: using JsonConvert.SerializeObject (this goes haywire trying to serialize all the foreign key references and repeating loops, using ExpandoObject (couldn't come up with a nice clean syntax), and libraries like https://github.com/kfinley/TypeMerger, which I haven't gotten to work either.

Has anyone come up with a clean way to do this? Does LINQPad have some built in synax for this I can use? Thanks!

UPDATE: I uploaded a sample script to demonstrate the issue and let anyone try their solutions against: http://share.linqpad.net/kclxpl.linq

To run, you'll need to populate the Nutshell database, which you can do using the "Populate demo database" sample in LINQPad.

答:
You can add some extension methods to make this work. I do not recommend adding these to My Extensions because they require importing System.Dynamic which you probably don't want for most queries. Put these in another query which imports System.Dynamic and #load it when desired.

```<code>public static class ExpandoObjectExt {
    // convert object to ExpandoObject, add a property and return as dynamic
    public static dynamic With<T, TAdd>(this T obj, string propName, TAdd val) {
        var eo = Util.ToExpando(obj);
        var objDict = (IDictionary<string, object>)eo;
        objDict[propName] = val;
        return eo;
    }
    // convert IEnumerable<T> to IEnumerable<dynamic>, adding a property to each object
    public static IEnumerable<dynamic> With<T, TAdd>(this IEnumerable<T> src, string propName, Func<T, TAdd> valFn) => src.Select(s => s.With(propName, valFn(s)));
}
</code>```

Now you can use this like:

```<code>Publishers
    .With("AppCount", p => p.Apps.Count())
</code>```

However, conversion to ExpandoObject will eliminate any hyperlinks for collection properties, you can get around this by specifying only one level of output with an explicit .Dump(1). You could also write a custom Util.ToExpando (the code is here) that uses Util.OnDemand to create hyperlinks for collection properties.

Also, if you want to add more than one property, you can write variations of With that take multiple pairs or a version that tests for an ExpandoObject (and IEnumerable<ExpandoObject>) and can be chained fluent style.

Body:
In LINQPad, I frequently want to Dump some SQL table, but add a property to each row. I usually default to the simple:

Publishers
.Select(p => new { p, AppCount = p.Apps.Count() })

But of course this results in messy output, because each item is formatted as a vertical table, with an extra column containing the added property. I could create a new object, but that's very verbose, and you lose the table traversal links:

Publishers
.Select(p => new { p.PublisherId, p.Name, p.Added, ..., AppCount = p.Apps.Count() })

What I'd love is some sort of merge syntax, which creates a dynamic object to dump with the added property:

Publishers
.Select(p => p.Merge(new { AppCount = p.Apps.Count() })

I've tried a few different ways to accomplish that: using JsonConvert.SerializeObject (this goes haywire trying to serialize all the foreign key references and repeating loops, using ExpandoObject (couldn't come up with a nice clean syntax), and libraries like https://github.com/kfinley/TypeMerger, which I haven't gotten to work either.

Has anyone come up with a clean way to do this? Does LINQPad have some built in synax for this I can use? Thanks!

UPDATE: I uploaded a sample script to demonstrate the issue and let anyone try their solutions against: http://share.linqpad.net/kclxpl.linq

To run, you'll need to populate the Nutshell database, which you can do using the "Populate demo database" sample in LINQPad.

Body:
You can add some extension methods to make this work. I do not recommend adding these to My Extensions because they require importing System.Dynamic which you probably don't want for most queries. Put these in another query which imports System.Dynamic and #load it when desired.

public static class ExpandoObjectExt {
    // convert object to ExpandoObject, add a property and return as dynamic
    public static dynamic With<T, TAdd>(this T obj, string propName, TAdd val) {
        var eo = Util.ToExpando(obj);
        var objDict = (IDictionary<string, object>)eo;
        objDict[propName] = val;
        return eo;
    }
    // convert IEnumerable<T> to IEnumerable<dynamic>, adding a property to each object
    public static IEnumerable<dynamic> With<T, TAdd>(this IEnumerable<T> src, string propName, Func<T, TAdd> valFn) => src.Select(s => s.With(propName, valFn(s)));
}

Now you can use this like:

Publishers
    .With("AppCount", p => p.Apps.Count())

However, conversion to ExpandoObject will eliminate any hyperlinks for collection properties, you can get around this by specifying only one level of output with an explicit .Dump(1). You could also write a custom Util.ToExpando (the code is here) that uses Util.OnDemand to create hyperlinks for collection properties.

Also, if you want to add more than one property, you can write variations of With that take multiple pairs or a version that tests for an ExpandoObject (and IEnumerable<ExpandoObject>) and can be chained fluent style.


问:
How to search an element in column of a dataframe containing lists
I have a pandas dataframe df which contains two columns. First column sentence contains the sentence and second column keywords contains the all the keywords in list from the sentence in the first column. So my dataframe looks something like this :

```<code>>>> df
                                       sentence                          keywords
0        What are the advantages of the prepaid             [advantages, prepaid]
1     is salon facility available in your hotel          [salon, facility, hotel]
2  I want to check my balance and usage history  [check, balance, usage, history]
</code>```

Now suppose I have a list like ["salon", "usage", "history"] containing the keywords which I want to search against the keywords column and in return I want to get all the sentences containing the keywords in the given list. So the output in this particular case would be :

```<code>>>> output
["is salon facility available in your hotel", "I want to check my balance and usage history"]
</code>```

What is the fastest and most efficient way of achieving this result because I have thousands of sentences in the sentence column. The only way I know to achieve this to get all the lists from keywords column in a separate list and enumerate over it and get the indexes of the all the sub-lists containing the keywords and then look for same indexes in the sentence column. But this would be very slow. Is there any other better way of doing this?

Data:

```<code>data = {'sentence': ['What are the advantages of the prepaid',
                     'is salon facility available in your hotel',
                     'I want to check my balance and usage history'],
        'keywords': [['advantages', 'prepaid'],
                     ['salon', 'facility', 'hotel'],
                     ['check', 'balance', 'usage', 'history']]}
</code>```

答:
You can use set.isjdisoint and check if there are any overlapping words with the "keywords" to create a boolean mask. Then, use the mask on df to filter the matching sentences:

```<code>lst = ["salon", "usage", "history"]
msk = df['keywords'].apply(lambda x: not set(x).isdisjoint(lst))
out = df.loc[msk, 'sentence'].tolist()
</code>```

Output:

```<code>['is salon facility available in your hotel', 'I want to check my balance and usage history']
</code>```

Body:
I have a pandas dataframe df which contains two columns. First column sentence contains the sentence and second column keywords contains the all the keywords in list from the sentence in the first column. So my dataframe looks something like this :

>>> df
                                       sentence                          keywords
0        What are the advantages of the prepaid             [advantages, prepaid]
1     is salon facility available in your hotel          [salon, facility, hotel]
2  I want to check my balance and usage history  [check, balance, usage, history]

Now suppose I have a list like ["salon", "usage", "history"] containing the keywords which I want to search against the keywords column and in return I want to get all the sentences containing the keywords in the given list. So the output in this particular case would be :

>>> output
["is salon facility available in your hotel", "I want to check my balance and usage history"]

What is the fastest and most efficient way of achieving this result because I have thousands of sentences in the sentence column. The only way I know to achieve this to get all the lists from keywords column in a separate list and enumerate over it and get the indexes of the all the sub-lists containing the keywords and then look for same indexes in the sentence column. But this would be very slow. Is there any other better way of doing this?

Data:

data = {'sentence': ['What are the advantages of the prepaid',
                     'is salon facility available in your hotel',
                     'I want to check my balance and usage history'],
        'keywords': [['advantages', 'prepaid'],
                     ['salon', 'facility', 'hotel'],
                     ['check', 'balance', 'usage', 'history']]}

Body:
You can use set.isjdisoint and check if there are any overlapping words with the "keywords" to create a boolean mask. Then, use the mask on df to filter the matching sentences:

lst = ["salon", "usage", "history"]
msk = df['keywords'].apply(lambda x: not set(x).isdisjoint(lst))
out = df.loc[msk, 'sentence'].tolist()

Output:

['is salon facility available in your hotel', 'I want to check my balance and usage history']