问:
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true); why it give me error?
After watching a video on youtube about designing the login page of an app, I copied the code line by line, but this two lines of login.dart give me an error. What this two lines mean ?

```<code>ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
</code>```

This is login.dart page code

```<code>import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
    ScreenUtil.instance =
        ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomPadding: true,
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 50.0, right: 20.0),
                child: Image.asset("assets/login_logo.png"),
              ),
              Expanded(
                child: Container(),
              ),
              Image.asset("assets/image_02.png")
            ],
          ),
          SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.fromLTRB(28.0, 50.0, 28.0, 0.0),
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Image.asset("assets/logo.png")
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

I add the Screen Util packge flutter_screenutil: ^1.0.2 in pubspec.yaml file

答:
In this video the old version of flutter_screenutil is used: 0.7.0.

You're using 1.0.2 and the API has been changed in 1.0.0.

So, instead of:

ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
```

<p>you should use:</p>

<pre class="lang-dart prettyprint-override"><code>ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
</code>```

And, instead of:

ScreenUtil.getInstance().setWidth(...); // or .setHeight(...)
```

<p>you should use:</p>

<pre class="lang-dart prettyprint-override"><code>ScreenUtil().setWidth(...); // or .setHeight(...);
</code>```

Body:
After watching a video on youtube about designing the login page of an app, I copied the code line by line, but this two lines of login.dart give me an error. What this two lines mean ?

ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true);

This is login.dart page code

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
    ScreenUtil.instance =
        ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomPadding: true,
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 50.0, right: 20.0),
                child: Image.asset("assets/login_logo.png"),
              ),
              Expanded(
                child: Container(),
              ),
              Image.asset("assets/image_02.png")
            ],
          ),
          SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.fromLTRB(28.0, 50.0, 28.0, 0.0),
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Image.asset("assets/logo.png")
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

I add the Screen Util packge flutter_screenutil: ^1.0.2 in pubspec.yaml file

Body:
In this video the old version of flutter_screenutil is used: 0.7.0.

You're using 1.0.2 and the API has been changed in 1.0.0.

So, instead of:

ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true);

you should use:

ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);

And, instead of:

ScreenUtil.getInstance().setWidth(...); // or .setHeight(...)

you should use:

ScreenUtil().setWidth(...); // or .setHeight(...);


来源: stackexchange

问:
Topological Sort pseudocode
I have the following pseudocode for Topological Sort

```<code>Repeat:
Find a vertex with no successor
Remove it from graph
Put It at beginning of list
Until graph is empty
</code>```

My question is, should it be amended to "Find a vertex with no predecessor"?

答:
A topological sort is a way of drawing a graph that all edges go forward(horizontally). Suppose you have a graph G (G should be a DAG)and you want to do a topological sot. Pseudocode for topological sort:
Repeat:
    Find a vertex with no incoming edges
    Remove the vertex and edges in G
    Put It at beginning of list
Until graph is empty

You can also use DFS for topological sort. That is run DFS on your G, as each time a vertex is finished, inserts its identifier at the head of your topological sort list. When all the vertices in G have been discovered, the completed list is topological sort. The time complexity for this algorithm is the same with DFS which is big O of (V + E).

ContentLicense: CC BY-SA 3.0

Title: Topological Sort pseudocode

Body:
I have the following pseudocode for Topological Sort

Repeat:
Find a vertex with no successor
Remove it from graph
Put It at beginning of list
Until graph is empty

My question is, should it be amended to "Find a vertex with no predecessor"?

ContentLicense: CC BY-SA 4.0


问:
Infinite stream from a video file (in a loop)
Is there any way howto create an infinite h264 stream from a video file (eg. mp4, avi, ...). I'd like to use ffmpeg to transcode avi file to h264 but there's no loop option for output.

答:
If you want to have a live stream by looping a single video file then you could split it into .ts files and then simulate .m3u8 file with a php script which would return different .ts based on current time. You could try something similar to this:</p>

```<code><?php
// lets assume that we have stream splitted to parts named testXXXXX.ts
// and all parts have 2.4 seconds and we want to play in loop part
// from test0.ts to test29.ts forever in a live stream
header('Content-Type: application/x-mpegURL');
$time = intval(time() / 2.40000);
$s1 = ($time + 1) % 30;
$s2 = ($time + 2) % 30;
$s3 = ($time + 3) % 30;
$s4 = ($time + 4) % 30;
?>
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:2
#EXT-X-MEDIA-SEQUENCE:<?php echo "$time\n"; ?>
#EXTINF:2.40000,
test<?php echo $s1; ?>.ts
<?php if ($s2 < $s1) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s2; ?>.ts
<?php if ($s3 < $s2) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s3; ?>.ts
<?php if ($s4 < $s3) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s4; ?>.ts
</code>```

Body:
If you want to have a live stream by looping a single video file then you could split it into .ts files and then simulate .m3u8 file with a php script which would return different .ts based on current time. You could try something similar to this:

<?php
// lets assume that we have stream splitted to parts named testXXXXX.ts
// and all parts have 2.4 seconds and we want to play in loop part
// from test0.ts to test29.ts forever in a live stream
header('Content-Type: application/x-mpegURL');
$time = intval(time() / 2.40000);
$s1 = ($time + 1) % 30;
$s2 = ($time + 2) % 30;
$s3 = ($time + 3) % 30;
$s4 = ($time + 4) % 30;
?>
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:2
#EXT-X-MEDIA-SEQUENCE:<?php echo "$time\n"; ?>
#EXTINF:2.40000,
test<?php echo $s1; ?>.ts
<?php if ($s2 < $s1) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s2; ?>.ts
<?php if ($s3 < $s2) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s3; ?>.ts
<?php if ($s4 < $s3) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s4; ?>.ts


问:
Computing BITMAPINFOHEADER biCompression value for monochrome BMP
Hopefully someone has an answer, and it's not TOO complex.  I'm working on a C++ dll (no C# or .Net, fully static DLL).

Anyhow, its woring on buildin monochrome bitmaps.  I have all of it working EXCEPT the resolution. I get the Device Context, Get Compatible Device Context, build bitmap, draw what I need to (as black/white), and can save.  All this works fine.  However, I can't figure out how to set the resolution of the bitmap.

While doing some testing from another utility under C#, I can create a bitmap and set the resolution.  In doing so, I ran a routine to generate the same file content with a parameter from 1 to 300 for the resolution.  Each image came out exactly the same EXCEPT for the values in the "biCompression" DWORD property.  The default is the screen resolution of 96x96, but need to obviously change for printers of 300x300, and even some at 203x203 resolution.

答: Are you sure you don't want to set biXPelsPerMeter and biYPelsPerMeter? Those two fields tell you how many pixels per meter in X and Y, which you can use to set the DPI. biCompression only deals with the compression type of the bitmap, e.g., RLE, JPG, PNG, etc.

OwnerDisplayName: Don

LastEditorDisplayName: plinth

OwnerDisplayName: MSN

ContentLicense: CC BY-SA 2.5


问:
Best way to create a bottom toolbar in android.

Looking for a good approach to achieve a similar toolbar. Should I use image buttons ??

答:
This works for me in 2020, Android Studio 3.5.3 is how to set a Toolbar (the second half of the accepted answer).
How do I align views at the bottom of the screen?
You can use a Toolbar layout/widget in androidx.appcompat.widget.Toolbar

Set the
    alignParentBottom
property to "true" (Place the elements Inside a RelativeLayout).


问:
Temperature converter
Im am trying to solve an issue.
My teacher wants us to do a C# console with temperature converter from Celsius to Fahrenheit and switch. The problem is I continue getting errors in my coding and I don't know where I started wrong in order to get completely lost. Just to mention I am in the beginning and I would appreciate some help.

We should write a program that displays a list of temperatures in Celsius converted to Fahrenheit and vice versa. A menu is provided for the user to choose the type of conversions: The menu should repeat until the user chooses 0 to exit.

When option 1 is chosen, the program calculates and displays a list of values between 0 and 212 degrees in Fahrenheit converted to Celsius degrees as shown in the next image When option 2 is selected, the program lists values from 0 to 100 Celsius converted to Fahrenheit degrees.

This is my beginning:

using System;

namespace TempconverterA2
{
    class TemperatureConverter
    {
        public void Start()
        {

            Console.WriteLine("**************************************");
            Console.WriteLine("\t      MAIN MENU");
            Console.WriteLine("**************************************");
            Console.WriteLine(" Convert Fahrenheit to Celsius : 1");
            Console.WriteLine(" Convert Celsius to Farenheit : 2");
            Console.WriteLine(" Exit the Converter : 0");
            Console.WriteLine("**************************************");

            Console.WriteLine("\nYour choice: ");
            switch (choice)
            {
                case 1:
                    CalculateFarenheitToCelsius(F = 9 / 5 * C + 32);
                    break;
                case 2:
                    CalculateCelsiusToFarenhet(C = 5 / 9 * (F - 32));
                case 0: //do nothing (exists to loop)
                    break;

                default:
                    Console.WriteLine("Invalid option. Choose between 0 and 2.");
                    break;
            } while (choice != 0) ;
            public void CalculateCelsiusToFarenhet()
            {
                double convertedValue = 0;
                stringtextOut = string.Empty;

                for (int i= 0, i <= 100; i += 5)
                {
                    convertedValue = CalculateCelsiusToFarenhet(i);
                    textOut = string.Format("{0,16:f2} C = {1,6:f2} F", i, convertedValue);
                    Console.WriteLine(textOut);

                }
                Console.WriteLine();
    }
}//End of Start
```

答:
This is not doing what you think it is:

```<code>switch (choice)
{
    // case statements removed for brevity
} while (choice != 0);
</code>```

It is actually doing this:

```<code>switch (choice)
{

}

while (choice != 0)
{
    // infinite loop if choice != 0
}
</code>```

This is because switch is a control block and while is a separate control block.

Title: Temperature converter

Body:
This is not doing what you think it is:

switch (choice)
{
    // case statements removed for brevity
} while (choice != 0);

It is actually doing this:

switch (choice)
{

}

while (choice != 0)
{
    // infinite loop if choice != 0
}

This is because switch is a control block and while is a separate control block.


问:
I am getting A RenderFlex overflowed by 57 pixels on the bottom
Hi I am new to Flutter and I came across this error that is in the title I looked here as well but nothing seems to help, the layout looks just fine when I star the app however I am getting an error which drives me crazy. One of the solutions that I found was to add  resizeToAvoidBottomPadding: false which I did but the error is still present.  </p>

```<code>Widget build(BuildContext context) {
return Scaffold(
  resizeToAvoidBottomPadding: false,
  body: Stack(
    children: <Widget>[
      Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              flex: 3,
              child: SizedBox(),
            ),
            _title(),
            SizedBox(
              height: 50,
            ),
            _displayUserNameAndPassword(),
            SizedBox(
              height: 20,
            ),
            _submitButton(),
            Container(
              padding: EdgeInsets.symmetric(vertical: 10),
              alignment: Alignment.centerRight,
              child: Text('Forgot Password ?',
                  style:
                      TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
            ),
            _divider(),
            _facebookButton(),
            Expanded(
              flex: 2,
              child: SizedBox(),
            ),
          ],
        ),
      ),
      Align(
        alignment: Alignment.bottomCenter,
        child:  _createAccountLabel(),
      ),
    ],
  ),
);
</code>```

<p>}</p>

答:
You need to use ListView instead of Column.
In column when keyboard appears for text field it caused renderflexed overflow error.
Thanks</p>

Body:
Hi I am new to Flutter and I came across this error that is in the title I looked here as well but nothing seems to help, the layout looks just fine when I star the app however I am getting an error which drives me crazy. One of the solutions that I found was to add  resizeToAvoidBottomPadding: false which I did but the error is still present.

Widget build(BuildContext context) {
return Scaffold(
  resizeToAvoidBottomPadding: false,
  body: Stack(
    children: <Widget>[
      Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              flex: 3,
              child: SizedBox(),
            ),
            _title(),
            SizedBox(
              height: 50,
            ),
            _displayUserNameAndPassword(),
            SizedBox(
              height: 20,
            ),
            _submitButton(),
            Container(
              padding: EdgeInsets.symmetric(vertical: 10),
              alignment: Alignment.centerRight,
              child: Text('Forgot Password ?',
                  style:
                      TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
            ),
            _divider(),
            _facebookButton(),
            Expanded(
              flex: 2,
              child: SizedBox(),
            ),
          ],
        ),
      ),
      Align(
        alignment: Alignment.bottomCenter,
        child:  _createAccountLabel(),
      ),
    ],
  ),
);

}


问:
How do I get the return address of a function?
I am writing a Rust library containing an implementation of the callbacks for LLVM SanitizerCoverage. These callbacks can be used to trace the execution of an instrumented program.

A common way to produce a trace is to print the address of each executed basic block. However, in order to do that, it is necessary to retrieve the address of the call instruction that invoked the callback. The C++ examples provided by LLVM rely on the compiler intrinsic __builtin_return_address(0) in order to obtain this information.

```<code>extern "C" void __sanitizer_cov_trace_pc_guard(uint32_t *guard) {
  if (!*guard) return;
  void *PC = __builtin_return_address(0);
  printf("guard: %p %x PC %p\n", guard, *guard, PC);
}
</code>```

I am trying to reproduce the same function in Rust but, apparently, there is no equivalent to __builtin_return_address. The only reference I found is from an old version of Rust, but the function described is not available anymore. The function is the following:

pub unsafe extern "rust-intrinsic" fn return_address() -> *const u8

My current hacky solution involves having a C file in my crate that contains the following function:

```<code>void* get_return_address() {
  return __builtin_return_address(1);
}
</code>```

If I call it from a Rust function, I am able to obtain the return address of the Rust function itself. This solution, however, requires the compilation of my Rust code with -C force-frame-pointers=yes for it to work, since the C compiler intrinsic relies on the presence of frame pointers.

Concluding, is there a more straightforward way of getting the return address of the current function in Rust?

edit: The removal of the return_address intrinsic is discussed in this GitHub issue.

edit 2: Further testing showed that the backtrace crate is able to correctly extract the return address of the current function, thus avoiding the hack I described before. Credit goes to this tweet.

The problem with this solution is the overhead that is generated creating a full backtrace when only the return address of the current function is needed. In addition, the crate is using C libraries to extract the backtrace; this looks like something that should be done in pure Rust.

edit 3: The compiler intrinsic __builtin_return_address(0) generates a call to the LLVM intrinsic llvm.returnaddress. The corresponding documentation can be found here.

答:
I could not find any official documentation about this, but found out by asking in the rust-lang repository: You can link against LLVM intrinsics, like llvm.returnaddress, with only a few lines of code:

extern {
    #[link_name = "llvm.returnaddress"]
    fn return_address() -> *const u8;
}

fn foo() {
    println!("I was called by {:X}", return_address());
}
```

The LLVM intrinsic llvm.addressofreturnaddress might also be interesting.

Body:
I am writing a Rust library containing an implementation of the callbacks for LLVM SanitizerCoverage. These callbacks can be used to trace the execution of an instrumented program.

A common way to produce a trace is to print the address of each executed basic block. However, in order to do that, it is necessary to retrieve the address of the call instruction that invoked the callback. The C++ examples provided by LLVM rely on the compiler intrinsic __builtin_return_address(0) in order to obtain this information.

extern "C" void __sanitizer_cov_trace_pc_guard(uint32_t *guard) {
  if (!*guard) return;
  void *PC = __builtin_return_address(0);
  printf("guard: %p %x PC %p\n", guard, *guard, PC);
}

I am trying to reproduce the same function in Rust but, apparently, there is no equivalent to __builtin_return_address. The only reference I found is from an old version of Rust, but the function described is not available anymore. The function is the following:

pub unsafe extern "rust-intrinsic" fn return_address() -> *const u8

My current hacky solution involves having a C file in my crate that contains the following function:

void* get_return_address() {
  return __builtin_return_address(1);
}

If I call it from a Rust function, I am able to obtain the return address of the Rust function itself. This solution, however, requires the compilation of my Rust code with -C force-frame-pointers=yes for it to work, since the C compiler intrinsic relies on the presence of frame pointers.

Concluding, is there a more straightforward way of getting the return address of the current function in Rust?

edit: The removal of the return_address intrinsic is discussed in this GitHub issue.

edit 2: Further testing showed that the backtrace crate is able to correctly extract the return address of the current function, thus avoiding the hack I described before. Credit goes to this tweet.

The problem with this solution is the overhead that is generated creating a full backtrace when only the return address of the current function is needed. In addition, the crate is using C libraries to extract the backtrace; this looks like something that should be done in pure Rust.

edit 3: The compiler intrinsic __builtin_return_address(0) generates a call to the LLVM intrinsic llvm.returnaddress. The corresponding documentation can be found here.

Body:
I could not find any official documentation about this, but found out by asking in the rust-lang repository: You can link against LLVM intrinsics, like llvm.returnaddress, with only a few lines of code:

extern {
    #[link_name = "llvm.returnaddress"]
    fn return_address() -> *const u8;
}

fn foo() {
    println!("I was called by {:X}", return_address());
}

The LLVM intrinsic llvm.addressofreturnaddress might also be interesting.


问:
Check if sum of a list is equal to either of two values or not
I have a list of True or False. I want to know if all of them are either True or False.

My code:

```<code>list1 = [False, True,False,False,True]
list2 = [False, True,False,True]
list3 = [False, False,False]
list4 = [True, True,True, True,True]

if sum(list1)==len(list1)|0:
    print("Yes! all are either True or False")
else:
    print("Not satisfied")
</code>```

Looks like my code works fine if all are True but not if all are False. How to check if all are False

Expected output for four lists:

```<code>list1 >> Not satisfied
list2 >> Not satisfied
list3 >> Yes! all are either True or False
list4 >> Yes! all are either True or False
</code>```

答:
In this case, you could use the built-in all() and any():

```<code>for lst in [list1, list2, list3, list4]:
    if all(lst) or not any(lst):   # if it isn't true that any are true, then all must be False
        print("Yes! all are either True or False")
    else:
        print("Not satisfied")
</code>```

output:

```<code>Not satisfied
Not satisfied
Yes! all are either True or False
Yes! all are either True or False
</code>```

Body:
I have a list of True or False. I want to know if all of them are either True or False.

My code:

list1 = [False, True,False,False,True]
list2 = [False, True,False,True]
list3 = [False, False,False]
list4 = [True, True,True, True,True]

if sum(list1)==len(list1)|0:
    print("Yes! all are either True or False")
else:
    print("Not satisfied")

Looks like my code works fine if all are True but not if all are False. How to check if all are False

Expected output for four lists:

list1 >> Not satisfied
list2 >> Not satisfied
list3 >> Yes! all are either True or False
list4 >> Yes! all are either True or False

Body:
In this case, you could use the built-in all() and any():

for lst in [list1, list2, list3, list4]:
    if all(lst) or not any(lst):   # if it isn't true that any are true, then all must be False
        print("Yes! all are either True or False")
    else:
        print("Not satisfied")

output:

Not satisfied
Not satisfied
Yes! all are either True or False
Yes! all are either True or False


问:
C# How do i get the Right(String) based on one character?
I have this:

```<code>MyString = @"C:\\Somepath\otherpath\etc\string";
</code>```

And i need this string (which can be longer than a group of characters)

How can i do something like:

```<code>NewString = MyString.Right(string, when last "\" is found) ?
</code>```

答:
If you don't mind using a bit of LINQ:</p>

```<code>var result = MyString?.Split('\\').LastOrDefault();
</code>```

Body:
I have this:

MyString = @"C:\\Somepath\otherpath\etc\string";

And i need this string (which can be longer than a group of characters)

How can i do something like:

NewString = MyString.Right(string, when last "\" is found) ?

Body:
If you don't mind using a bit of LINQ:

var result = MyString?.Split('\\').LastOrDefault();


问:
Filling in columns
I have the following data:

1)

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

What I need to do is to fill in the missing rows like this:

```<code>1 1
1 2
1 3
1 4
1 5
2 1
2 2
</code>```

After which I need to populate a new column so that the new rows have a zero and the old rows have a 1, like this:

```<code>1 1 1
1 2 0
1 3 1
1 4 0
1 5 1
2 1 1
2 2 1
</code>```

After which I would have to transpose the last column into a row like this:

```<code>1,0,1,0,1,1,1
</code>```

I am stuck at the first step, not knowing how to check for and fill the entries so I cannot really give you an example of my work... Thank you for your help!

答:
You can try this:

import pandas as pd
import numpy as np

df=pd.DataFrame({"x": [1,1,1,2,2], "y": [1,3,5,1,2]})

df["rep"]=np.where(df["y"].lt(df["y"].shift(-1)),df["y"].shift(-1).sub(df["y"]).sub(1), 0)

df=df.loc[df.index.repeat(df["rep"].add(1))]

df["y"]=df["y"].add(df.groupby(level=0)["y"].cumcount())

df["rep"]=df.groupby(level=0)["y"].cumcount().lt(1).astype(int)

df=df.reset_index(drop=True)
```
<p>And the output you're looking for:</p>
<pre class="lang-py prettyprint-override"><code>>>> print(df["rep"].T.tolist())
[1, 0, 1, 0, 1, 1, 1]

>>> print(df)
   x  y  rep
0  1  1    1
1  1  2    0
2  1  3    1
3  1  4    0
4  1  5    1
5  2  1    1
6  2  2    1
</code>```

Title: Filling in columns

Body:
I have the following data:

1)

1 1
1 3
1 5
2 1
2 2

What I need to do is to fill in the missing rows like this:

1 1
1 2
1 3
1 4
1 5
2 1
2 2

After which I need to populate a new column so that the new rows have a zero and the old rows have a 1, like this:

1 1 1
1 2 0
1 3 1
1 4 0
1 5 1
2 1 1
2 2 1

After which I would have to transpose the last column into a row like this:

1,0,1,0,1,1,1

I am stuck at the first step, not knowing how to check for and fill the entries so I cannot really give you an example of my work... Thank you for your help!

Body:
You can try this:

import pandas as pd
import numpy as np

df=pd.DataFrame({"x": [1,1,1,2,2], "y": [1,3,5,1,2]})

df["rep"]=np.where(df["y"].lt(df["y"].shift(-1)),df["y"].shift(-1).sub(df["y"]).sub(1), 0)

df=df.loc[df.index.repeat(df["rep"].add(1))]

df["y"]=df["y"].add(df.groupby(level=0)["y"].cumcount())

df["rep"]=df.groupby(level=0)["y"].cumcount().lt(1).astype(int)

df=df.reset_index(drop=True)

And the output you're looking for:

>>> print(df["rep"].T.tolist())
[1, 0, 1, 0, 1, 1, 1]

>>> print(df)
   x  y  rep
0  1  1    1
1  1  2    0
2  1  3    1
3  1  4    0
4  1  5    1
5  2  1    1
6  2  2    1


问:
Debugging .dll with R application attachment produces "Illegal Instruction" error
The program I am debugging is an R GUI application that utilizes several C .dll files to perform tasks. I am using Visual Studio 2019 as my debugger.

The error: Unhandled exception at 0x00000000279BB8CC (tcl86.dll) in rsession.exe: 0xC000001D: Illegal Instruction.

I am not sure how to look deeper into why tcl86.dll is acting up as it is.

This is my first time debugging a program, and it happens to be a fairly convoluted one, so I am not sure how to interpret the output I am given. I will share as much as I can, and let me know if I need to post more information.

Here is the call stack:

```<code>    tcl86.dll!00000000279bb8cc()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!000000002797f8b5()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!000000002797f9d2()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!0000000027999606()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!0000000027999c2b()    Unknown Non-user code. Binary was not built with debug information.
>   tkogl2.dll!del(void * clientData, Tcl_Interp * interp, int objc, Tcl_Obj * const * objv) Line 1148  C   Symbols loaded.
    tcl86.dll!00000000278a7a07()    Unknown Non-user code. Binary was not built with debug information.
    tcltk.dll!000000006c302378()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7a6542()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f3249()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fa2()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fa2()    Unknown Non-user code. Binary was not built with debug information.
    tcltk.dll!000000006c301aae()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!00000000278a2492()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!00000000278a7a07()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!00000000278aa454()    Unknown Non-user code. Binary was not built with debug information.
    tk86.dll!0000000062982874() Unknown Non-user code. Binary was not built with debug information.
    tk86.dll!00000000629170bf() Unknown Non-user code. Binary was not built with debug information.
    tk86.dll!000000006292111f() Unknown Non-user code. Binary was not built with debug information.
    user32.dll!00007ffea7315b6d()   Unknown Non-user code. Cannot find or open the PDB file.
    user32.dll!00007ffea7315562()   Unknown Non-user code. Cannot find or open the PDB file.
    Rgraphapp.dll!000000006355751b()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c721365()    Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000085b0e9() Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c796727()    Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000085d670() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000044de43() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000004194b7() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!0000000000894845() Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c829772()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c829a01()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c829a92()    Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000008a9801() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000008915cf() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!0000000000bedf98() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000004013e8() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000040151b() Unknown Non-user code. Binary was not built with debug information.
    kernel32.dll!00007ffea5b47bd4() Unknown Non-user code. Cannot find or open the PDB file.
    ntdll.dll!00007ffea754ced1()    Unknown Non-user code. Cannot find or open the PDB file.
</code>```

Here is the output in the debugger: alloc: invalid block: 000000002BF31390: 0 2bException thrown at 0x00000000279BB8CC (tcl86.dll) in rsession.exe: 0xC000001D: Illegal Instruction.
Unhandled exception at 0x00000000279BB8CC (tcl86.dll) in rsession.exe: 0xC000001D: Illegal Instruction.

Here is a bit of code where the debugger stopped in the C code:

```<code>else if (strcmp(shape, "specimens") == 0)
    {
        specimen_del(0);

        if (models != NULL)
        {
            Tcl_Free((char*)models);
            models = NULL; //error symbol here
        }
        if (context != NULL)
        {
            Tcl_Free((char*)context);
            context = NULL;
        }
    }
</code>```

The goal of this post is to understand how to interpret the error and information I am given by the debugger and potential solutions I may be able to explore. Thank you!

答:
The first part of that message, alloc: invalid block: 000000002BF31390: 0 2b, is a message out of the Tcl library. The meaning of the message is that memory has been corrupted by an out-of-bounds memory write. The location of the generation of that message is in Tcl's thread-aware memory allocator, but is not the place where the bug is: it's just where the problem was detected.
Once memory is corrupted, all bets are off about the future behaviour of the program; dying with an illegal instruction error is entirely possible (which could be due to a corrupted stack).

Neither the Tcl nor the Tk DLLs (specifically tcl86.dll and tk86.dll in your stack trace) will create out of bounds accesses if memory is not corrupted: we really do check for this sort of thing very carefully (and have developer build modes that make any such problems show up, at least in their implementation). However, if other code writes where it shouldn't (and there's plenty of code in there that I cannot vouch for at all) then all bets are off because the preconditions for the correctness of the code no longer hold.

tl;dr You've got a memory corruption problem. Which sucks a lot.

Try a static build of your application with a memory access tracing tool like electricfence or purify (there may be others too, this isn't intended to be an exhaustive list); the performance hit for doing that is profound, but the chances of it finding the bug itself are reasonably high.

Body:
The program I am debugging is an R GUI application that utilizes several C .dll files to perform tasks. I am using Visual Studio 2019 as my debugger.

The error: Unhandled exception at 0x00000000279BB8CC (tcl86.dll) in rsession.exe: 0xC000001D: Illegal Instruction.

I am not sure how to look deeper into why tcl86.dll is acting up as it is.

This is my first time debugging a program, and it happens to be a fairly convoluted one, so I am not sure how to interpret the output I am given. I will share as much as I can, and let me know if I need to post more information.

Here is the call stack:

    tcl86.dll!00000000279bb8cc()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!000000002797f8b5()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!000000002797f9d2()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!0000000027999606()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!0000000027999c2b()    Unknown Non-user code. Binary was not built with debug information.
>   tkogl2.dll!del(void * clientData, Tcl_Interp * interp, int objc, Tcl_Obj * const * objv) Line 1148  C   Symbols loaded.
    tcl86.dll!00000000278a7a07()    Unknown Non-user code. Binary was not built with debug information.
    tcltk.dll!000000006c302378()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7a6542()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f3249()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fa2()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c80268c()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c802f2a()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f6733()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c7f8bdf()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fe1()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c803a98()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c804b1f()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c801fa2()    Unknown Non-user code. Binary was not built with debug information.
    tcltk.dll!000000006c301aae()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!00000000278a2492()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!00000000278a7a07()    Unknown Non-user code. Binary was not built with debug information.
    tcl86.dll!00000000278aa454()    Unknown Non-user code. Binary was not built with debug information.
    tk86.dll!0000000062982874() Unknown Non-user code. Binary was not built with debug information.
    tk86.dll!00000000629170bf() Unknown Non-user code. Binary was not built with debug information.
    tk86.dll!000000006292111f() Unknown Non-user code. Binary was not built with debug information.
    user32.dll!00007ffea7315b6d()   Unknown Non-user code. Cannot find or open the PDB file.
    user32.dll!00007ffea7315562()   Unknown Non-user code. Cannot find or open the PDB file.
    Rgraphapp.dll!000000006355751b()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c721365()    Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000085b0e9() Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c796727()    Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000085d670() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000044de43() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000004194b7() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!0000000000894845() Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c829772()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c829a01()    Unknown Non-user code. Binary was not built with debug information.
    R.dll!000000006c829a92()    Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000008a9801() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000008915cf() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!0000000000bedf98() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!00000000004013e8() Unknown Non-user code. Binary was not built with debug information.
    rsession.exe!000000000040151b() Unknown Non-user code. Binary was not built with debug information.
    kernel32.dll!00007ffea5b47bd4() Unknown Non-user code. Cannot find or open the PDB file.
    ntdll.dll!00007ffea754ced1()    Unknown Non-user code. Cannot find or open the PDB file.

Here is the output in the debugger: alloc: invalid block: 000000002BF31390: 0 2bException thrown at 0x00000000279BB8CC (tcl86.dll) in rsession.exe: 0xC000001D: Illegal Instruction.
Unhandled exception at 0x00000000279BB8CC (tcl86.dll) in rsession.exe: 0xC000001D: Illegal Instruction.

Here is a bit of code where the debugger stopped in the C code:

else if (strcmp(shape, "specimens") == 0)
    {
        specimen_del(0);

        if (models != NULL)
        {
            Tcl_Free((char*)models);
            models = NULL; //error symbol here
        }
        if (context != NULL)
        {
            Tcl_Free((char*)context);
            context = NULL;
        }
    }

The goal of this post is to understand how to interpret the error and information I am given by the debugger and potential solutions I may be able to explore. Thank you!


问:
There is a print invoice API / Endpoint for the Authorize.net SDK?
There is a way to print PDF or HTML or whatever format an invoice from Authorize SDK (Sending the transaction ID )? </p>

答: No, there is not. Authorize.Net does not handle invoicing. It only facilitates the payment. </p>


问:
Error updating table in SSIS
I am getting the following error while updating data to a table with lookup in SSIS:

Source: "Microsoft SQL Native Client"
  Hresult: 0x80040E14  Description: "The
  incoming tabular data stream (TDS)
  remote procedure call (RPC) protocol
  stream is incorrect. The RPC name is
  invalid.".

I deleted the DFD and recreated again but getting the same error. I am updating the table with OLEDB command.

答: Have you tried changing the connection to your Sql Server to use OLEDB instead of SQL Native Client?</p>

Title: Error updating table in SSIS


问:
GCP Dataflow- read CSV file from Compute Engine VM and write into BigQuery
GCP Dataflow- read CSV file from Storage and write into BigQuery</p>

答: Cloud Dataflow can't read files from the disk of VM. The best way is to upload your file into a Bucket and then to use BuiltIn connector. In Java, I use FileIO.


问:
Image is visible but text is not visible in ListView
I am trying to create a custom layout for list view in android studio. I was able to successfully get image in the in ListView on runtime but wasn't able to print text in the list view . When i run my program in emulator it runs without any error but it doesn't show any text it only shows image from drawables.

MainActivity.java

```<code>    import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    private final  static String[] names={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
            "A","A","A","A","A","A","A","A","A","A","A","A","A","A",};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView ls = findViewById((R.id.customlistview));
        ls.setAdapter(new CustomListAdapter(getApplicationContext(),names,R.drawable.za));
    }
}
</code>```

activity_main.xml

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

    <ListView
        android:id="@+id/customlistview"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

CustomListAdapter.java

```<code>    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends BaseAdapter {
    private final Context context;
    private final String[] names;
    private final int image;
    private final LayoutInflater layoutInflater;

    public  CustomListAdapter(Context context,String[] names,int image) {

        this.context=context;
        this.image=image;
        this.names=names;
        layoutInflater= (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rootview;
        rootview = layoutInflater.inflate(R.layout.list_item_layout, null);
        TextView tv= rootview.findViewById(R.id.textView);
        ImageView iv=rootview.findViewById(R.id.imageView);
        tv.setText(names[position]);
        iv.setImageResource(image);
        return rootview;

    }
}
</code>```

list_item_layout.xml

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:height="70dp"
        android:gravity="center"
        android:text="TextView"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_weight="2"
        app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>
</code>```

答: The problem was caused by the text colour , changing the colour of textview text in list_item_layout resolved the issue.</p>

Body:
I am trying to create a custom layout for list view in android studio. I was able to successfully get image in the in ListView on runtime but wasn't able to print text in the list view . When i run my program in emulator it runs without any error but it doesn't show any text it only shows image from drawables.

MainActivity.java

    import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    private final  static String[] names={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
            "A","A","A","A","A","A","A","A","A","A","A","A","A","A",};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView ls = findViewById((R.id.customlistview));
        ls.setAdapter(new CustomListAdapter(getApplicationContext(),names,R.drawable.za));
    }
}

activity_main.xml

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

    <ListView
        android:id="@+id/customlistview"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

CustomListAdapter.java

    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends BaseAdapter {
    private final Context context;
    private final String[] names;
    private final int image;
    private final LayoutInflater layoutInflater;

    public  CustomListAdapter(Context context,String[] names,int image) {

        this.context=context;
        this.image=image;
        this.names=names;
        layoutInflater= (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rootview;
        rootview = layoutInflater.inflate(R.layout.list_item_layout, null);
        TextView tv= rootview.findViewById(R.id.textView);
        ImageView iv=rootview.findViewById(R.id.imageView);
        tv.setText(names[position]);
        iv.setImageResource(image);
        return rootview;

    }
}

list_item_layout.xml

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:height="70dp"
        android:gravity="center"
        android:text="TextView"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_weight="2"
        app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>


问:
Error when connecting from a web server to a remote MySQL DB Server
I have been struggling to connect from  a Ubuntu version 16.04 web server
(running on 1  AWS instance, with PHP 7.0.33 and Apache 2.7.18)
communicating with a data base server using MySQL 8.0.19 running on another AWS instance (running Ubuntu version 16.04).

I set up the data base server and configured it as follows:

I edit the file  /etc/mysql/mysql.conf.d/mysqld.cnf

I add the following in the [mysqld] section
     [mysqld]

```<code>require_secure_transport = on
</code>```

I save the file and from the console issue:

```<code>sudo mysql_ssl_rsa_setup --uid=mysql
</code>```

I then restart mysql with:

```<code>sudo systemctl restart mysql
</code>```

I have created a data base and tables on this data base server.

I also created a remote user on this data base server as follows (IP address and user are fictitious):

```<code>CREATE USER 'Master'@'1.26.4.44' IDENTIFIED BY 'admin';

GRANT ALL PRIVILEGES ON sample_data_base.* TO ' Master'@'1.26.4.44';

FLUSH PRIVILEGES;

Exit
</code>```

I successfully test the connectivity to this db server from the web server client instance:

```<code>mysql -u Master -p   -h '1.26.4.44'
</code>```

However when I use the following PHP code snippet from the web server client instance
to open the connection to the data base server, I get an error (see below):

```<code>// set up for  remote DB access
  $dbhost  = '1.26.4.44';    // Unlikely to require changing
  $dbname  = 'sample_data_base';   // Modify these...
  $dbuser  = 'Master';   // ...variables according
  $dbpass  = "admin";   // ...to your installation
  $appname = "test_app"; // ...and preference

$dbconnection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

   if ( !$dbconnection)
  {
      echo "connection failed   ";
      die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
  }
</code>```

The error is:

```<code>Connect Error (3159) Connections using insecure transport are prohibited while --require_secure_transport=ON
</code>```

Just as an FYI,  when I comment out the line on the data base server in the
file  /etc/mysql/mysql.conf.d/mysqld.cnf

```<code># require_secure_transport = on
</code>```

There are no issues with the php code connection to the remote data base server.

What am I missing on the web server client side to let me connect to the remote db server from the php code?

答:
You need extra configurations in your db setup:

```<code>$db = mysqli_init();
mysqli_options ($db, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);

$db->ssl_set(
    '/etc/mysql/ssl/client-key.pem',
    '/etc/mysql/ssl/client-cert.pem',
    '/etc/mysql/ssl/ca-cert.pem',
    NULL,
    NULL);

$link = mysqli_real_connect(
        $db, 'ip', 'user', 'password', 'db', 3306, NULL, MYSQLI_CLIENT_SSL);

if (!$link)
{
    die ('Connect error (' . mysqli_connect_errno() . '): ' . mysqli_connect_error() . "\n");
} else {
    // your queries should be here
     $db->close();
}
</code>```

Hope this can help.

Body:
I have been struggling to connect from  a Ubuntu version 16.04 web server
(running on 1  AWS instance, with PHP 7.0.33 and Apache 2.7.18)
communicating with a data base server using MySQL 8.0.19 running on another AWS instance (running Ubuntu version 16.04).

I set up the data base server and configured it as follows:

I edit the file  /etc/mysql/mysql.conf.d/mysqld.cnf

I add the following in the [mysqld] section
     [mysqld]

require_secure_transport = on

I save the file and from the console issue:

sudo mysql_ssl_rsa_setup --uid=mysql

I then restart mysql with:

sudo systemctl restart mysql

I have created a data base and tables on this data base server.

I also created a remote user on this data base server as follows (IP address and user are fictitious):

CREATE USER 'Master'@'1.26.4.44' IDENTIFIED BY 'admin';

GRANT ALL PRIVILEGES ON sample_data_base.* TO ' Master'@'1.26.4.44';

FLUSH PRIVILEGES;

Exit

I successfully test the connectivity to this db server from the web server client instance:

mysql -u Master -p   -h '1.26.4.44'

However when I use the following PHP code snippet from the web server client instance
to open the connection to the data base server, I get an error (see below):

// set up for  remote DB access
  $dbhost  = '1.26.4.44';    // Unlikely to require changing
  $dbname  = 'sample_data_base';   // Modify these...
  $dbuser  = 'Master';   // ...variables according
  $dbpass  = "admin";   // ...to your installation
  $appname = "test_app"; // ...and preference

$dbconnection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

   if ( !$dbconnection)
  {
      echo "connection failed   ";
      die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
  }

The error is:

Connect Error (3159) Connections using insecure transport are prohibited while --require_secure_transport=ON

Just as an FYI,  when I comment out the line on the data base server in the
file  /etc/mysql/mysql.conf.d/mysqld.cnf

# require_secure_transport = on

There are no issues with the php code connection to the remote data base server.

What am I missing on the web server client side to let me connect to the remote db server from the php code?

Body:
You need extra configurations in your db setup:

$db = mysqli_init();
mysqli_options ($db, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);

$db->ssl_set(
    '/etc/mysql/ssl/client-key.pem',
    '/etc/mysql/ssl/client-cert.pem',
    '/etc/mysql/ssl/ca-cert.pem',
    NULL,
    NULL);

$link = mysqli_real_connect(
        $db, 'ip', 'user', 'password', 'db', 3306, NULL, MYSQLI_CLIENT_SSL);

if (!$link)
{
    die ('Connect error (' . mysqli_connect_errno() . '): ' . mysqli_connect_error() . "\n");
} else {
    // your queries should be here
     $db->close();
}

Hope this can help.


问:
Vue axios post request blocked by CORS policy
Vue axios post request

```<code>axios.post(`${this.host}:${this.port}/apiv2/login`, {
        body: {
          userName: this.user,
          password: this.pwd
        }
      });
</code>```

resulted in ERROR:

```<code>Access to XMLHttpRequest at 'http://localhost:9047/apiv2/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

python requests, postman or simple curl does the job without errors

```<code>curl 'http://localhost:9047/apiv2/login' -H 'Content-Type: application/json' --data-binary '{"userName":"user","password":"pass"}'
</code>```

UPDATE:
Here my solution:

I added NodeJS server (localhost:8081). Now Vue (localhost:8080) is accessing NodeJS and NodeJS is quering Dremio API (localhost:9047).

The idea of having just static Vue app didn't work.

答:
1st: Try add {'Access-Control-Allow-Origin': '*'} inside  and then try again.
If not work, then go to your "Localhost:8080" and set Access Control Origin to * then try first step again

Body:
Vue axios post request

axios.post(`${this.host}:${this.port}/apiv2/login`, {
        body: {
          userName: this.user,
          password: this.pwd
        }
      });

resulted in ERROR:

Access to XMLHttpRequest at 'http://localhost:9047/apiv2/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

python requests, postman or simple curl does the job without errors

curl 'http://localhost:9047/apiv2/login' -H 'Content-Type: application/json' --data-binary '{"userName":"user","password":"pass"}'

UPDATE:
Here my solution:

I added NodeJS server (localhost:8081). Now Vue (localhost:8080) is accessing NodeJS and NodeJS is quering Dremio API (localhost:9047).

The idea of having just static Vue app didn't work.


问:
EXCEL isThisWeek()
I would like a formula that would return true if a given date is in this week, for example:
Lets say Today() is 2/18/2020
I would want it to return true if the GivenDate() is anywhere between 2/16/2020 and 2/22/2020.
I would also like a formula for isNextWeek().</p>

答:
For this week:

```<code>=AND(WEEKNUM(TODAY())=WEEKNUM(A1),YEAR(TODAY())=YEAR(A1))
</code>```

For Next Week

```<code>=AND(WEEKNUM(TODAY())+1=WEEKNUM(A1),YEAR(TODAY())=YEAR(A1))
</code>```

One note:  This will fail during the new year change.

For a formula that works no matter if over the new year:

This Week:

```<code> =MEDIAN(TODAY()-WEEKDAY(TODAY())+1,TODAY()-WEEKDAY(TODAY())+7,A1)=A1
</code>```

Next Week:

```<code>=MEDIAN(TODAY()-WEEKDAY(TODAY())+8,TODAY()-WEEKDAY(TODAY())+14,A1)=A1
</code>```

Title: EXCEL isThisWeek()

Body:
For this week:

=AND(WEEKNUM(TODAY())=WEEKNUM(A1),YEAR(TODAY())=YEAR(A1))

For Next Week

=AND(WEEKNUM(TODAY())+1=WEEKNUM(A1),YEAR(TODAY())=YEAR(A1))

One note:  This will fail during the new year change.

For a formula that works no matter if over the new year:

This Week:

 =MEDIAN(TODAY()-WEEKDAY(TODAY())+1,TODAY()-WEEKDAY(TODAY())+7,A1)=A1

Next Week:

=MEDIAN(TODAY()-WEEKDAY(TODAY())+8,TODAY()-WEEKDAY(TODAY())+14,A1)=A1


问:
Is There A Way To Remove Duplicate Code While Providing lvalue and rvalue Overloads?
While learning C++ I decided to write a simple templated binary search tree (bst) and encountered the following problem: I want to be able to construct a bst by both passing it an lvalue like const T &val and an rvalue like T &&val. Similarly I want to be able to insert lvalues and rvalues. So I ended up with a lot of duplicate code which I don't like:

```<code>/// copy constructor
explicit inline constexpr binary_search_tree(const T &val)
    : _root{std::make_unique<binary_search_tree_node>(val)} {}

/// move constructor
explicit inline constexpr binary_search_tree(T &&val)
    : _root{std::make_unique<binary_search_tree_node>(std::move(val))} {}
</code>```

for the constructors, where binary_search_tree_node is a private member ofbinary_search_tree which then had to provide copy and move constructor as well:

```<code>struct binary_search_tree_node {
  T value;
  std::unique_ptr<binary_search_tree_node> left;
  std::unique_ptr<binary_search_tree_node> right;

  // prohibit creation of tree_node without value
  inline constexpr binary_search_tree_node() = delete;

  /// copy constructor
  explicit inline constexpr binary_search_tree_node(const T &val)
      : value{val}, left{nullptr}, right{nullptr} {}

  /// move constructor
  explicit inline constexpr binary_search_tree_node(T &&val)
      : value{std::move(val)}, left{nullptr}, right{nullptr} {}
};
</code>```

Also:

```<code>inline constexpr void insert(const T &v) {
  if (!_root) {
    _root = std::make_unique<binary_search_tree_node>(v);
    ++_size;
  } else {
    insert(_root, v);
  }
}

inline constexpr void insert(T &&v) {
  if (!_root) {
    _root = std::make_unique<binary_search_tree_node>(std::move(v));
    ++_size;
  } else {
    insert(_root, std::move(v));
  }
}
</code>```

for the insert functions.

The list goes on when I want to search a value: Should I provide overloads for find(const T &val) and find(T &&val)..?

So my question is whether there is a way of combining these overloads or any
  other way to remove this duplicate code?

I read about reference collapsing rules but I am not sure whether I could make use of this concept here.

Any other thoughts or suggestions are also appreciated.

答:
Yes, you can use reference collapsing to reduce the amount of function written.

For example, your function insert can use a rvalue reference + immediate context to leverage reference collapsing, resulting in a forwarding reference:

```<code>template<typename U>
inline constexpr void insert(U &&v) { // v is a forwarding reference
    if (!_root) {
        // we use std::forward to keep rvalue-ness
        // of the named object when v is an rvalue, but not when it's a lvalue
        _root = std::make_unique<binary_search_tree_node>(std::forward<U>(v));
        ++_size;
    } else {
        insert(_root, std::forward<U>(v));
    }
}
</code>```

Even though the parameter is using an rvalue reference, lvalue will work here because of the reference collapsing. If U deduces to int&, then the parameter is kind of int& &&, which collapse to int&. On the contrary, if an rvalue is sent, it will deduce int as U so the parameter is int &&.

This pattern is called a forwarding reference.

As you can see, such code only has that property if template argument deduction is there for the forwarding parameter.

Be aware that making it a template will make it accept more types than anticipated if not constrained correctly.

You can also use a copy then move to avoid code duplication:

```<code>inline constexpr void insert(const T &v) {
    T copy = v;
    insert(std::move(copy)); // calls the rvalue overload
}
</code>```

Body:
While learning C++ I decided to write a simple templated binary search tree (bst) and encountered the following problem: I want to be able to construct a bst by both passing it an lvalue like const T &val and an rvalue like T &&val. Similarly I want to be able to insert lvalues and rvalues. So I ended up with a lot of duplicate code which I don't like:

/// copy constructor
explicit inline constexpr binary_search_tree(const T &val)
    : _root{std::make_unique<binary_search_tree_node>(val)} {}

/// move constructor
explicit inline constexpr binary_search_tree(T &&val)
    : _root{std::make_unique<binary_search_tree_node>(std::move(val))} {}

for the constructors, where binary_search_tree_node is a private member ofbinary_search_tree which then had to provide copy and move constructor as well:

struct binary_search_tree_node {
  T value;
  std::unique_ptr<binary_search_tree_node> left;
  std::unique_ptr<binary_search_tree_node> right;

  // prohibit creation of tree_node without value
  inline constexpr binary_search_tree_node() = delete;

  /// copy constructor
  explicit inline constexpr binary_search_tree_node(const T &val)
      : value{val}, left{nullptr}, right{nullptr} {}

  /// move constructor
  explicit inline constexpr binary_search_tree_node(T &&val)
      : value{std::move(val)}, left{nullptr}, right{nullptr} {}
};

Also:

inline constexpr void insert(const T &v) {
  if (!_root) {
    _root = std::make_unique<binary_search_tree_node>(v);
    ++_size;
  } else {
    insert(_root, v);
  }
}

inline constexpr void insert(T &&v) {
  if (!_root) {
    _root = std::make_unique<binary_search_tree_node>(std::move(v));
    ++_size;
  } else {
    insert(_root, std::move(v));
  }
}

for the insert functions.

The list goes on when I want to search a value: Should I provide overloads for find(const T &val) and find(T &&val)..?

So my question is whether there is a way of combining these overloads or any
  other way to remove this duplicate code?

I read about reference collapsing rules but I am not sure whether I could make use of this concept here.

Any other thoughts or suggestions are also appreciated.

Body:
Yes, you can use reference collapsing to reduce the amount of function written.

For example, your function insert can use a rvalue reference + immediate context to leverage reference collapsing, resulting in a forwarding reference:

template<typename U>
inline constexpr void insert(U &&v) { // v is a forwarding reference
    if (!_root) {
        // we use std::forward to keep rvalue-ness
        // of the named object when v is an rvalue, but not when it's a lvalue
        _root = std::make_unique<binary_search_tree_node>(std::forward<U>(v));
        ++_size;
    } else {
        insert(_root, std::forward<U>(v));
    }
}

Even though the parameter is using an rvalue reference, lvalue will work here because of the reference collapsing. If U deduces to int&, then the parameter is kind of int& &&, which collapse to int&. On the contrary, if an rvalue is sent, it will deduce int as U so the parameter is int &&.

This pattern is called a forwarding reference.

As you can see, such code only has that property if template argument deduction is there for the forwarding parameter.

Be aware that making it a template will make it accept more types than anticipated if not constrained correctly.

You can also use a copy then move to avoid code duplication:

inline constexpr void insert(const T &v) {
    T copy = v;
    insert(std::move(copy)); // calls the rvalue overload
}


问:
Explaining semantics around module imports within TypeScript declaration files
A couple months ago I wrote a simple TS declaration library @types/datadog-winston that can be seen here. I used the typings locally, added them to the DefinitelyTyped repository, got through all the usual verifications and tests from that team and got my library published.

I am now trying to go back and actually use it and am running into a problem. When I try to add my new DatadogWinston(options) object to the list of TransportStream[] in order to use it as another transport for winston I get this error:

```<code>Services/Sandbox/sandbox/node_modules/@types/datadog-winston/index.d.ts:19:48 - error TS2339: Property 'TransportStream' does not exist on type 'typeof TransportStream'.

declare class DatadogWinston extends Transport.TransportStream {
                                               ~~~~~~~~~~~~~~~

Services/Sandbox/sandbox/src/logging/logger.ts:32:21 - error TS2345: Argument of type 'DatadogWinston' is not assignable to parameter of type 'TransportStream'.
  Type 'DatadogWinston' is missing the following properties from type 'TransportStream': writable, writableHighWaterMark, writableLength, _write, and 24 more.

transports.push(transport);
                ~~~~~~~~~
</code>```

After a lot of looking around at how other winston transports work, I found they all seem to do slightly different things when importing the module winston-transport.

Graylog2

They did exactly what I did like this:

```<code>import * as TransportStream from "winston-transport";

declare class Graylog2Transport extends TransportStream {
  constructor(options?: Graylog2Transport.TransportOptions);
}
...
</code>```

Then there is winston-loggly-bulk that did this instead:

```<code>import TransportStream = require('winston-transport');
</code>```

When I changed mine from  being like Graylog2 to be like winston-loggly-bulk by using

```<code>import TransportStream = require("winston-transport");
</code>```

All of a sudden my build errors go away.  So my question is what exactly is the difference in what I am doing here? I know CommonJS was the old way of doing const lib = require('mylib') and ES6 has the new import { Thing } from 'mylib', but what is this bizarre hybrid way of doing it where you have import MyLib = require('mylib') and why is this needed for this situation? I am having a hard time understanding the nuances between all these methods.

UPDATE

I tried installing the winston-graylog2 library and use it and I get the exact same error! FYI I am using the latest version of TypeScript (v3.7.5). I have a feeling this is related to my local development, but I get the error both in VS Code (using TS Server extension) and when doing a tsc build from CLI directly.

答:
This is covered in the module documentation here.

When you do import * as TransportStream from "winston-transport"; you're importing the module namespace object for the module, a synthetic object that has all of the module's exports on it as properties.

When you do import Transport = require("winston-transport"); you're using the TypeScript-specific single object export.

[I suspect (but don't know) that import default as Transport from "winston-transport"; would also work.]

Body:
A couple months ago I wrote a simple TS declaration library @types/datadog-winston that can be seen here. I used the typings locally, added them to the DefinitelyTyped repository, got through all the usual verifications and tests from that team and got my library published.

I am now trying to go back and actually use it and am running into a problem. When I try to add my new DatadogWinston(options) object to the list of TransportStream[] in order to use it as another transport for winston I get this error:

Services/Sandbox/sandbox/node_modules/@types/datadog-winston/index.d.ts:19:48 - error TS2339: Property 'TransportStream' does not exist on type 'typeof TransportStream'.

declare class DatadogWinston extends Transport.TransportStream {
                                               ~~~~~~~~~~~~~~~

Services/Sandbox/sandbox/src/logging/logger.ts:32:21 - error TS2345: Argument of type 'DatadogWinston' is not assignable to parameter of type 'TransportStream'.
  Type 'DatadogWinston' is missing the following properties from type 'TransportStream': writable, writableHighWaterMark, writableLength, _write, and 24 more.

transports.push(transport);
                ~~~~~~~~~

After a lot of looking around at how other winston transports work, I found they all seem to do slightly different things when importing the module winston-transport.

Graylog2

They did exactly what I did like this:

import * as TransportStream from "winston-transport";

declare class Graylog2Transport extends TransportStream {
  constructor(options?: Graylog2Transport.TransportOptions);
}
...

Then there is winston-loggly-bulk that did this instead:

import TransportStream = require('winston-transport');

When I changed mine from  being like Graylog2 to be like winston-loggly-bulk by using

import TransportStream = require("winston-transport");

All of a sudden my build errors go away.  So my question is what exactly is the difference in what I am doing here? I know CommonJS was the old way of doing const lib = require('mylib') and ES6 has the new import { Thing } from 'mylib', but what is this bizarre hybrid way of doing it where you have import MyLib = require('mylib') and why is this needed for this situation? I am having a hard time understanding the nuances between all these methods.

UPDATE

I tried installing the winston-graylog2 library and use it and I get the exact same error! FYI I am using the latest version of TypeScript (v3.7.5). I have a feeling this is related to my local development, but I get the error both in VS Code (using TS Server extension) and when doing a tsc build from CLI directly.


问:
Return not killing recursive function
I have the bit of code that searches the entire computer for a file and once found, should return that file. The problem is in the second function, the recursive one. Once the file is found, it should return, which it does, but for some reason, even after returning the value, it continues the recursive search.

I don't get it. I'd still consider myself new to programming so please explain in detail if you see what I'm doing wrong.

```<code>public string SearchDirectory(string dir, string fileName)
{
    string foundDir = "";
    bool fileFound = false;
    // Gets all files from directory and creates list of matches to fileName
    try
    {
        foreach (string match in Directory.GetFiles(dir, fileName))
        {
            // Returns the first found match as a path and breaks loop
            Console.WriteLine("Checked path: " + dir + ".");
            if (File.Exists(dir + @"\" + fileName))
            {
                Console.WriteLine("FOUND!!");
                fileFound = true;
                foundDir = dir;
                break;
            }
            if (fileFound == true)
            {
                break;
            }
        }
    }
    catch
    {
        Console.WriteLine("Access to path: " + dir + " denied.");
    }

    // If fileName isn't found in directory, it searches each new directory
    // The last directory it will check is the last one in the original directory
    if (fileFound == false)
    {
        try
        {
            foreach (string newDirectory in Directory.GetDirectories(dir))
            {
                Console.WriteLine("Checked path: " + dir + ".");
                SearchDirectory(newDirectory, fileName);
            }
        }
        catch
        {
            Console.WriteLine("Access to path: " + dir + " denied.");
        }
        // fileName does not exist in starting directory
    }
    else
    {
        return foundDir;
    }
    return "";
}
</code>```

答:
Your recursive call is ignoring the returned value.  You should instead check to see if it found something so you can stop searching more sub-directories.</p>

```<code>foreach (string newDirectory in Directory.GetDirectories(dir))
{
    Console.WriteLine("Checked path: " + dir + ".");
    var result = SearchDirectory(newDirectory, fileName);
    if(result != "") return result;
}
</code>```

Title: Return not killing recursive function

Body:
I have the bit of code that searches the entire computer for a file and once found, should return that file. The problem is in the second function, the recursive one. Once the file is found, it should return, which it does, but for some reason, even after returning the value, it continues the recursive search.

I don't get it. I'd still consider myself new to programming so please explain in detail if you see what I'm doing wrong.

public string SearchDirectory(string dir, string fileName)
{
    string foundDir = "";
    bool fileFound = false;
    // Gets all files from directory and creates list of matches to fileName
    try
    {
        foreach (string match in Directory.GetFiles(dir, fileName))
        {
            // Returns the first found match as a path and breaks loop
            Console.WriteLine("Checked path: " + dir + ".");
            if (File.Exists(dir + @"\" + fileName))
            {
                Console.WriteLine("FOUND!!");
                fileFound = true;
                foundDir = dir;
                break;
            }
            if (fileFound == true)
            {
                break;
            }
        }
    }
    catch
    {
        Console.WriteLine("Access to path: " + dir + " denied.");
    }

    // If fileName isn't found in directory, it searches each new directory
    // The last directory it will check is the last one in the original directory
    if (fileFound == false)
    {
        try
        {
            foreach (string newDirectory in Directory.GetDirectories(dir))
            {
                Console.WriteLine("Checked path: " + dir + ".");
                SearchDirectory(newDirectory, fileName);
            }
        }
        catch
        {
            Console.WriteLine("Access to path: " + dir + " denied.");
        }
        // fileName does not exist in starting directory
    }
    else
    {
        return foundDir;
    }
    return "";
}

Body:
Your recursive call is ignoring the returned value.  You should instead check to see if it found something so you can stop searching more sub-directories.

foreach (string newDirectory in Directory.GetDirectories(dir))
{
    Console.WriteLine("Checked path: " + dir + ".");
    var result = SearchDirectory(newDirectory, fileName);
    if(result != "") return result;
}


问:
How do I rate limit the beta HTTP Api from AWS API Gateway
How do I rate limit the beta HTTP Api from AWS API Gateway</p>

答: beta HTTP api is pretty much non-functional atm, would stick to the original REST one for now</p>


问:
Python: Boto3, specifying attribute names for delete_item operation
The following code gives me an error:

dynamo_table.delete_item(Key={'segmentUuid': segment_id, 'value': value})
```

Error:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the DeleteItem operation: The provided key element does not match the schema

After doing some searching, I found that the issue is due to the sort key column being called value which is a reserved keyword in Dynamo.
Unfortunately, boto3 doesn't seem to allow me to specify that using ExpressionAttributeName argument since it's unsupported for Key in delete_item operation. Can someone please suggest what I could do to resolve this issue?

答:
value being a reserved word does make it confusing, but that error should have been

```<code>"Attribute name is a reserved keyword; reserved keyword: value"
</code>```

in that case.

Your error occurs when you are trying to match an item by fields which are not hash/sort keys. So for this particular delete_item to work, you need a GSI with

segmentUuid → hash key

value → sort key

Body:
The following code gives me an error:

dynamo_table.delete_item(Key={'segmentUuid': segment_id, 'value': value})

Error:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the DeleteItem operation: The provided key element does not match the schema

After doing some searching, I found that the issue is due to the sort key column being called value which is a reserved keyword in Dynamo.
Unfortunately, boto3 doesn't seem to allow me to specify that using ExpressionAttributeName argument since it's unsupported for Key in delete_item operation. Can someone please suggest what I could do to resolve this issue?

Body:
value being a reserved word does make it confusing, but that error should have been

"Attribute name is a reserved keyword; reserved keyword: value"

in that case.

Your error occurs when you are trying to match an item by fields which are not hash/sort keys. So for this particular delete_item to work, you need a GSI with

segmentUuid → hash key

value → sort key