问:
bash: aliasing for filtering lines with specified character count
I want to filter lines on bash CLI that have a character count provided by the user.

While this can be done through awk (eg,| awk -F+ 'NF==7'), I want to alias this (say as cfreq) so that I can use it as follows:

```<code>$ cat foo | awk '$1 > 10' | cfreq 7 | wc
</code>```

While the command can be generated by something simple such as printf (eg, printf "awk -F+ NF==%s\n" 7), I am unable to turn this into some alias that I can use across multiple systems though .bashrc file. Any help would be greatly appreciated.

PS: While the above requirement assumes the character + to be the reference character, if I can generalize that as well, it could be better. Eg:

```<code>$ cat foo | awk '$1 > 10' | cfreq + 7 | wc
</code>```

I am not sure if this is too much to expect from aliasing, though I have been able to alias similar tasks in some cases.

Body:
I want to filter lines on bash CLI that have a character count provided by the user.

While this can be done through awk (eg,| awk -F+ 'NF==7'), I want to alias this (say as cfreq) so that I can use it as follows:

$ cat foo | awk '$1 > 10' | cfreq 7 | wc

While the command can be generated by something simple such as printf (eg, printf "awk -F+ NF==%s\n" 7), I am unable to turn this into some alias that I can use across multiple systems though .bashrc file. Any help would be greatly appreciated.

PS: While the above requirement assumes the character + to be the reference character, if I can generalize that as well, it could be better. Eg:

$ cat foo | awk '$1 > 10' | cfreq + 7 | wc

I am not sure if this is too much to expect from aliasing, though I have been able to alias similar tasks in some cases.

Body:
Use a function instead of an alias:

cfreq() { local n="$1"; shift; awk -F'+' -v n="$n" 'NF==n' "${@:--}"; }

e.g.:

$ { printf '%s+' {1..8}; echo 9; } | cfreq 9
1+2+3+4+5+6+7+8+9

$ { printf '%s+' {1..8}; echo 9; } | cfreq 7
$

$ { printf '%s+' {1..8}; echo 9; } > file
$ cfreq 9 file
1+2+3+4+5+6+7+8+9


来源: stackexchange

问:
Template arguments to operator (over loading)
I have a struct that is "templated" like this:

```<code>template<int _WM_BITS>
struct STD_LOGIC_VECTOR_32 {
  const int s_Bits = _WM_BITS;
  int other data
};
</code>```

I have two overloaded function templates for the * operator:

```<code>int operator*(STD_LOGIC_VECTOR_32<0> a, STD_LOGIC_VECTOR_32<1> b) {
   // ... want to throw a compile time error with static_assert
}
int operator*(STD_LOGIC_VECTOR_32<0> a, STD_LOGIC_VECTOR_32<0> b) {
   // ... blah no error
}
</code>```

At the moment, the compilation always fails (and I understand why). However, the erroring function is never called and therefore should never be in the program text once compilation has completed, so the static_assert is too early in the compiler process to detect this. I understand and accept this too.

The question is: How can I parameterize the * operator overload function to include all integer template values of STD_LOGIC_VECTOR_32 and then catch the invocations where the template parameters are not the same? This information is available to the compiler, as each concrete instance of STD_LOGIC_VECTOR_32 must be instantiated in the code with:

```<code>struct STD_LOGIC_VECTOR_32<24> a;
</code>```

Therefore, the compiler knows which * operator function to use and the const element in the struct is initialized at compile time to a specific, immutable value.

I think the order of compilation processing is going to get the better of me, but I thought I would ask the question; after all C++ is supposed to be a multi-pass compilation process.

答:
Make your * operator a function template that takes the size(s) as its template parameters:

template<int _WM_BITS>
struct STD_LOGIC_VECTOR_32 {
    const int s_Bits = _WM_BITS;
    int other_data;
};

template<int N, int M>
int operator*(STD_LOGIC_VECTOR_32<N> a, STD_LOGIC_VECTOR_32<M> b)
{
    static_assert(N == M, "Sizes don't match");
    // ... do stuff ...
    return 0;
}

int main()
{
    STD_LOGIC_VECTOR_32<0> a, b;
    STD_LOGIC_VECTOR_32<1> c;
    auto d = a * b; // OK
    auto e = a * c; // error : static_assert failed due to requirement '0 == 1' "Sizes don't match"
    return 0;
}
```
<p>Alternatively, as the two sizes <em>have</em> to be the same, you can simply have only one template parameter:</p>
<pre class="lang-cpp prettyprint-override"><code>template<int N>
int operator*(STD_LOGIC_VECTOR_32<N> a, STD_LOGIC_VECTOR_32<N> b)
{
    // ... do stuff ...
    return 0;
}
</code>```

But then the error is different: the auto e = a * c; statement from the above main will generate:

error : invalid operands to binary expression
('STD_LOGIC_VECTOR_32<0>' and 'STD_LOGIC_VECTOR_32<1>')

So, if you want to force the use of the static_assert, then stick with the two-int template.

ContentLicense: CC BY-SA 4.0

Body:
I have a struct that is "templated" like this:

template<int _WM_BITS>
struct STD_LOGIC_VECTOR_32 {
  const int s_Bits = _WM_BITS;
  int other data
};

I have two overloaded function templates for the * operator:

int operator*(STD_LOGIC_VECTOR_32<0> a, STD_LOGIC_VECTOR_32<1> b) {
   // ... want to throw a compile time error with static_assert
}
int operator*(STD_LOGIC_VECTOR_32<0> a, STD_LOGIC_VECTOR_32<0> b) {
   // ... blah no error
}

At the moment, the compilation always fails (and I understand why). However, the erroring function is never called and therefore should never be in the program text once compilation has completed, so the static_assert is too early in the compiler process to detect this. I understand and accept this too.

The question is: How can I parameterize the * operator overload function to include all integer template values of STD_LOGIC_VECTOR_32 and then catch the invocations where the template parameters are not the same? This information is available to the compiler, as each concrete instance of STD_LOGIC_VECTOR_32 must be instantiated in the code with:

struct STD_LOGIC_VECTOR_32<24> a;

Therefore, the compiler knows which * operator function to use and the const element in the struct is initialized at compile time to a specific, immutable value.

I think the order of compilation processing is going to get the better of me, but I thought I would ask the question; after all C++ is supposed to be a multi-pass compilation process.

Body:
Make your * operator a function template that takes the size(s) as its template parameters:

template<int _WM_BITS>
struct STD_LOGIC_VECTOR_32 {
    const int s_Bits = _WM_BITS;
    int other_data;
};

template<int N, int M>
int operator*(STD_LOGIC_VECTOR_32<N> a, STD_LOGIC_VECTOR_32<M> b)
{
    static_assert(N == M, "Sizes don't match");
    // ... do stuff ...
    return 0;
}

int main()
{
    STD_LOGIC_VECTOR_32<0> a, b;
    STD_LOGIC_VECTOR_32<1> c;
    auto d = a * b; // OK
    auto e = a * c; // error : static_assert failed due to requirement '0 == 1' "Sizes don't match"
    return 0;
}

Alternatively, as the two sizes have to be the same, you can simply have only one template parameter:

template<int N>
int operator*(STD_LOGIC_VECTOR_32<N> a, STD_LOGIC_VECTOR_32<N> b)
{
    // ... do stuff ...
    return 0;
}

But then the error is different: the auto e = a * c; statement from the above main will generate:

error : invalid operands to binary expression
('STD_LOGIC_VECTOR_32<0>' and 'STD_LOGIC_VECTOR_32<1>')

So, if you want to force the use of the static_assert, then stick with the two-int template.


问:
How to store output in log file in this case:
```<code>webhook=https://webhook-url

if [[ some_condition ]]; then
curl "some_command..." -d '{"content":"'"success"'"}' $webhook #sends message to discord if condition is met
else
curl "some_command..." -d '{"content":"'"error"'"}' $webhook #sends message to discord if condition isn't met
fi
</code>```

Above bash script successfully sends message to discord but at the same time I want it to store the same message in a log file. Without using webhook, earlier code was as follows:

```<code>if [[ some_condition ]]; then
echo "success" >> file.log
else
echo "error" >> file.log
fi
</code>```

Now I'm not sure how do I include >> file.log command in first script.

答:
If the content being sent to discord is just "success"

Shouldn't you just be able to do this?

```<code>webhook=https://webhook-url

if [[ some_condition ]]; then
curl "some_command..." -d '{"content":"'"success"'"}' $webhook
echo "success" >> file.log
else
curl "some_command..." -d '{"content":"'"error"'"}' $webhook
echo "error" >> file.log
fi
</code>```

Otherwise, if you are trying to store the response from curl, perhaps something like this could work?

```<code>webhook=https://webhook-url

if [[ some_condition ]]; then
res=$(curl "some_command..." -d '{"content":"'"success"'"}' $webhook)
echo "$res" >> file.log
else
res=$(curl "some_command..." -d '{"content":"'"error"'"}' $webhook)
echo "$res" >> file.log
fi
</code>```

Update:

Maybe try this?

```<code>cmd="curl "some_command..." -d '{"content":"'"success"'"}' $webhook"
echo $cmd >> file.log
</code>```

Body:
webhook=https://webhook-url

if [[ some_condition ]]; then
curl "some_command..." -d '{"content":"'"success"'"}' $webhook #sends message to discord if condition is met
else
curl "some_command..." -d '{"content":"'"error"'"}' $webhook #sends message to discord if condition isn't met
fi

Above bash script successfully sends message to discord but at the same time I want it to store the same message in a log file. Without using webhook, earlier code was as follows:

if [[ some_condition ]]; then
echo "success" >> file.log
else
echo "error" >> file.log
fi

Now I'm not sure how do I include >> file.log command in first script.

Body:
If the content being sent to discord is just "success"

Shouldn't you just be able to do this?

webhook=https://webhook-url

if [[ some_condition ]]; then
curl "some_command..." -d '{"content":"'"success"'"}' $webhook
echo "success" >> file.log
else
curl "some_command..." -d '{"content":"'"error"'"}' $webhook
echo "error" >> file.log
fi

Otherwise, if you are trying to store the response from curl, perhaps something like this could work?

webhook=https://webhook-url

if [[ some_condition ]]; then
res=$(curl "some_command..." -d '{"content":"'"success"'"}' $webhook)
echo "$res" >> file.log
else
res=$(curl "some_command..." -d '{"content":"'"error"'"}' $webhook)
echo "$res" >> file.log
fi

Update:

Maybe try this?

cmd="curl "some_command..." -d '{"content":"'"success"'"}' $webhook"
echo $cmd >> file.log


问:
Sql - Using boolean logic in the where clause
i have a where clause that looks like this

```<code>WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)
</code>```

it is basically allowing filtering within ceratin ranges to be specified for a report
If values are omitted then they default to a very larg positive or negative number

The problem I have is that certain users don't have a Tolerance defined, which means their Tolerance percentage will always be zero,

so if the report specifed a criteria like this

```<code>set @GBPExposureUpper = -7500
    set @OnsideOffsideUpper = -3
    set @UsedToleranceUpper = -100
</code>```

then it would not include users who don't have a tolerance defined (as their tolerance will be zero - which is obviously larger than -100)

So I've created a bit field (@ShowNoSpecialTerms) which is controlled from a checkbox on the report which sets a flag to indicate that we want to addiionally include users who don't have a tolerance defined

When this is false we should use the filter conditions as normal

When this it is true, we should additionally include users who don't have a tolerance defined - these can be identified using the ToleranceLevel column

so the logic is kind of like

```<code>if (@ShowNoSpecialTerms = 0)

    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)

...

if  (@ShowNoSpecialTerms = 1)
--then additionally bring back result where ToleranceLevel=0
</code>```

Have tried the following

```<code>WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND (@ShowNoSpecialTerms = 0 OR
        UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
        AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999))
</code>```

This is half way to what I want - basically when    @ShowNoSpecialTerms = 1 it ignores the rest of the tolerance check

However, what I want is for it to return he results or the tolerance check PLUS those users who have a ToleranceLevel of zero

答:
This is still pretty unclear, but I think you want:

```<code>WHERE (normal conditions)
OR (@ShowNoSpecialTerms = 1 AND
    <Additional logic for those special users>).
</code>```

The OR will only be used if the bit is flipped in that scenario.

ContentLicense: CC BY-SA 3.0

Body:
i have a where clause that looks like this

WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)

it is basically allowing filtering within ceratin ranges to be specified for a report
If values are omitted then they default to a very larg positive or negative number

The problem I have is that certain users don't have a Tolerance defined, which means their Tolerance percentage will always be zero,

so if the report specifed a criteria like this

set @GBPExposureUpper = -7500
    set @OnsideOffsideUpper = -3
    set @UsedToleranceUpper = -100

then it would not include users who don't have a tolerance defined (as their tolerance will be zero - which is obviously larger than -100)

So I've created a bit field (@ShowNoSpecialTerms) which is controlled from a checkbox on the report which sets a flag to indicate that we want to addiionally include users who don't have a tolerance defined

When this is false we should use the filter conditions as normal

When this it is true, we should additionally include users who don't have a tolerance defined - these can be identified using the ToleranceLevel column

so the logic is kind of like

if (@ShowNoSpecialTerms = 0)

    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)

...

if  (@ShowNoSpecialTerms = 1)
--then additionally bring back result where ToleranceLevel=0

Have tried the following

WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND (@ShowNoSpecialTerms = 0 OR
        UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
        AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999))

This is half way to what I want - basically when    @ShowNoSpecialTerms = 1 it ignores the rest of the tolerance check

However, what I want is for it to return he results or the tolerance check PLUS those users who have a ToleranceLevel of zero

Body:
This is still pretty unclear, but I think you want:

WHERE (normal conditions)
OR (@ShowNoSpecialTerms = 1 AND
    <Additional logic for those special users>).

The OR will only be used if the bit is flipped in that scenario.


问:
Partially initialized module 'csv' has no attribute 'writer' (most likely due to a circular import)
I tried many times but it showing same error, i dont know where is did mistake..</p>
```<code>import csv

with open('student.csv','w',newline='') as f:
   w = csv.writer(f)
   w.writerow(['Rollno','Name','Marks'])
   w.writerow([101,'somesh',89])
   w.writerow([102,'yogesh',85])
   w.writerow([103,'akhilesh',75])
   w.writerow([874,'supreet',87])
</code>```

答: This error is often related to the name of the .py file, as it is named as csv.py. When it tries to import csv, it imports its csv.py file which does not contain any csv.writer functions. This can be solved by simply changing the name of your .py file.</p>

Body:
I tried many times but it showing same error, i dont know where is did mistake..

import csv

with open('student.csv','w',newline='') as f:
   w = csv.writer(f)
   w.writerow(['Rollno','Name','Marks'])
   w.writerow([101,'somesh',89])
   w.writerow([102,'yogesh',85])
   w.writerow([103,'akhilesh',75])
   w.writerow([874,'supreet',87])


问:
How do I make a locator based on custom attribute based on webpage of a hybrid app
I tried to use xpath for custom attribute provided by developers but getting no element found exception.

```<code>[HTTP] --> POST /wd/session/5fcb27d1-ab07-4d9b-b06f-cb4d006391e3/element
[HTTP] {"using":"xpath","value":"//input[@data-autoid='AC_NAME_ctrl']"}
[debug] [W3C (5fcb27d1)] Calling AppiumDriver.findElement() with args: ["xpath","//input[@data-autoid='AC_NAME_ctrl']","5fcb27d1-ab07-4d9b-b06f-cb4d006391e3"]
[debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[debug] [BaseDriver] Waiting up to 10000 ms for condition
[debug] [WD Proxy] Matched '/element' to command name 'findElement'
[debug] [WD Proxy] Proxying [POST /element] to [POST http://127.0.0.1:8201/wd/hub/session/bb01926e-16fe-426e-881c-d1b4c689bc8e/element] with body: {"strategy":"xpath","selector":"//input[@data-autoid='AC_NAME_ctrl']","context":"","multiple":false}
[WD Proxy] Got response with status 404: {"sessionId":"bb01926e-16fe-426e-881c-d1b4c689bc8e","value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters","stacktrace":"io.appium.uiautomator2.common.exceptions.ElementNotFoundException: An element could not be located on the page using the given search parameters\n\tat io.appium.uiautomator2.handler.FindElement.findElement(FindElement.java:90)\n\tat io.appium.uiautomator2.handler.FindElement.safeHandle(FindElement.java:67)\n\tat io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:59)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:266)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:260)\n\tat io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:68)\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)\n\tat io.netty.channel.AbstractChannelHandlerCont...
</code>```

Code used:

```<code>WebElement f1 = driver.findElement(By.xpath("//input[@data-autoid='AC_NAME_ctrl']"));
f1.sendKeys("Rahul");
</code>```

data-autoid is custom attribute with value 'AC_NAME_ctrl'
Any help in this direction will be helpful.

答: If i get it right , you wanna create a locator based on the customer input ?</p>

Body:
I tried to use xpath for custom attribute provided by developers but getting no element found exception.

[HTTP] --> POST /wd/session/5fcb27d1-ab07-4d9b-b06f-cb4d006391e3/element
[HTTP] {"using":"xpath","value":"//input[@data-autoid='AC_NAME_ctrl']"}
[debug] [W3C (5fcb27d1)] Calling AppiumDriver.findElement() with args: ["xpath","//input[@data-autoid='AC_NAME_ctrl']","5fcb27d1-ab07-4d9b-b06f-cb4d006391e3"]
[debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[debug] [BaseDriver] Waiting up to 10000 ms for condition
[debug] [WD Proxy] Matched '/element' to command name 'findElement'
[debug] [WD Proxy] Proxying [POST /element] to [POST http://127.0.0.1:8201/wd/hub/session/bb01926e-16fe-426e-881c-d1b4c689bc8e/element] with body: {"strategy":"xpath","selector":"//input[@data-autoid='AC_NAME_ctrl']","context":"","multiple":false}
[WD Proxy] Got response with status 404: {"sessionId":"bb01926e-16fe-426e-881c-d1b4c689bc8e","value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters","stacktrace":"io.appium.uiautomator2.common.exceptions.ElementNotFoundException: An element could not be located on the page using the given search parameters\n\tat io.appium.uiautomator2.handler.FindElement.findElement(FindElement.java:90)\n\tat io.appium.uiautomator2.handler.FindElement.safeHandle(FindElement.java:67)\n\tat io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:59)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:266)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:260)\n\tat io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:68)\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)\n\tat io.netty.channel.AbstractChannelHandlerCont...

Code used:

WebElement f1 = driver.findElement(By.xpath("//input[@data-autoid='AC_NAME_ctrl']"));
f1.sendKeys("Rahul");

data-autoid is custom attribute with value 'AC_NAME_ctrl'
Any help in this direction will be helpful.


问:
MySQL script to convert DateTime.Ticks values to SQL Date
I have an old MySQL database where I stored dates as C# DateTime.Ticks.

Now I want to convert that old database to a new structure for a PHP app that has needs a datefield. How do I convert DateTime.Ticks to MySQL dates?

I am looking for something in the following format YYYY-MM-DD HH:mm:ss:

```<code>SELECT someconversion(olddate) as newDate FROM table;
</code>```

Thank you so much in advance

答:
This was a pain for me, but what I did was to store datetime.ticks in DB as Bigint then...
Datetime MyDateTimeVar = new datetime(Convert.toint64(DB.ticks)); //This gets the datetime from ticks!

Body:
I have an old MySQL database where I stored dates as C# DateTime.Ticks.

Now I want to convert that old database to a new structure for a PHP app that has needs a datefield. How do I convert DateTime.Ticks to MySQL dates?

I am looking for something in the following format YYYY-MM-DD HH:mm:ss:

SELECT someconversion(olddate) as newDate FROM table;

Thank you so much in advance


问:
Insertion sort using vectors, not working
Im trying to create an insertion sort algorithm using vectors, but instead of parsing the elements from the start of the array (vector here), i tried doing it from the end. The code does nothing but sort the element for the first time, and delete the first element of my vector. I want to know what correction to my code can I make for this to work.
Basic procedure:

Start by element towards last (second last element)

Insert it in correct position in the 'sorted' subarray (vector) after it

Delete it from its initial position

Continue with algorithm, traversing backwards until vector's beginning

Code:

```<code>#include <iostream>
#include <vector>
using namespace std;

template <class T>
void isort(vector <T> &ar){
    //start from second last element upto first element
    for(auto i = ar.end()-2; i >= ar.begin(); i--){
        //iterator pointing towards element next to insertion element
        auto j = i + 1;
        //traverse and increase the pointer until condition met
        while(j != ar.end() && *i < *j) j++;
        //insert the insertion element at final position of the pointer
        ar.insert(j,*i);
        //erase the original element
        ar.erase(i);
    }
}
template <class T>
void display(vector <T> &ar){
    for(auto i = ar.begin(); i != ar.end(); i++){
        cout << *i << ' ';
    }
    cout << endl;
}
int main() {
    vector <int> X {6,1,7,1,3,2,6723,4,1,6};
    display <int>(X);
    isort <int>(X);
    display <int>(X);
}
</code>```

Expected output:

```<code>6 1 7 1 3 2 6723 4 1 6
1 1 1 2 3 4 6 6 7 6723
</code>```

Output attained:

```<code>6 1 7 1 3 2 6723 4 1 6
1 7 1 3 2 6723 4 1 6 1
</code>```

答:
About your way, so I modified a bit your code according to your solution, so it works now.
The performance might be even worse than swapping, just because vector shifts elements after insert/erase.</p>
```<code>#include <iostream>
#include <vector>
using namespace std;

template <class T>
void isort(vector <T>& ar) {
    if (ar.size() < 2)
        return;

    //start from second last element upto first element
    auto i = ar.end() - 2;
    do
    {
        //iterator pointing towards element next to insertion element
        auto j = i + 1;
        //traverse and increase the pointer until condition met
        while (j != ar.end() && *i > *j) ++j;
        //insert the insertion element at final position of the pointer

        if (*(j - 1) < *i && (j - 1) != i) {
            ar.insert(j, *i);
            i = ar.erase(i);
        }

        if (i == ar.begin())
            break;
        --i;
    } while (true);
}

template <class T>
void display(vector <T> &ar){
    for(auto i = ar.begin(); i != ar.end(); i++){
        cout << *i << ' ';
    }
    cout << endl;
}
int main() {
    vector <int> X {6,1,7,1,3,2,6723,4,6,1};
    X.reserve(X.size() * 2);
    display <int>(X);
    isort <int>(X);
    display <int>(X);
}
</code>```

Body:
Im trying to create an insertion sort algorithm using vectors, but instead of parsing the elements from the start of the array (vector here), i tried doing it from the end. The code does nothing but sort the element for the first time, and delete the first element of my vector. I want to know what correction to my code can I make for this to work.
Basic procedure:

Start by element towards last (second last element)

Insert it in correct position in the 'sorted' subarray (vector) after it

Delete it from its initial position

Continue with algorithm, traversing backwards until vector's beginning

Code:

#include <iostream>
#include <vector>
using namespace std;

template <class T>
void isort(vector <T> &ar){
    //start from second last element upto first element
    for(auto i = ar.end()-2; i >= ar.begin(); i--){
        //iterator pointing towards element next to insertion element
        auto j = i + 1;
        //traverse and increase the pointer until condition met
        while(j != ar.end() && *i < *j) j++;
        //insert the insertion element at final position of the pointer
        ar.insert(j,*i);
        //erase the original element
        ar.erase(i);
    }
}
template <class T>
void display(vector <T> &ar){
    for(auto i = ar.begin(); i != ar.end(); i++){
        cout << *i << ' ';
    }
    cout << endl;
}
int main() {
    vector <int> X {6,1,7,1,3,2,6723,4,1,6};
    display <int>(X);
    isort <int>(X);
    display <int>(X);
}

Expected output:

6 1 7 1 3 2 6723 4 1 6
1 1 1 2 3 4 6 6 7 6723

Output attained:

6 1 7 1 3 2 6723 4 1 6
1 7 1 3 2 6723 4 1 6 1

Body:
About your way, so I modified a bit your code according to your solution, so it works now.
The performance might be even worse than swapping, just because vector shifts elements after insert/erase.

#include <iostream>
#include <vector>
using namespace std;

template <class T>
void isort(vector <T>& ar) {
    if (ar.size() < 2)
        return;

    //start from second last element upto first element
    auto i = ar.end() - 2;
    do
    {
        //iterator pointing towards element next to insertion element
        auto j = i + 1;
        //traverse and increase the pointer until condition met
        while (j != ar.end() && *i > *j) ++j;
        //insert the insertion element at final position of the pointer

        if (*(j - 1) < *i && (j - 1) != i) {
            ar.insert(j, *i);
            i = ar.erase(i);
        }

        if (i == ar.begin())
            break;
        --i;
    } while (true);
}

template <class T>
void display(vector <T> &ar){
    for(auto i = ar.begin(); i != ar.end(); i++){
        cout << *i << ' ';
    }
    cout << endl;
}
int main() {
    vector <int> X {6,1,7,1,3,2,6723,4,6,1};
    X.reserve(X.size() * 2);
    display <int>(X);
    isort <int>(X);
    display <int>(X);
}


问:
Is there a way, to prevent from precision lossing from converting from RGB, to HSV then back to RGB?
I try to convert color from RGB, to HSV, then back to RHB by using UIColor.

However, I notice there is precision losing by doing so.

This only happen in some colors.

For instance

```<code>import UIKit

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
        self.init(
            red: CGFloat(red) / 255.0,
            green: CGFloat(green) / 255.0,
            blue: CGFloat(blue) / 255.0,
            alpha: a
        )
    }

    func red() -> Int {
        var r: CGFloat = 0.0
        getRed(&r, green: nil, blue: nil, alpha: nil)

        let red = Int(r*0xff) & 0xff

        return red
    }

    func green() -> Int {
        var g: CGFloat = 0.0
        getRed(nil, green: &g, blue: nil, alpha: nil)

        let green = Int(g*0xff) & 0xff

        return green
    }

    func blue() -> Int {
        var b: CGFloat = 0.0
        getRed(nil, green: nil, blue: &b, alpha: nil)

        let blue = Int(b*0xff) & 0xff

        return blue
    }

    func alpha() -> Int {
        var a: CGFloat = 0.0
        getRed(nil, green: nil, blue: nil, alpha: &a)

        let alpha = Int(a*0xff) & 0xff

        return alpha
    }
}

let color = UIColor(red: 18, green: 52, blue: 86)
print("red \(color.red())")
print("green \(color.green())")
print("blue \(color.blue())")
print("alpha \(color.alpha())\n")

var h: CGFloat = 0.0
var s: CGFloat = 0.0
var v: CGFloat = 0.0
var a: CGFloat = 0.0
color.getHue(&h, saturation: &s, brightness: &v, alpha: &a)
let newColor = UIColor(hue: h, saturation: s, brightness: v, alpha: a)

print("new red \(newColor.red())")
print("new green \(newColor.green())")
print("new blue \(newColor.blue())")
print("new alpha \(newColor.alpha())")
</code>```

I am getting output

```<code>red 18
green 52
blue 86
alpha 255

new red 17
new green 52
new blue 86
new alpha 255
</code>```

As you can see, instead of getting original color when converting back from HSV to RGB, we are losing precision in red component color.

May I know why is it so? How can I solve such precision losing issue? Thank you.

答:
Rounding errors can not be avoided when doing roundtrip color space conversions, since not all intermediate results can be represented exactly as a binary floating point number.

The problem is that with your Int -> CGFloat and CGFloat -> Int conversions, even a tiny error in the floating point value can result in an integer result which is different from the original.

In your example, the red component changes from 0.07058823529411765 to 0.07058823529411763, which is smaller by 0.00000000000000002. That is not much, but since you truncate in the conversion from floating point values to integers, the final result is one less than the original integer.

This can be demonstrated with a small stand-alone program:

```<code>let red = 18
var r = CGFloat(red) / 255.0
r -= 2.0E-17 // Simulate rounding error in the color calculations
let newRed = Int(r * 255)
print(newRed) // 17
</code>```

In order to get the original integer values even after small rounding errors in the floating point calculations, it is therefore better to round in the conversion, in your case

```<code>red = Int((r * 255).rounded())
</code>```

and similarly for the other color components.

Body:
I try to convert color from RGB, to HSV, then back to RHB by using UIColor.

However, I notice there is precision losing by doing so.

This only happen in some colors.

For instance

import UIKit

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
        self.init(
            red: CGFloat(red) / 255.0,
            green: CGFloat(green) / 255.0,
            blue: CGFloat(blue) / 255.0,
            alpha: a
        )
    }

    func red() -> Int {
        var r: CGFloat = 0.0
        getRed(&r, green: nil, blue: nil, alpha: nil)

        let red = Int(r*0xff) & 0xff

        return red
    }

    func green() -> Int {
        var g: CGFloat = 0.0
        getRed(nil, green: &g, blue: nil, alpha: nil)

        let green = Int(g*0xff) & 0xff

        return green
    }

    func blue() -> Int {
        var b: CGFloat = 0.0
        getRed(nil, green: nil, blue: &b, alpha: nil)

        let blue = Int(b*0xff) & 0xff

        return blue
    }

    func alpha() -> Int {
        var a: CGFloat = 0.0
        getRed(nil, green: nil, blue: nil, alpha: &a)

        let alpha = Int(a*0xff) & 0xff

        return alpha
    }
}

let color = UIColor(red: 18, green: 52, blue: 86)
print("red \(color.red())")
print("green \(color.green())")
print("blue \(color.blue())")
print("alpha \(color.alpha())\n")

var h: CGFloat = 0.0
var s: CGFloat = 0.0
var v: CGFloat = 0.0
var a: CGFloat = 0.0
color.getHue(&h, saturation: &s, brightness: &v, alpha: &a)
let newColor = UIColor(hue: h, saturation: s, brightness: v, alpha: a)

print("new red \(newColor.red())")
print("new green \(newColor.green())")
print("new blue \(newColor.blue())")
print("new alpha \(newColor.alpha())")

I am getting output

red 18
green 52
blue 86
alpha 255

new red 17
new green 52
new blue 86
new alpha 255

As you can see, instead of getting original color when converting back from HSV to RGB, we are losing precision in red component color.

May I know why is it so? How can I solve such precision losing issue? Thank you.

Body:
Rounding errors can not be avoided when doing roundtrip color space conversions, since not all intermediate results can be represented exactly as a binary floating point number.

The problem is that with your Int -> CGFloat and CGFloat -> Int conversions, even a tiny error in the floating point value can result in an integer result which is different from the original.

In your example, the red component changes from 0.07058823529411765 to 0.07058823529411763, which is smaller by 0.00000000000000002. That is not much, but since you truncate in the conversion from floating point values to integers, the final result is one less than the original integer.

This can be demonstrated with a small stand-alone program:

let red = 18
var r = CGFloat(red) / 255.0
r -= 2.0E-17 // Simulate rounding error in the color calculations
let newRed = Int(r * 255)
print(newRed) // 17

In order to get the original integer values even after small rounding errors in the floating point calculations, it is therefore better to round in the conversion, in your case

red = Int((r * 255).rounded())

and similarly for the other color components.


问:
Losing the crs when writing to .gpkg with geopandas
When I write my .gpkg I am losing the CRS. I have tried setting the CRS with .set_crs, or adding the CRS when writing the .gpkg (which creates a fault -  "fiona._env - WARNING - dataset filename.gpkg does not support layer creation option EPSG"

My code

```<code>for layername in fiona.listlayers(file):
    vector = geopandas.read_file(file, layer=layername)
    vector.set_crs(4326)
    vector.to_file(filename + ".gpkg", layer = layername, driver='GPKG')
</code>```

or

```<code>for layername in fiona.listlayers(file):
    vector = geopandas.read_file(file, layer=layername)
    vector.to_file(filename + ".gpkg", layer = layername, driver='GPKG', epsg=4326)
</code>```

neither works.

答:
vector.set_crs(4326) does not work in place by default. You either need to assign it or specify inplace=True.

for layername in fiona.listlayers(file):
    vector = geopandas.read_file(file, layer=layername)
    # vector.set_crs(4326, inplace=True)  # one option
    vector = vector.set_crs(4326)  # other option
    vector.to_file(filename + ".gpkg", layer = layername, driver='GPKG')
```

Your second attempt does not work because to_file does not have espg keyword you are trying to lose and that gets lost among arguments passed to Fiona and GDAL (which silently ignores it).

Body:
When I write my .gpkg I am losing the CRS. I have tried setting the CRS with .set_crs, or adding the CRS when writing the .gpkg (which creates a fault -  "fiona._env - WARNING - dataset filename.gpkg does not support layer creation option EPSG"

My code

for layername in fiona.listlayers(file):
    vector = geopandas.read_file(file, layer=layername)
    vector.set_crs(4326)
    vector.to_file(filename + ".gpkg", layer = layername, driver='GPKG')

or

for layername in fiona.listlayers(file):
    vector = geopandas.read_file(file, layer=layername)
    vector.to_file(filename + ".gpkg", layer = layername, driver='GPKG', epsg=4326)

neither works.

Body:
vector.set_crs(4326) does not work in place by default. You either need to assign it or specify inplace=True.

for layername in fiona.listlayers(file):
    vector = geopandas.read_file(file, layer=layername)
    # vector.set_crs(4326, inplace=True)  # one option
    vector = vector.set_crs(4326)  # other option
    vector.to_file(filename + ".gpkg", layer = layername, driver='GPKG')

Your second attempt does not work because to_file does not have espg keyword you are trying to lose and that gets lost among arguments passed to Fiona and GDAL (which silently ignores it).


问:
Default constructor parameters in pyyaml
I haven't been able to find out how to do this in the PyYAML documentation. I want to represent python classes I've defined in YAML, and have a default value given to a parameter in the constructor if it's not specified in the YAML. For example:

```<code>>>> class Test(yaml.YAMLObject):
...     yaml_tag = u"!Test"
...     def __init__(self, foo, bar=3):
...             self.foo = foo
...             self.bar = bar
...     def __repr__(self):
...             return "%s(foo=%r, bar=%r)" % (self.__class__.__name__, self.foo, self.bar)
...
>>> yaml.load("""
... --- !Test
... foo: 5
... """)
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "<stdin>", line 7, in __repr__
AttributeError: 'Test' object has no attribute 'bar'
</code>```

I expected that it would create a Test object with bar=3, but I guess it bypasses my constructor when it creates the object. If I include a mapping for bar in the YAML, everything works as expected:

```<code>>>> yaml.load("""
... --- !Test
... foo: 5
... bar: 42
... """)
Test(foo=5, bar=42)
</code>```

Does anyone know how I can have it use a default value?

答:
The answers above work well, but here is a way to make initialisation work fully with a class based approach:

UNSPECIFIED = object()

class SomeYAMLObject(yaml.YAMLObject):
    @classmethod
    def from_yaml(cls, loader, node):
        arg_spec = inspect.getfullargspec(cls.__init__)
        arg_spec.args.remove("self")

        arg_defaults = reversed(list(
                zip_longest(
                    reversed(arg_spec.args),
                    reversed(arg_spec.defaults or []),
                    fillvalue=UNSPECIFIED)))

        kwarg_defaults = reversed(list(
                    zip_longest(
                        reversed(arg_spec.kwonlyargs),
                        reversed(arg_spec.kwonlydefaults or []),
                        fillvalue=UNSPECIFIED)))

        node_mapping = loader.construct_mapping(node)
        used_nodes = set()

        # fill args first
        args = []
        for a,d in arg_defaults:
            if a in node_mapping:
                args.append(node_mapping[a])
                used_nodes.add(a)
            elif d is not UNSPECIFIED:
                args.append(d)
            else:
                raise Exception(f"Tag {cls.yaml_tag} is missing '{a}' argument")

        # then kwargs
        kwargs = {}
        for a,d in kwarg_defaults:
            if a in node_mapping:
                kwargs[a] = node_mapping[a]
                used_nodes.add(a)
            elif d is not UNSPECIFIED:
                args[a] = d

        # if it accepts additional kwargs, fill with leftover kwargs
        if arg_spec.varkw and len(used_nodes) != len(node_mapping):
            for k,v in node_mapping:
                if k not in used_nodes:
                    kwargs[k] = v

        return cls(*args,**kwargs)
```

It's a bit lengthy, but gives a nice error if required positional arguments without a default value are missing.

Body:
I haven't been able to find out how to do this in the PyYAML documentation. I want to represent python classes I've defined in YAML, and have a default value given to a parameter in the constructor if it's not specified in the YAML. For example:

>>> class Test(yaml.YAMLObject):
...     yaml_tag = u"!Test"
...     def __init__(self, foo, bar=3):
...             self.foo = foo
...             self.bar = bar
...     def __repr__(self):
...             return "%s(foo=%r, bar=%r)" % (self.__class__.__name__, self.foo, self.bar)
...
>>> yaml.load("""
... --- !Test
... foo: 5
... """)
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "<stdin>", line 7, in __repr__
AttributeError: 'Test' object has no attribute 'bar'

I expected that it would create a Test object with bar=3, but I guess it bypasses my constructor when it creates the object. If I include a mapping for bar in the YAML, everything works as expected:

>>> yaml.load("""
... --- !Test
... foo: 5
... bar: 42
... """)
Test(foo=5, bar=42)

Does anyone know how I can have it use a default value?

Body:
The answers above work well, but here is a way to make initialisation work fully with a class based approach:

UNSPECIFIED = object()

class SomeYAMLObject(yaml.YAMLObject):
    @classmethod
    def from_yaml(cls, loader, node):
        arg_spec = inspect.getfullargspec(cls.__init__)
        arg_spec.args.remove("self")

        arg_defaults = reversed(list(
                zip_longest(
                    reversed(arg_spec.args),
                    reversed(arg_spec.defaults or []),
                    fillvalue=UNSPECIFIED)))

        kwarg_defaults = reversed(list(
                    zip_longest(
                        reversed(arg_spec.kwonlyargs),
                        reversed(arg_spec.kwonlydefaults or []),
                        fillvalue=UNSPECIFIED)))

        node_mapping = loader.construct_mapping(node)
        used_nodes = set()

        # fill args first
        args = []
        for a,d in arg_defaults:
            if a in node_mapping:
                args.append(node_mapping[a])
                used_nodes.add(a)
            elif d is not UNSPECIFIED:
                args.append(d)
            else:
                raise Exception(f"Tag {cls.yaml_tag} is missing '{a}' argument")

        # then kwargs
        kwargs = {}
        for a,d in kwarg_defaults:
            if a in node_mapping:
                kwargs[a] = node_mapping[a]
                used_nodes.add(a)
            elif d is not UNSPECIFIED:
                args[a] = d

        # if it accepts additional kwargs, fill with leftover kwargs
        if arg_spec.varkw and len(used_nodes) != len(node_mapping):
            for k,v in node_mapping:
                if k not in used_nodes:
                    kwargs[k] = v

        return cls(*args,**kwargs)

It's a bit lengthy, but gives a nice error if required positional arguments without a default value are missing.


问:
How to configure OAuth Code flow wihout discovery
It is my first try with OAuth. I am using Angular 13 + angular-oauth2-oidc library and I am trying to configure code flow. My problem is that in tutorial discovery document is used by default but my auth server does not have anything like that so when in the beggining app asking about identity_provider_url/.well-known/openid-configuration I am getting an 404 error. Question is how to configure code flow without loading discovery document from auth server?
I found only configuration without discovery document for implicit flow.
That is how my code looks like right now:

auth.config.ts

```<code>import { AuthConfig } from 'angular-oauth2-oidc';

export const authCodeFlowConfig: AuthConfig = {
  // Url of the Identity Provider
  issuer: '**************', // identity provider URL,
  redirectUri: window.location.origin + '/index.html',
  clientId: 'spa',
  dummyClientSecret: 'secret',
  responseType: 'code',
  scope: 'read, write',
  showDebugInformation: true,
};
</code>```

app.component.ts

```<code>import {Component} from '@angular/core';
import {authCodeFlowConfig} from './sso.confiig';
import {OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'sso';

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.configure(authCodeFlowConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin(); // I don`t want this
  }
}
</code>```

login.component.ts

```<code>import {Component, OnInit} from '@angular/core';
import {OAuthErrorEvent, OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.events.subscribe(e => (e instanceof OAuthErrorEvent) ? console.error(e) : console.warn(e));
  }

  public async login(): Promise<void> {
    await this.oAuthService.initCodeFlow();
  }

  public logout(): void {
    this.oAuthService.logOut();
  }

  public get userName() {
    let claims = this.oAuthService.getIdentityClaims();
    if (!claims) return null;
    return claims;
  }
}
</code>```

答:
Have a look at the AuthConfig class and try setting loginUrl to the authorize endpoint and also set the token endpoint explicitly. See if this gives you a different error.

A good library should allow you to set endpoints explicitly. As an example, a couple of years ago an SPA of mine did not work with Azure AD since it did not allow CORS requests to the token endpoint. I worked around this by setting a token endpoint in the oidc client library to point to an API, so that I could call the token endpoint from there.

Body:
It is my first try with OAuth. I am using Angular 13 + angular-oauth2-oidc library and I am trying to configure code flow. My problem is that in tutorial discovery document is used by default but my auth server does not have anything like that so when in the beggining app asking about identity_provider_url/.well-known/openid-configuration I am getting an 404 error. Question is how to configure code flow without loading discovery document from auth server?
I found only configuration without discovery document for implicit flow.
That is how my code looks like right now:

auth.config.ts

import { AuthConfig } from 'angular-oauth2-oidc';

export const authCodeFlowConfig: AuthConfig = {
  // Url of the Identity Provider
  issuer: '**************', // identity provider URL,
  redirectUri: window.location.origin + '/index.html',
  clientId: 'spa',
  dummyClientSecret: 'secret',
  responseType: 'code',
  scope: 'read, write',
  showDebugInformation: true,
};

app.component.ts

import {Component} from '@angular/core';
import {authCodeFlowConfig} from './sso.confiig';
import {OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'sso';

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.configure(authCodeFlowConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin(); // I don`t want this
  }
}

login.component.ts

import {Component, OnInit} from '@angular/core';
import {OAuthErrorEvent, OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.events.subscribe(e => (e instanceof OAuthErrorEvent) ? console.error(e) : console.warn(e));
  }

  public async login(): Promise<void> {
    await this.oAuthService.initCodeFlow();
  }

  public logout(): void {
    this.oAuthService.logOut();
  }

  public get userName() {
    let claims = this.oAuthService.getIdentityClaims();
    if (!claims) return null;
    return claims;
  }
}


问:
Understanding Glubort() handling of logical vector vs character vector in creating confidence interval
I'm using a custom styling function to cap odds ratios and confidence intervals if they are below or above a certain number for ease of printing in a final table. All of the variables in my dataset work except for one, which is not unique in it's composition, as far as I can tell.

library(tidyverse)
library(gtsummary)

bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {
    dplyr::case_when(
        x < min ~ paste0("<", gtsummary::style_ratio(min, ...)),
        x > max ~ paste0(">", gtsummary::style_ratio(max, ...)),
        is.na(x) == TRUE ~ NA_character_,
        TRUE ~ gtsummary::style_ratio(x, ...)
    )
}
dat_2 <- structure(list(con = structure(c(1L, 1L, 1L, 2L, 1L, 2L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L,
                                          1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
                                          1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L,
                                          1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L,
                                          1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L,
                                          1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L,
                                          1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L,
                                          1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
                                          2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L,
                                          1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
                                          2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
                                          2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
                                          1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
                                          2L, 1L, 1L), .Label = c("0", "1"), class = "factor"), education_c = structure(c(2L,
                                                                                5L, 5L, 3L, 4L, 4L, 4L, 2L, 3L, 5L, 3L, 3L, 4L, 3L, 4L, 4L, 3L,
                                                                                4L, 2L, 5L, 4L, 3L, 3L, 5L, 5L, 4L, 3L, 2L, 1L, 5L, 5L, 5L, 2L,
                                                                                2L, 4L, 4L, 5L, 3L, 5L, 3L, 4L, 5L, 5L, 3L, 5L, 3L, 4L, 3L, 5L,
                                                                                5L, 5L, 4L, 3L, 5L, 5L, 4L, 2L, 5L, 3L, 4L, 3L, 4L, 4L, 5L, 4L,
                                                                                5L, 3L, 4L, 3L, 5L, 5L, 4L, 2L, 5L, 4L, 2L, 5L, 5L, 4L, 3L, 4L,
                                                                                4L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 3L, 3L, 5L, 4L, 2L, 2L, 5L, 4L,
                                                                                5L, 4L, 3L, 5L, 4L, 2L, 4L, 3L, 4L, 5L, 4L, 2L, 3L, 5L, 5L, 2L,
                                                                                5L, 3L, 4L, 3L, 4L, 3L, 2L, 4L, 2L, 5L, 3L, 5L, 5L, 3L, 5L, 5L,
                                                                                5L, 3L, 3L, 3L, 5L, 5L, 3L, 4L, 3L, 4L, 3L, 3L, 4L, 5L, 3L, 2L,
                                                                                5L, 2L, 3L, 3L, 4L, 5L, 5L, 4L, 4L, 3L, 4L, 4L, 5L, 4L, 4L, 5L,
                                                                                3L, 5L, 4L, 4L, 5L, 4L, 3L, 5L, 2L, 5L, 4L, 5L, 4L, 4L, 4L, 4L,
                                                                                3L, 4L, 5L, 3L, 4L, 5L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 4L, 4L, 4L,
                                                                                3L, 4L, 5L, 5L, 4L, 4L, 4L, 4L, 5L, 4L, 3L, 2L, 3L, 4L, 5L, 4L,
                                                                                5L, 4L, 3L, 5L, 4L, 4L, 2L, 4L, 5L, 4L, 3L, 4L, 5L, 3L, 4L, 4L,
                                                                                2L, 5L, 5L, 3L, 2L, 4L, 5L, 4L, 5L, 5L, 5L, 4L, 3L, 5L, 5L, 4L,
                                                                                4L, 3L, 4L, 4L, 5L, 5L, 3L, 4L, 5L, 2L, 4L, 4L, 5L, 4L, 5L, 5L,
                                                                                4L, 3L, 4L, 2L, 3L, 3L, 2L, 4L, 5L, 3L, 4L, 4L, 3L, 2L, 3L, 3L,
                                                                                5L, 4L, 5L, 2L, 2L, 4L, 5L, 3L, 4L, 2L, 5L, 3L, 5L, 3L, 4L, 4L,
                                                                                3L, 2L, 3L, 4L, 2L, 5L, 3L, 3L, 3L, 3L, 5L, 3L, 5L, 3L, 5L, 5L,
                                                                                5L, 4L, 3L, 5L, 3L, 2L, 4L, 4L, 1L, 4L, 2L, 3L, 3L, 3L, 5L, 4L,
                                                                                5L, 2L, 5L, 4L, 3L, 4L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 3L, 4L,
                                                                                4L, 5L, 5L, 4L, 3L, 4L, 4L, 3L, 2L), .Label = c("LTHS", "HS",
                                                                                "LTBA", "BA", "PostBA"), class = "factor")), row.names = c(NA,
                                                                                -346L), class = c("tbl_df", "tbl", "data.frame"))
dat_2 %>%
    tbl_uvregression(
        y = con,
        method = glm,
        method.args = list(family = binomial),
        exponentiate = TRUE,
        estimate_fun = purrr::partial(bounded_style_ratio, max = 2)
    )
#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
#> Warning in regularize.values(x, y, ties, missing(ties), na.rm = na.rm):
#> collapsing to unique 'x' values
#> Error in `mutate_cols()`:
#> ! Problem with `mutate()` column `ci`.
#> i `ci = if_else(...)`.
#> x must be a character vector, not a logical vector.
#> Caused by error in `glubort()`:
#> ! must be a character vector, not a logical vector.
```

Created on 2022-02-10 by the reprex package (v2.0.1)

I understand the warnings around data fitting, and will likely discard this predictor downstream in data analysis, but I don't understand what's happening with the error in mutate_cols() section. Does anyone have insight into how I could update my formatting call to handle this error?

答:
The upper bound of confidence intervals are all NA in this example, and the custom function you've defined doesn't handle NA values. You'll need to update it to handle NA values, and it should work

bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {
  dplyr::case_when(
    x < min ~ paste0("<", gtsummary::style_ratio(min, ...)),
    x > max ~ paste0(">", gtsummary::style_ratio(max, ...)),
    is.na(x) == TRUE ~ NA_character_,
    TRUE ~ gtsummary::style_ratio(x, ...)
  )
}

bounded_style_ratio(c(NA, NA))
#> Error in `glubort()`:
#> ! must be a character vector, not a logical vector.
```
<p><sup>Created on 2022-02-10 by the reprex package (v2.0.1)</sup></p>
<p>Something like this should work:</p>
<pre class="lang-r prettyprint-override"><code>bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {
  purrr::map_chr(
    x,
    function(x) {
      if (isTRUE(x < min)) return(paste0("<", gtsummary::style_ratio(min, ...)))
      if (isTRUE(x > max)) return(paste0(">", gtsummary::style_ratio(max, ...)))
      gtsummary::style_ratio(x, ...)
    }
  )
}
</code>```

Body:
I'm using a custom styling function to cap odds ratios and confidence intervals if they are below or above a certain number for ease of printing in a final table. All of the variables in my dataset work except for one, which is not unique in it's composition, as far as I can tell.

library(tidyverse)
library(gtsummary)

bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {
    dplyr::case_when(
        x < min ~ paste0("<", gtsummary::style_ratio(min, ...)),
        x > max ~ paste0(">", gtsummary::style_ratio(max, ...)),
        is.na(x) == TRUE ~ NA_character_,
        TRUE ~ gtsummary::style_ratio(x, ...)
    )
}
dat_2 <- structure(list(con = structure(c(1L, 1L, 1L, 2L, 1L, 2L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L,
                                          1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
                                          1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L,
                                          1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L,
                                          1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L,
                                          1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L,
                                          1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L,
                                          1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
                                          2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L,
                                          1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
                                          2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
                                          2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
                                          1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
                                          1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
                                          2L, 1L, 1L), .Label = c("0", "1"), class = "factor"), education_c = structure(c(2L,
                                                                                5L, 5L, 3L, 4L, 4L, 4L, 2L, 3L, 5L, 3L, 3L, 4L, 3L, 4L, 4L, 3L,
                                                                                4L, 2L, 5L, 4L, 3L, 3L, 5L, 5L, 4L, 3L, 2L, 1L, 5L, 5L, 5L, 2L,
                                                                                2L, 4L, 4L, 5L, 3L, 5L, 3L, 4L, 5L, 5L, 3L, 5L, 3L, 4L, 3L, 5L,
                                                                                5L, 5L, 4L, 3L, 5L, 5L, 4L, 2L, 5L, 3L, 4L, 3L, 4L, 4L, 5L, 4L,
                                                                                5L, 3L, 4L, 3L, 5L, 5L, 4L, 2L, 5L, 4L, 2L, 5L, 5L, 4L, 3L, 4L,
                                                                                4L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 3L, 3L, 5L, 4L, 2L, 2L, 5L, 4L,
                                                                                5L, 4L, 3L, 5L, 4L, 2L, 4L, 3L, 4L, 5L, 4L, 2L, 3L, 5L, 5L, 2L,
                                                                                5L, 3L, 4L, 3L, 4L, 3L, 2L, 4L, 2L, 5L, 3L, 5L, 5L, 3L, 5L, 5L,
                                                                                5L, 3L, 3L, 3L, 5L, 5L, 3L, 4L, 3L, 4L, 3L, 3L, 4L, 5L, 3L, 2L,
                                                                                5L, 2L, 3L, 3L, 4L, 5L, 5L, 4L, 4L, 3L, 4L, 4L, 5L, 4L, 4L, 5L,
                                                                                3L, 5L, 4L, 4L, 5L, 4L, 3L, 5L, 2L, 5L, 4L, 5L, 4L, 4L, 4L, 4L,
                                                                                3L, 4L, 5L, 3L, 4L, 5L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 4L, 4L, 4L,
                                                                                3L, 4L, 5L, 5L, 4L, 4L, 4L, 4L, 5L, 4L, 3L, 2L, 3L, 4L, 5L, 4L,
                                                                                5L, 4L, 3L, 5L, 4L, 4L, 2L, 4L, 5L, 4L, 3L, 4L, 5L, 3L, 4L, 4L,
                                                                                2L, 5L, 5L, 3L, 2L, 4L, 5L, 4L, 5L, 5L, 5L, 4L, 3L, 5L, 5L, 4L,
                                                                                4L, 3L, 4L, 4L, 5L, 5L, 3L, 4L, 5L, 2L, 4L, 4L, 5L, 4L, 5L, 5L,
                                                                                4L, 3L, 4L, 2L, 3L, 3L, 2L, 4L, 5L, 3L, 4L, 4L, 3L, 2L, 3L, 3L,
                                                                                5L, 4L, 5L, 2L, 2L, 4L, 5L, 3L, 4L, 2L, 5L, 3L, 5L, 3L, 4L, 4L,
                                                                                3L, 2L, 3L, 4L, 2L, 5L, 3L, 3L, 3L, 3L, 5L, 3L, 5L, 3L, 5L, 5L,
                                                                                5L, 4L, 3L, 5L, 3L, 2L, 4L, 4L, 1L, 4L, 2L, 3L, 3L, 3L, 5L, 4L,
                                                                                5L, 2L, 5L, 4L, 3L, 4L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 3L, 4L,
                                                                                4L, 5L, 5L, 4L, 3L, 4L, 4L, 3L, 2L), .Label = c("LTHS", "HS",
                                                                                "LTBA", "BA", "PostBA"), class = "factor")), row.names = c(NA,
                                                                                -346L), class = c("tbl_df", "tbl", "data.frame"))
dat_2 %>%
    tbl_uvregression(
        y = con,
        method = glm,
        method.args = list(family = binomial),
        exponentiate = TRUE,
        estimate_fun = purrr::partial(bounded_style_ratio, max = 2)
    )
#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred

#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
#> Warning in regularize.values(x, y, ties, missing(ties), na.rm = na.rm):
#> collapsing to unique 'x' values
#> Error in `mutate_cols()`:
#> ! Problem with `mutate()` column `ci`.
#> i `ci = if_else(...)`.
#> x must be a character vector, not a logical vector.
#> Caused by error in `glubort()`:
#> ! must be a character vector, not a logical vector.

Created on 2022-02-10 by the reprex package (v2.0.1)

I understand the warnings around data fitting, and will likely discard this predictor downstream in data analysis, but I don't understand what's happening with the error in mutate_cols() section. Does anyone have insight into how I could update my formatting call to handle this error?

Body:
The upper bound of confidence intervals are all NA in this example, and the custom function you've defined doesn't handle NA values. You'll need to update it to handle NA values, and it should work

bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {
  dplyr::case_when(
    x < min ~ paste0("<", gtsummary::style_ratio(min, ...)),
    x > max ~ paste0(">", gtsummary::style_ratio(max, ...)),
    is.na(x) == TRUE ~ NA_character_,
    TRUE ~ gtsummary::style_ratio(x, ...)
  )
}

bounded_style_ratio(c(NA, NA))
#> Error in `glubort()`:
#> ! must be a character vector, not a logical vector.

Created on 2022-02-10 by the reprex package (v2.0.1)

Something like this should work:

bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {
  purrr::map_chr(
    x,
    function(x) {
      if (isTRUE(x < min)) return(paste0("<", gtsummary::style_ratio(min, ...)))
      if (isTRUE(x > max)) return(paste0(">", gtsummary::style_ratio(max, ...)))
      gtsummary::style_ratio(x, ...)
    }
  )
}


问:
2 TypeError: Cannot read properties of undefined (reading 'value') in reactjs with event handler
What's the issue with my code ?

I've gotten two - TypeError: Cannot read properties of undefined (reading 'value')

expected behavior = click one button, the button uses class name red and calls function addValue if I click this button again it should call function removeValue and its color should change to white.

Instead I get this type error and every button is highlighted in red.

```<code>const [color, setColor] = useState(false)

function addValue(e) {
> 38 |     if (e.target.value !== "") {

  function removeValue(e, value) {
> 63 |   if (e.target.value !== "") {
</code>```

These are the functions

```<code>function addValue(e) {
    if (e.target.value !== "") {

      if (!favs.includes(e.target.value)) {
        favs.push(e.target.value);
        localStorage.setItem("name", JSON.stringify(favs));
        console.log(favs);
        document.getElementById("favsarray").innerHTML =  favs
      }
    }
  }

function removeValue(e, value) {
    if (e.target.value !== "") {
      //delete from array
      favs.pop(e.target.value);
      console.log(favs);
      //change the div text
      document.getElementById("favsarray").innerHTML = favs;
      //get the values from localstorage- parse
      const stored = JSON.parse(localStorage.getItem("name"));
      //delete the value
      delete stored[(value, e.target.value)];
      //store the new array as a string
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(stored);
    }
  }
</code>```

I am calling this function with this and an event handler

```<code>function addOrRemove(e) {
  const elem = e.currentTarget;
  setColor(!color)
if (color){
  addValue(elem)
} else {
  removeValue(elem)
}
}

<button
                id="btn"
                onClick={addOrRemove}
                className={color? "white": "red"}
                value={"Name:  " + d.name + "  Description:   " + d.description + "  Stars: " + d.stargazers_count + "  URL:   " + d.html_url}

</code>```

答:
you just need to replace e.target.value in the two offending places with e.value.

This is because e is the argument to the function, which you're calling like this:

```<code>addValue(elem);
</code>```

after

```<code>const elem = e.currentTarget;
</code>```

where e is the argument to your event handler function. So elem is the DOM element that the event handler is currently firing on, therefore this is what e is inside the function. And DOM elements don't have a target property, but - if they're a button or input - they do have a value property.

It would also be clearer if you call the argument something like elem (which you use when you make the call) or element (in full) rather than e, which by convention is used for an event object, and may be what is confusing you here.

Body:
What's the issue with my code ?

I've gotten two - TypeError: Cannot read properties of undefined (reading 'value')

expected behavior = click one button, the button uses class name red and calls function addValue if I click this button again it should call function removeValue and its color should change to white.

Instead I get this type error and every button is highlighted in red.

const [color, setColor] = useState(false)

function addValue(e) {
> 38 |     if (e.target.value !== "") {

  function removeValue(e, value) {
> 63 |   if (e.target.value !== "") {

These are the functions

function addValue(e) {
    if (e.target.value !== "") {

      if (!favs.includes(e.target.value)) {
        favs.push(e.target.value);
        localStorage.setItem("name", JSON.stringify(favs));
        console.log(favs);
        document.getElementById("favsarray").innerHTML =  favs
      }
    }
  }

function removeValue(e, value) {
    if (e.target.value !== "") {
      //delete from array
      favs.pop(e.target.value);
      console.log(favs);
      //change the div text
      document.getElementById("favsarray").innerHTML = favs;
      //get the values from localstorage- parse
      const stored = JSON.parse(localStorage.getItem("name"));
      //delete the value
      delete stored[(value, e.target.value)];
      //store the new array as a string
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(stored);
    }
  }

I am calling this function with this and an event handler

function addOrRemove(e) {
  const elem = e.currentTarget;
  setColor(!color)
if (color){
  addValue(elem)
} else {
  removeValue(elem)
}
}

<button
                id="btn"
                onClick={addOrRemove}
                className={color? "white": "red"}
                value={"Name:  " + d.name + "  Description:   " + d.description + "  Stars: " + d.stargazers_count + "  URL:   " + d.html_url}

Body:
you just need to replace e.target.value in the two offending places with e.value.

This is because e is the argument to the function, which you're calling like this:

addValue(elem);

after

const elem = e.currentTarget;

where e is the argument to your event handler function. So elem is the DOM element that the event handler is currently firing on, therefore this is what e is inside the function. And DOM elements don't have a target property, but - if they're a button or input - they do have a value property.

It would also be clearer if you call the argument something like elem (which you use when you make the call) or element (in full) rather than e, which by convention is used for an event object, and may be what is confusing you here.


问:
C# Permutation of an array of arraylists?
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

```<code>myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
</code>```

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

```<code>1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
</code>```

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

答:
Recursive solution

```<code>    static List<string> foo(int a, List<Array> x)
    {
        List<string> retval= new List<string>();
        if (a == x.Count)
        {
            retval.Add("");
            return retval;
        }
        foreach (Object y in x[a])
        {
            foreach (string x2 in foo(a + 1, x))
            {
                retval.Add(y.ToString() + " " + x2.ToString());
            }

        }
        return retval;
    }
    static void Main(string[] args)
    {
        List<Array> myList = new List<Array>();
        myList.Add(new string[0]);
        myList.Add(new string[0]);
        myList.Add(new string[0]);
        myList[0] = new string[]{ "1", "5", "3", "9" };
        myList[1] = new string[] { "2", "3" };
        myList[2] = new string[] { "93" };
        foreach (string x in foo(0, myList))
        {
            Console.WriteLine(x);
        }

        Console.ReadKey();
    }
</code>```

Note that it would be pretty easy to return a list or array instead of a string by changing the return to be a list of lists of strings and changing the retval.add call to work with a list instead of using concatenation.

How it works:

This is a classic recursive algorithm.  The base case is foo(myList.Count, myList), which returns a List containing one element, the empty string.  The permutation of a list of n string arrays s1, s2, ..., sN is equal to every member of sA1 prefixed to the permutation of n-1 string arrays, s2, ..., sN.  The base case is just there to provide something for each element of sN to be concatenated to.

OwnerDisplayName: TaRDy

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Body:
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

Body:
Recursive solution

    static List<string> foo(int a, List<Array> x)
    {
        List<string> retval= new List<string>();
        if (a == x.Count)
        {
            retval.Add("");
            return retval;
        }
        foreach (Object y in x[a])
        {
            foreach (string x2 in foo(a + 1, x))
            {
                retval.Add(y.ToString() + " " + x2.ToString());
            }

        }
        return retval;
    }
    static void Main(string[] args)
    {
        List<Array> myList = new List<Array>();
        myList.Add(new string[0]);
        myList.Add(new string[0]);
        myList.Add(new string[0]);
        myList[0] = new string[]{ "1", "5", "3", "9" };
        myList[1] = new string[] { "2", "3" };
        myList[2] = new string[] { "93" };
        foreach (string x in foo(0, myList))
        {
            Console.WriteLine(x);
        }

        Console.ReadKey();
    }

Note that it would be pretty easy to return a list or array instead of a string by changing the return to be a list of lists of strings and changing the retval.add call to work with a list instead of using concatenation.

How it works:

This is a classic recursive algorithm.  The base case is foo(myList.Count, myList), which returns a List containing one element, the empty string.  The permutation of a list of n string arrays s1, s2, ..., sN is equal to every member of sA1 prefixed to the permutation of n-1 string arrays, s2, ..., sN.  The base case is just there to provide something for each element of sN to be concatenated to.

OwnerDisplayName: Brian

LastEditorDisplayName: Brian


问:
Problem with handling path length
I'm creating library which will be used for file manipulations, both on linux and windows. So I need to handle paths, the main requirements is that my functions will recieve strings in UTF8 format. But it causes some problems, one of them is I'm using MAX_PATH on windows and PATH_MAX in linux, to represent static path variables. In the case of ASCII characters there will be no problem, but when path contains unicode characters, the length of path will be twice shorter if unicode char requires 2 bytes per char, 3 times shorter if unicode char requires 3 bytes per char and so on. So is there good solution for this problem?

Thanks in advance!

p.s. sorry for my english.

答:
At least on Linux, your concern seems misplaced. Linux (and POSIX in general) treats paths as an opaque blob of bytes terminated by "\0". It does not concern itself with how those bytes are translated to characters. That is, PATH_MAX specifies the max length of a path name in bytes, not in characters.

So if the path names contains >= 0 multibyte UTF-8 characters, then it just means that the max path length in characters is <= PATH_MAX.

Title: Problem with handling path length


问:
Azure SDK - Add/Remove Virtual Network from App Service
We have a need to Add or Remove Web Apps from Virtual Neworks.
We have the virtual network already setup, so we created an app to create subnets and then allocate the Web App to the VN using that subnet.

I have the following SDK's consumed in our C# project:

```<code>    <PackageReference Include="Microsoft.Azure.Management.AppService.Fluent" Version="1.38.0" />
    <PackageReference Include="Microsoft.Azure.Management.Fluent" Version="1.38.0" />
    <PackageReference Include="Microsoft.Azure.Management.Network.Fluent" Version="1.38.0" />
    <PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.6.2" />
</code>```

I have tried to find a way to update the network settings for my Web App, but cannot seem to find an Update that works with it?

In the code below I have added a comment on the bit I don't know how to do.

var networks = azure.Networks.List().ToList();
var mainVN = networks.Find(n => n.Key == "MainVn");
webApp = azure.WebApps.Find(w => w.Name == "PrimaryApp")
var cidr = $"10.0.1.0/24";
string subNetName = webApp.Name + "-subnet";
await mainVN.Update().WithSubnet(subNetName, cidr).ApplyAsync();
webApp.Update() // <----- how do I do this bit? To add the subnet/VN to the app service?
```

答:
```<code>    // DELETE
    await azure.WebApps.Manager.Inner.WebApps.DeleteSwiftVirtualNetworkAsync("rg", "webapp");

    // ADD
    await azure.WebApps.Manager.Inner.WebApps.CreateOrUpdateSwiftVirtualNetworkConnectionAsync("rg", "webapp",
        new Microsoft.Azure.Management.AppService.Fluent.Models.SwiftVirtualNetworkInner {
    });
</code>```

Body:
We have a need to Add or Remove Web Apps from Virtual Neworks.
We have the virtual network already setup, so we created an app to create subnets and then allocate the Web App to the VN using that subnet.

I have the following SDK's consumed in our C# project:

    <PackageReference Include="Microsoft.Azure.Management.AppService.Fluent" Version="1.38.0" />
    <PackageReference Include="Microsoft.Azure.Management.Fluent" Version="1.38.0" />
    <PackageReference Include="Microsoft.Azure.Management.Network.Fluent" Version="1.38.0" />
    <PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.6.2" />

I have tried to find a way to update the network settings for my Web App, but cannot seem to find an Update that works with it?

In the code below I have added a comment on the bit I don't know how to do.

var networks = azure.Networks.List().ToList();
var mainVN = networks.Find(n => n.Key == "MainVn");
webApp = azure.WebApps.Find(w => w.Name == "PrimaryApp")
var cidr = $"10.0.1.0/24";
string subNetName = webApp.Name + "-subnet";
await mainVN.Update().WithSubnet(subNetName, cidr).ApplyAsync();
webApp.Update() // <----- how do I do this bit? To add the subnet/VN to the app service?


问:
e.preventDefault() not working always reloads
I have the following code and the e.preventDefault() doesn´t work. Always recharges the page. Could it be something on my computer?

html:

```<code><!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> </title>
  </head>

  <body>
    <script>src="app.js"</script>

    <form id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
    </form>

  </body>

</html>

</code>```

Javascript:

```<code>
const tweetForm = document.querySelector("#tweetForm")
tweetForm.addEventListener('submit', function (e) {
    console.log("SUBMIT!!")
    e.preventDefault();
});
</code>```

答:
const tweetForm = document.querySelector("#tweetForm")

tweetForm.addEventListener('submit', function (e) {
    console.log("SUBMIT!!")
    e.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> </title>
  </head>
  <body>
    <!-- MOVE YOUR SCRIPT TO BOTTOM, JUST BEFORE CLOSE BODY TAG -->
    <!-- <script src="app.js"></script> -->
    <form id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
    </form>
    <!-- HERE IS GOOD, WITHOUT COMMENT NOTATION -->
    <!-- <script src="app.js"></script> -->
  </body>
</html></code>```

Body:
I have the following code and the e.preventDefault() doesn´t work. Always recharges the page. Could it be something on my computer?

html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> </title>

    <form id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
    </form>

Javascript:

const tweetForm = document.querySelector("#tweetForm")
tweetForm.addEventListener('submit', function (e) {
    console.log("SUBMIT!!")
    e.preventDefault();
});

Body:
const tweetForm = document.querySelector("#tweetForm")

tweetForm.addEventListener('submit', function (e) {
    console.log("SUBMIT!!")
    e.preventDefault();
});

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> </title>
  </head>
  <body>
    <!-- MOVE YOUR SCRIPT TO BOTTOM, JUST BEFORE CLOSE BODY TAG -->
    <!-- <script src="app.js"></script> -->
    <form id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
    </form>
    <!-- HERE IS GOOD, WITHOUT COMMENT NOTATION -->
    <!-- <script src="app.js"></script> -->
  </body>
</html>