问:
How to pass any selected option value from a view to a controller ASP.NET Core
This is my code. I want to select a option and pass the value in controller.

```<code>                    <div class="form-group">
                        <label asp-for="MobileNumber" class="control-label">Mobile Number</label>
                        <input asp-for="MobileNumber" class="form-control" />
                        <span asp-validation-for="MobileNumber" class="text-danger"></span>
                    </div>

                    <div class="form-group">
                         <label asp-for="Gender" for="inputState">Gender</label>
                          <select asp-for="Gender" id="inputState" class="form-control">
                            <option selected>Please Choose...</option>
                            <option>Male</option>
                            <option>Female</option>
                            <option>Other</option>
                          </select>
                    </div>
</code>```

This is Controller Action. I want to get select option value this action.

```<code>    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                model.Resolve(_scope);
                await model.UserCreate();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "User not create.");
            }
        }
        return View(model);
    }
</code>```

答:
Not sure about the full context of the CreateModel object, specifically what type is Gender, but I'm assuming it's string.
One thing that you are missing is defining values for the select options.

You need to do something similar to this in order to give a value for each option:

```<code><select asp-for="Gender" id="inputState" class="form-control">
    <option selected>Please Choose...</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Other">Other</option>
</select>
</code>```

Let me know if it helped!

Body:
This is my code. I want to select a option and pass the value in controller.

                        Mobile Number
                        <input asp-for="MobileNumber" class="form-control" />

                         Gender
                          <select asp-for="Gender" id="inputState" class="form-control">
                            <option selected>Please Choose...</option>
                            <option>Male</option>
                            <option>Female</option>
                            <option>Other</option>
                          </select>

This is Controller Action. I want to get select option value this action.

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                model.Resolve(_scope);
                await model.UserCreate();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "User not create.");
            }
        }
        return View(model);
    }

Body:
Not sure about the full context of the CreateModel object, specifically what type is Gender, but I'm assuming it's string.
One thing that you are missing is defining values for the select options.

You need to do something similar to this in order to give a value for each option:

<select asp-for="Gender" id="inputState" class="form-control">
    <option selected>Please Choose...</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Other">Other</option>
</select>

Let me know if it helped!


来源: stackexchange

问:
how to prevent websites from log you out due to inactivity
I am working with 5 different websites which have short session life, they log out in 10 - 15 mins of inactivity.
I came up with browser extension to do the jon for me.
and what I did so far:

reloading the page.

open another tab from the same host and close it automatically.

switch tabs to be active automatically ( like every 2 minutes one of thes websites becomes active).

those seems to be working, but they had very bad user experience.

also, reloading the page might cause losses of the work that I am doing.

I tried to make some requests on the background but these websites use alot of headers and cookies which seems to be very hard to figure out how to use them.

is there a better way to stop logging off due to inactivity or a proper way to figure out which headers and cookies should I attach with my request??

I really don't know which stack these websites are using but it seems that they have a high security standards.

答:
What I tend to do is once the "Are you still there?" message pops up, I right click, inspect, copy the selector, then do this in the console:

# paste your selector in this variable
selector = "#j_idt473 > div.modal-footer > a.btn.btn-primary.btn-sm"
document.querySelector(selector).click()
```

If that works, I then put it in a intervalID = window.setInterval(callback, milliseconds) call. I stop the loop with window.clearInterval(intervalID) if needed.

Not sure if you'd consider a realtime hack, this is StackOverflow after all.

ContentLicense: CC BY-SA 4.0

Body:
What I tend to do is once the "Are you still there?" message pops up, I right click, inspect, copy the selector, then do this in the console:

# paste your selector in this variable
selector = "#j_idt473 > div.modal-footer > a.btn.btn-primary.btn-sm"
document.querySelector(selector).click()

If that works, I then put it in a intervalID = window.setInterval(callback, milliseconds) call. I stop the loop with window.clearInterval(intervalID) if needed.

Not sure if you'd consider a realtime hack, this is StackOverflow after all.


问:
How do I make sidebar automatically disappear once a menu item clicked

I implemented a some Sidebar code and would like the sidebar to automatically close once an item is clicked. Currently have to click the 'X' to hide sidebar.  Below is the existing code for the Sidebar and Sidebar sub-menu.

Probably a one line fix if you know what you are doing, but I am new to React, so any help would be appreciated.

...

```<code>import React, { useState } from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import { SidebarData } from './SidebarData';
import SubMenu from './SubMenu';
import { IconContext } from 'react-icons/lib';

const Nav = styled.div`
  // background: #15171c;
  background: black;
  height: 60px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
`;

const NavIcon = styled(Link)`
  margin-left: 2rem;
  font-size: 2rem;
  height: 60px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
`;
//  background: #15171c;

const SidebarNav = styled.nav`
  background: #15171c;
  width: 250px;
  height: 150vh;
  display: flex;
  justify-content: center;
  position: fixed;
  top: 0;
  left: ${({ sidebar }) => (sidebar ? '0' : '-100%')};
  transition: 350ms;
  z-index: 10;
`;

const SidebarWrap = styled.div`
  width: 100%;
`;

const Sidebar = () => {
  const [sidebar, setSidebar] = useState(false);

  const showSidebar = () => setSidebar(!sidebar);

  return (
    <>
      <IconContext.Provider value={{ color: '#fff' }}>

        <Nav>
          <NavIcon to='#'>
            <FaIcons.FaBars onClick={showSidebar} />
          </NavIcon>
        </Nav>
        <SidebarNav sidebar={sidebar}>
          <SidebarWrap>
            <NavIcon to='#'>
              <AiIcons.AiOutlineClose onClick={showSidebar} />
            </NavIcon>
            {SidebarData.map((item, index) => {
              return <SubMenu item={item} key={index} />;
            })}
          </SidebarWrap>
        </SidebarNav>
      </IconContext.Provider>
    </>
  );
};

export default Sidebar;

import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';

const SidebarLink = styled(Link)`
  display: flex;
  color: #e1e9fc;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  list-style: none;
  height: 40px;
  text-decoration: none;
  font-size: 18px;

  //#c6c8cf
  //#252831
  &:hover {
    background: #c6c8cf;
    border-left: 4px solid #632ce4;
    cursor: pointer;
  }
`;

const SidebarLabel = styled.span`
  margin-left: 16px;
`;

const DropdownLink = styled(Link)`
  background: #414757;
  height: 40px;
  padding-left: 3rem;
  display: flex;
  align-items: center;
  text-decoration: none;
  color: #f5f5f5;
  font-size: 18px;

//  background: #632ce4;

  &:hover {
    background: #d9dbd5;
    cursor: pointer;
  }
`;

const SubMenu = ({ item }) => {
  const [subnav, setSubnav] = useState(false);

  const showSubnav = () => setSubnav(!subnav);

  return (
    <>
      <SidebarLink to={item.path} onClick={item.subNav && showSubnav}>
        <div>
          {item.icon}
          <SidebarLabel>{item.title}</SidebarLabel>
        </div>
        <div>
          {item.subNav && subnav
            ? item.iconOpened
            : item.subNav
            ? item.iconClosed
            : null}
        </div>
      </SidebarLink>
      {subnav &&
        item.subNav.map((item, index) => {
          return (
            <DropdownLink to={item.path} key={index}>
              {item.icon}
              <SidebarLabel>{item.title}</SidebarLabel>
            </DropdownLink>
          );
        })}
    </>
  );
};

export default SubMenu;

import React from 'react';
// import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import * as IoIcons from 'react-icons/io';
import * as RiIcons from 'react-icons/ri';
import * as FaIcons from 'react-icons/fa';

export const SidebarData = [
  {
    title: 'Login',
    path: '/login',
    icon: <AiIcons.AiOutlineLogin />,
  },
  {
    title: 'Site Master',
    path: '/list-sitemaster',
    icon: <FaIcons.FaBroadcastTower />,
  },
  {
    title: 'Site Report Cards',
    path: '/sitereportcardmaster',
    icon: <IoIcons.IoIosPaper />,

  },
  {
    title: 'Report Card Master',
    path: '/reportcardmaster',
    icon: <IoIcons.IoIosPaper />
  },
  {
    title: 'Categories',
    path: '/categories',
    icon: <IoIcons.IoIosClipboard />,

    iconClosed: <RiIcons.RiArrowDownSFill />,
    iconOpened: <RiIcons.RiArrowUpSFill />,

    subNav: [
      {
        title: 'Asset Type',
        path: '/assettype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Asset Sub Type',
        path: '/assetsubtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Document Type',
        path: '/documenttype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Document Sub Type',
        path: '/documentsubtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Report Card Category',
        path: '/reportcarddetailcategory',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Contact Detail Type',
        path: '/contactdetailtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Lighting Type',
        path: '/lightingtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      }
    ]
  },
  {
    title: 'Company Master',
    path: '/cpymaster-toplevel',
    icon: <AiIcons.AiFillHome />,
    iconClosed: <RiIcons.RiArrowDownSFill />,
    iconOpened: <RiIcons.RiArrowUpSFill />,

    subNav: [
      {
        title: 'CompanyMaster',
        path: '/cpymaster',
        icon: <AiIcons.AiFillHome />,
        cName: 'sub-nav'
      },
      {
        title: 'Users',
        path: '/users',
        icon: <IoIcons.IoIosPerson />,
        cName: 'sub-nav'
      },
      {
        title: 'Contacts',
        path: '/contactmaster',
        icon: <IoIcons.IoIosPeople />,
        cName: 'sub-nav'
      }
    ]
  },
  {
    title: 'My Profile',
    path: '/add-usersmall',
    icon: <AiIcons.AiOutlineUser/>,
  },
  {
    title: 'PDF',
    path: '/pdfcomponent',
    icon: <AiIcons.AiOutlineUser/>,
  },
  {
    title: 'Users PageSort Test',
    path: '/userstable',
    icon: <AiIcons.AiOutlineUser/>,
  },
  {
    title: 'Logout',
    path: '/logout',
    icon: <AiIcons.AiOutlineLogin />,
  }
];
</code>```

...

答:
You have a state for the sidebar in

```<code>const Sidebar = () => {
  const [sidebar, setSidebar] = useState(false);

  const showSidebar = () => setSidebar(!sidebar);
...
</code>```

If I'm not wrong, you close it in

```<code> <AiIcons.AiOutlineClose onClick={showSidebar} />
</code>```

You can pass down that showSidebar function to the link components, somthing like

```<code><SubMenu item={item} key={index} toggleSidebar={showSidebar}/>
</code>```

(Also, avoid using index as key)
Receiving the funtion in the SubMenu component

```<code>const SubMenu = ({ item,toggleSidebar }) => {
</code>```

thus, you are able to use it in the link

Body:
I implemented a some Sidebar code and would like the sidebar to automatically close once an item is clicked. Currently have to click the 'X' to hide sidebar.  Below is the existing code for the Sidebar and Sidebar sub-menu.

Probably a one line fix if you know what you are doing, but I am new to React, so any help would be appreciated.

...

import React, { useState } from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import { SidebarData } from './SidebarData';
import SubMenu from './SubMenu';
import { IconContext } from 'react-icons/lib';

const Nav = styled.div`
  // background: #15171c;
  background: black;
  height: 60px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
`;

const NavIcon = styled(Link)`
  margin-left: 2rem;
  font-size: 2rem;
  height: 60px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
`;
//  background: #15171c;

const SidebarNav = styled.nav`
  background: #15171c;
  width: 250px;
  height: 150vh;
  display: flex;
  justify-content: center;
  position: fixed;
  top: 0;
  left: ${({ sidebar }) => (sidebar ? '0' : '-100%')};
  transition: 350ms;
  z-index: 10;
`;

const SidebarWrap = styled.div`
  width: 100%;
`;

const Sidebar = () => {
  const [sidebar, setSidebar] = useState(false);

  const showSidebar = () => setSidebar(!sidebar);

  return (
    <>
      <IconContext.Provider value={{ color: '#fff' }}>

          <NavIcon to='#'>
            <FaIcons.FaBars onClick={showSidebar} />
          </NavIcon>

        <SidebarNav sidebar={sidebar}>
          <SidebarWrap>
            <NavIcon to='#'>
              <AiIcons.AiOutlineClose onClick={showSidebar} />
            </NavIcon>
            {SidebarData.map((item, index) => {
              return <SubMenu item={item} key={index} />;
            })}
          </SidebarWrap>
        </SidebarNav>
      </IconContext.Provider>
    </>
  );
};

export default Sidebar;

import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';

const SidebarLink = styled(Link)`
  display: flex;
  color: #e1e9fc;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  list-style: none;
  height: 40px;
  text-decoration: none;
  font-size: 18px;

  //#c6c8cf
  //#252831
  &:hover {
    background: #c6c8cf;
    border-left: 4px solid #632ce4;
    cursor: pointer;
  }
`;

const SidebarLabel = styled.span`
  margin-left: 16px;
`;

const DropdownLink = styled(Link)`
  background: #414757;
  height: 40px;
  padding-left: 3rem;
  display: flex;
  align-items: center;
  text-decoration: none;
  color: #f5f5f5;
  font-size: 18px;

//  background: #632ce4;

  &:hover {
    background: #d9dbd5;
    cursor: pointer;
  }
`;

const SubMenu = ({ item }) => {
  const [subnav, setSubnav] = useState(false);

  const showSubnav = () => setSubnav(!subnav);

  return (
    <>
      <SidebarLink to={item.path} onClick={item.subNav && showSubnav}>

          {item.icon}
          <SidebarLabel>{item.title}</SidebarLabel>

          {item.subNav && subnav
            ? item.iconOpened
            : item.subNav
            ? item.iconClosed
            : null}

      </SidebarLink>
      {subnav &&
        item.subNav.map((item, index) => {
          return (
            <DropdownLink to={item.path} key={index}>
              {item.icon}
              <SidebarLabel>{item.title}</SidebarLabel>
            </DropdownLink>
          );
        })}
    </>
  );
};

export default SubMenu;

import React from 'react';
// import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import * as IoIcons from 'react-icons/io';
import * as RiIcons from 'react-icons/ri';
import * as FaIcons from 'react-icons/fa';

export const SidebarData = [
  {
    title: 'Login',
    path: '/login',
    icon: <AiIcons.AiOutlineLogin />,
  },
  {
    title: 'Site Master',
    path: '/list-sitemaster',
    icon: <FaIcons.FaBroadcastTower />,
  },
  {
    title: 'Site Report Cards',
    path: '/sitereportcardmaster',
    icon: <IoIcons.IoIosPaper />,

  },
  {
    title: 'Report Card Master',
    path: '/reportcardmaster',
    icon: <IoIcons.IoIosPaper />
  },
  {
    title: 'Categories',
    path: '/categories',
    icon: <IoIcons.IoIosClipboard />,

    iconClosed: <RiIcons.RiArrowDownSFill />,
    iconOpened: <RiIcons.RiArrowUpSFill />,

    subNav: [
      {
        title: 'Asset Type',
        path: '/assettype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Asset Sub Type',
        path: '/assetsubtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Document Type',
        path: '/documenttype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Document Sub Type',
        path: '/documentsubtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Report Card Category',
        path: '/reportcarddetailcategory',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Contact Detail Type',
        path: '/contactdetailtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      },
      {
        title: 'Lighting Type',
        path: '/lightingtype',
        icon: <IoIcons.IoIosPaper />,
        cName: 'sub-nav'
      }
    ]
  },
  {
    title: 'Company Master',
    path: '/cpymaster-toplevel',
    icon: <AiIcons.AiFillHome />,
    iconClosed: <RiIcons.RiArrowDownSFill />,
    iconOpened: <RiIcons.RiArrowUpSFill />,

    subNav: [
      {
        title: 'CompanyMaster',
        path: '/cpymaster',
        icon: <AiIcons.AiFillHome />,
        cName: 'sub-nav'
      },
      {
        title: 'Users',
        path: '/users',
        icon: <IoIcons.IoIosPerson />,
        cName: 'sub-nav'
      },
      {
        title: 'Contacts',
        path: '/contactmaster',
        icon: <IoIcons.IoIosPeople />,
        cName: 'sub-nav'
      }
    ]
  },
  {
    title: 'My Profile',
    path: '/add-usersmall',
    icon: <AiIcons.AiOutlineUser/>,
  },
  {
    title: 'PDF',
    path: '/pdfcomponent',
    icon: <AiIcons.AiOutlineUser/>,
  },
  {
    title: 'Users PageSort Test',
    path: '/userstable',
    icon: <AiIcons.AiOutlineUser/>,
  },
  {
    title: 'Logout',
    path: '/logout',
    icon: <AiIcons.AiOutlineLogin />,
  }
];

...

Body:
You have a state for the sidebar in

const Sidebar = () => {
  const [sidebar, setSidebar] = useState(false);

  const showSidebar = () => setSidebar(!sidebar);
...

If I'm not wrong, you close it in

 <AiIcons.AiOutlineClose onClick={showSidebar} />

You can pass down that showSidebar function to the link components, somthing like

<SubMenu item={item} key={index} toggleSidebar={showSidebar}/>

(Also, avoid using index as key)
Receiving the funtion in the SubMenu component

const SubMenu = ({ item,toggleSidebar }) => {

thus, you are able to use it in the link


问:
sum() to remove bracket in a double list
I just saw someone wrote this below and got confused why sum() could be used to remove the bracket from another list:

```<code>pwd = [['x'], ['y'], ['z']]

a = sum(pwd, [])
print(a)          // ['x', 'y', 'z']
</code>```

By looking up sum() definition…

sum(iterable, /, start=0)`

iterable can be anything, list, tuples or dictionaries, but most importantly it should be numeric.

start is added to the sum of numbers in the iterable.
If start is not given in the syntax, it is assumed to be 0.

How does an empty list as start argument of sum() remove the list from another list? This puzzles me…could anyone demystify this?

答:
Python doesn't know what addition means. It relies on object methods to do the work. + is really a call to an object's __add__ method.
Integers add, but lists extend - at least when adding another list.

sum adds iterated values to the start object. When you make start a list, it sums using the list addition rules. In your case, you start with an empty list, and then each iterated value, also a list, is added - extending the list. Its the same as

```<code>>>> a = []
>>> pwd = [['x'], ['y'], ['z']]
>>> for val in pwd:
...     print(val)
...     a = a + val
...
['x']
['y']
['z']
>>> a
['x', 'y', 'z']
</code>```

This is part of the dynamic nature of python and is leveraged in many ways in various packages. numpy and pandas broadcast operations across entire matricies, for example. pathlib overrides division to join paths.

One could argue that any class you implement should prefer overriding the existing "magic methods" that implement python operators over their own methods. Why would a queue have a put when it can implement +=? Okay, there are reasons why that would be a bad choice, too! That's design work.

Body:
I just saw someone wrote this below and got confused why sum() could be used to remove the bracket from another list:

pwd = [['x'], ['y'], ['z']]

a = sum(pwd, [])
print(a)          // ['x', 'y', 'z']

By looking up sum() definition…

sum(iterable, /, start=0)`

iterable can be anything, list, tuples or dictionaries, but most importantly it should be numeric.

start is added to the sum of numbers in the iterable.
If start is not given in the syntax, it is assumed to be 0.

How does an empty list as start argument of sum() remove the list from another list? This puzzles me…could anyone demystify this?

Body:
Python doesn't know what addition means. It relies on object methods to do the work. + is really a call to an object's __add__ method.
Integers add, but lists extend - at least when adding another list.

sum adds iterated values to the start object. When you make start a list, it sums using the list addition rules. In your case, you start with an empty list, and then each iterated value, also a list, is added - extending the list. Its the same as

>>> a = []
>>> pwd = [['x'], ['y'], ['z']]
>>> for val in pwd:
...     print(val)
...     a = a + val
...
['x']
['y']
['z']
>>> a
['x', 'y', 'z']

This is part of the dynamic nature of python and is leveraged in many ways in various packages. numpy and pandas broadcast operations across entire matricies, for example. pathlib overrides division to join paths.

One could argue that any class you implement should prefer overriding the existing "magic methods" that implement python operators over their own methods. Why would a queue have a put when it can implement +=? Okay, there are reasons why that would be a bad choice, too! That's design work.


问:
How to automap a backend-agnostic Base in SQLAlchemy
I am trying to take a simple database schema in Oracle and migrate it to a mssql database. There are other ways I can do this but my first thought was to utilize SQLAlchemy's automap and create_all functionality to do it pretty much instantaneously.

Unfortunately when I attempt to do so I run into some conversion errors:

Input:

```<code>from sqlalchemy.ext.automap import automap_base
from custom_connections import connect_to_oracle, connect_to_mssql

Base = automap_base()
oracle_engine = connect_to_oracle()
mssql_engine = connect_to_mssql()

Base.prepare(oracle_engine, reflect=True, schema = ‘ORACLE_MAIN_DB’)

Base.metadata.create_all(mssql_engine)
</code>```

(Note that the connect_to functions are custom functions which return sqlalchemy engines. Currently they just return engines with base settings.)

Output:

```<code>CompileError: (in table 'acct', column 'acctnbr'): Compiler <sqlalchemy.dialects.mssql.base.MSTypeCompiler object at 0x00000268E8FF6DA0> can't render element of type <class 'sqlalchemy.dialects.oracle.base.NUMBER'>
</code>```

The issue is that while Sqlalchemy is converting most types to sqlalchemy types when mapping the Base, it doesn't do the same with Oracle NUMBER types. I attempted a similar trick using alembic autogeneration off the automapped Base, but the Oracle NUMBER types caused issues there as well.

Given all the power behind it, I would have thought Sqlalchemy would be able to handle this without any issues. Is there a technique or setting I could use when running this code which would cause it to convert all types to their Sqlalchemy equivalent when mapping the base instead of just most types?

答:
This is described in the SQLAlchemy docs about reflection:</p>
```<code>from sqlalchemy import MetaData, Table, create_engine
from sqlalchemy import event

mysql_engine = create_engine("mysql://scott:tiger@localhost/test")
metadata_obj = MetaData()
my_mysql_table = Table("my_table", metadata_obj, autoload_with=mysql_engine)
# my_table should already exist in your db, this is the table you want to convert

@event.listens_for(metadata_obj, "column_reflect")
def genericize_datatypes(inspector, tablename, column_dict):
    column_dict["type"] = column_dict["type"].as_generic()

my_generic_table = Table("my_table", metadata_obj, autoload_with=mysql_engine)
# generic table will be a generic version of my_table
sqlite_eng = create_engine("sqlite:///test.db", echo=True)\
my_generic_table.create(sqlite_eng)
</code>```

Body:
I am trying to take a simple database schema in Oracle and migrate it to a mssql database. There are other ways I can do this but my first thought was to utilize SQLAlchemy's automap and create_all functionality to do it pretty much instantaneously.

Unfortunately when I attempt to do so I run into some conversion errors:

Input:

from sqlalchemy.ext.automap import automap_base
from custom_connections import connect_to_oracle, connect_to_mssql

Base = automap_base()
oracle_engine = connect_to_oracle()
mssql_engine = connect_to_mssql()

Base.prepare(oracle_engine, reflect=True, schema = ‘ORACLE_MAIN_DB’)

Base.metadata.create_all(mssql_engine)

(Note that the connect_to functions are custom functions which return sqlalchemy engines. Currently they just return engines with base settings.)

Output:

CompileError: (in table 'acct', column 'acctnbr'): Compiler <sqlalchemy.dialects.mssql.base.MSTypeCompiler object at 0x00000268E8FF6DA0> can't render element of type <class 'sqlalchemy.dialects.oracle.base.NUMBER'>

The issue is that while Sqlalchemy is converting most types to sqlalchemy types when mapping the Base, it doesn't do the same with Oracle NUMBER types. I attempted a similar trick using alembic autogeneration off the automapped Base, but the Oracle NUMBER types caused issues there as well.

Given all the power behind it, I would have thought Sqlalchemy would be able to handle this without any issues. Is there a technique or setting I could use when running this code which would cause it to convert all types to their Sqlalchemy equivalent when mapping the base instead of just most types?

Body:
This is described in the SQLAlchemy docs about reflection:

from sqlalchemy import MetaData, Table, create_engine
from sqlalchemy import event

mysql_engine = create_engine("mysql://scott:tiger@localhost/test")
metadata_obj = MetaData()
my_mysql_table = Table("my_table", metadata_obj, autoload_with=mysql_engine)
# my_table should already exist in your db, this is the table you want to convert

@event.listens_for(metadata_obj, "column_reflect")
def genericize_datatypes(inspector, tablename, column_dict):
    column_dict["type"] = column_dict["type"].as_generic()

my_generic_table = Table("my_table", metadata_obj, autoload_with=mysql_engine)
# generic table will be a generic version of my_table
sqlite_eng = create_engine("sqlite:///test.db", echo=True)\
my_generic_table.create(sqlite_eng)


问:
Create a Dataframe of Difference scores between users for multiple variables
I have a large dataframe with users scores on a number of language dimensions, with a simplified version looking like the code below (I have included a dput replication data at the bottom of the post)

```<code>    user             Authentic   Analytic    Clout       Tone
2   Adams_Alma       0.05738848  0.7511374  0.3675847   0.95387755
3   Aguilar_Pete     0.24302974  0.7725205  0.3873588   0.79183673
4   Allred_Colin     0.11245353  0.7770701  0.7482345   0.58346939
5   Auchincloss_Jake 0.96119888  0.8020928  0.2673023   0.49765306
6   Axne_Cynthia     0.12500000  0.8644222  0.4918785   0.97112245
</code>```

Using this data, I want to create a dataframe in which each row is the difference score of between a pair of users in the dataset, as seen below (though the actual dataframe is much larger).

```<code>    from        to                 diff_Authentic   diff_Analytic  diff_Clout  diff_Tone
1   Adams_Alma  Aguilar_Pete       0.9802260        0.123456       0.123456    0.123456
2   Adams_Alma  Allred_Colin       0.6193503        0.123456       0.123456    0.123456
3   Adams_Alma  Auchincloss_Jake   0.8997175        0.123456       0.123456    0.123456
4   Adams_Alma  Axne_Cynthia       0.8757062        0.123456       0.123456    0.123456
5   Adams_Alma  Baldwin_Tammy      0.9406780        0.123456       0.123456    0.123456
6   Adams_Alma  Barragán_Nanette   0.8495763        0.123456       0.123456    0.123456
7   Adams_Alma  Bass_Karen         0.8234463        0.123456       0.123456    0.123456
8   Adams_Alma  Beatty_Joyce       0.9014831        0.123456       0.123456    0.123456
9   Adams_Alma  Bennet_Michael     0.5183616        0.123456       0.123456    0.123456
10  Adams_Alma  Bera_Ami           0.8223870        0.123456       0.123456    0.123456
</code>```

Using the code below, I am able to create a difference edgelist for one variable at a time, but my full dataframe has 90 variables I want differences for.

```<code>out <- with(norm_data, as.matrix(dist(setNames(norm_data$Authentic, norm_data$user))))
dif_g <- graph_from_adjacency_matrix (out, mode = 'undirected', weighted = TRUE)
dif_edge_list <- as_data_frame(dif_g, 'edges')
dif_edge_list$weight <- 1 - dif_edge_list$weight
</code>```

I would like to have a single dataframe that has the difference scores for each pair of users across all variables. I'm assuming a loop might be the solution, but I can't figure out how to do this. Any help would be greatly appreciated. Let me know if you need any more info.

Dput Data:

```<code>Show in New WindowClear OutputExpand/Collapse Output
structure(list(user = structure(1:50, .Label = c("Adams_Alma",
"Aguilar_Pete", "Allred_Colin", "Auchincloss_Jake", "Axne_Cynthia",
"Baldwin_Tammy", "Barragán_Nanette", "Bass_Karen", "Beatty_Joyce",
"Bennet_Michael", "Bera_Ami", "Beyer_Donald", "Bishop_Sanford",
"Blumenthal_Richard", "Blunt_Rochester_Lisa", "Bonamici_Suzanne",
"Booker_Cory", "Bourdeaux_Carolyn", "Bowman_Jamaal", "Boyle_Brendan",
"Brown_Anthony", "Brown_Sherrod", "Brownley_Julia", "Bush_Cori",
"Bustos_Cheri", "Butterfield_George", "Cantwell_Maria", "Carbajal_Salud",
"Cárdenas_Tony", "Cardin_Benjamin", "Carper_Thomas", "Carson_André",
"Cartwright_Matthew", "Case_Ed", "Casey_Robert", "Casten_Sean",
"Castor_Kathy", "Castro_Joaquin", "Chu_Judy", "Cicilline_David",
"Clark_Katherine", "Clarke_Yvette", "Cleaver_Emanuel", "Clyburn_James",
"Cohen_Steve", "Connolly_Gerald", "Coons_Christopher", "Cooper_Jim",
"Correa_J", "Cortez_Masto_Catherine", "Costa_Jim", "Courtney_Joe",
"Craig_Angie", "Crist_Charlie", "Crow_Jason", "Cuellar_Henry",
"Davids_Sharice", "Davis_Danny", "Dean_Madeleine", "DeFazio_Peter",
"DeGette_Diana", "DeLauro_Rosa", "DelBene_Suzan", "Delgado_Antonio",
"Demings_Val", "DeSaulnier_Mark", "Deutch_Theodore", "Dingell_Debbie",
"Doggett_Lloyd", "Doyle_Michael", "Duckworth_Tammy", "Durbin_Richard",
"Escobar_Veronica", "Eshoo_Anna", "Espaillat_Adriano", "Evans_Dwight",
"Feinstein_Dianne", "Fletcher_Lizzie", "Foster_Bill", "Frankel_Lois",
"Gallego_Ruben", "Garamendi_John", "García_Jesús", "Garcia_Sylvia",
"Golden_Jared", "Gomez_Jimmy", "Gonzalez_Vicente", "Gottheimer_Josh",
"Green_Al", "Grijalva_Raúl", "Harder_Josh", "Hassan_Margaret",
"Hayes_Jahana", "Heinrich_Martin", "Higgins_Brian", "Himes_James",
"Hirono_Mazie", "Horsford_Steven", "Houlahan_Chrissy", "Hoyer_Steny",
"Huffman_Jared", "Jackson_Lee_Sheila", "Jacobs_Sara", "Jayapal_Pramila",
"Jeffries_Hakeem", "Johnson_Eddie", "Johnson_Henry", "Kaptur_Marcy",
"Keating_William", "Kelly_Mark", "Kelly_Robin", "Khanna_Ro",
"Kildee_Daniel", "Kilmer_Derek", "Kim_Andy", "Kind_Ron", "Kirkpatrick_Ann",
"Klobuchar_Amy", "Krishnamoorthi_Raja", "Kuster_Ann", "Lamb_Conor",
"Langevin_James", "Larsen_Rick", "Larson_John", "Lawrence_Brenda",
"Lawson_Al", "Leahy_Patrick", "Lee_Barbara", "Lee_Susie", "Leger_Fernandez_Teresa",
"Levin_Andy", "Levin_Mike", "Lieu_Ted", "Lofgren_Zoe", "Lowenthal_Alan",
"Luján_Ben", "Luria_Elaine", "Lynch_Stephen", "Malinowski_Tom",
"Maloney_Carolyn", "Maloney_Sean", "Manchin_Joe", "Manning_Kathy",
"Markey_Edward", "Matsui_Doris", "McBath_Lucy", "McCollum_Betty",
"McEachin_A", "McGovern_James", "McNerney_Jerry", "Meeks_Gregory",
"Menendez_Robert", "Meng_Grace", "Merkley_Jeff", "Mfume_Kweisi",
"Moore_Gwen", "Morelle_Joseph", "Moulton_Seth", "Mrvan_Frank",
"Murphy_Stephanie", "Murray_Patty", "Nadler_Jerrold", "Napolitano_Grace",
"Neal_Richard", "Neguse_Joe", "Newman_Marie", "Norcross_Donald",
"Norton_Eleanor", "O_Halleran_Tom", "Ocasio_Cortez_Alexandria",
"Omar_Ilhan", "Ossoff_Jon", "Padilla_Alejandro", "Pallone_Frank",
"Panetta_Jimmy", "Pappas_Chris", "Pascrell_Bill", "Payne_Donald",
"Pelosi_Nancy", "Perlmutter_Ed", "Peters_Gary", "Peters_Scott",
"Phillips_Dean", "Pingree_Chellie", "Plaskett_Stacey", "Pocan_Mark",
"Porter_Katie", "Pressley_Ayanna", "Price_David", "Quigley_Mike",
"Raskin_Jamie", "Reed_John", "Rice_Kathleen", "Rosen_Jacky",
"Ross_Deborah", "Roybal_Allard_Lucille", "Ruiz_Raul", "Ruppersberger_C",
"Rush_Bobby", "Ryan_Tim", "Sablan_Gregorio", "Sánchez_Linda",
"Sarbanes_John", "Scanlon_Mary", "Schakowsky_Janice", "Schatz_Brian",
"Schiff_Adam", "Schneider_Bradley", "Schrader_Kurt", "Schrier_Kim",
"Schumer_Charles", "Scott_David", "Scott_Robert", "Sewell_Terri",
"Shaheen_Jeanne", "Shelby_Richard", "Sherman_Brad", "Sherrill_Mikie",
"Sinema_Kyrsten", "Sires_Albio", "Slotkin_Elissa", "Smith_Adam",
"Smith_Tina", "Soto_Darren", "Spanberger_Abigail", "Speier_Jackie",
"Stabenow_Debbie", "Stanton_Greg", "Stevens_Haley", "Strickland_Marilyn",
"Suozzi_Thomas", "Swalwell_Eric", "Takano_Mark", "Tester_Jon",
"Thompson_Bennie", "Thompson_Mike", "Titus_Dina", "Tlaib_Rashida",
"Tonko_Paul", "Torres_Norma", "Torres_Ritchie", "Trahan_Lori",
"Trone_David", "Underwood_Lauren", "user", "Van_Hollen_Chris",
"Vargas_Juan", "Veasey_Marc", "Vela_Filemon", "Velázquez_Nydia",
"Warner_Mark", "Warnock_Raphael", "Warren_Elizabeth", "Wasserman_Schultz_Debbie",
"Waters_Maxine", "Watson_Coleman_Bonnie", "Welch_Peter", "Wexton_Jennifer",
"Whitehouse_Sheldon", "Wild_Susan", "Williams_Nikema", "Wilson_Frederica",
"Wyden_Ron", "Yarmuth_John"), class = "factor"), Authentic = c(0.0573884758364312,
0.243029739776952, 0.112453531598513, 0.961198884758364, 0.125,
0.139869888475836, 0.131737918215613, 0.174024163568773, 0.115706319702602,
0.325046468401487, 0.223048327137546, 0.087592936802974, 0.133364312267658,
0.190985130111524, 0.21003717472119, 0.0422862453531598, 0.153113382899628,
0.263708178438662, 0.157295539033457, 0.328996282527881, 0.139637546468401,
0.48025092936803, 0.26974907063197, 0.378020446096654, 0.153113382899628,
0.454693308550186, 0.0820167286245353, 0.130576208178439, 0.33317843866171,
0.263243494423792, 0.197490706319703, 0.295074349442379, 0.251626394052045,
0.303671003717472, 0.180065055762082, 0.155204460966543, 0.10246282527881,
0.237453531598513, 0.132434944237918, 0.151022304832714, 0.10339219330855,
0.991635687732342, 0.185176579925651, 0.263475836431227, 0.0669144981412639,
0.143587360594796, 0.127788104089219, 0.212360594795539, 0.45817843866171,
0.054135687732342), Analytic = c(0.751137397634213, 0.772520473157416,
0.777070063694267, 0.802092811646951, 0.86442220200182, 0.75796178343949,
0.847133757961783, 0.873976342129208, 0.816196542311192, 0.801182893539581,
0.809827115559599, 0.695177434030937, 0.803457688808007, 0.726569608735214,
0.774795268425842, 0.843039126478617, 0.788898999090082, 0.773885350318471,
0.79936305732484, 0.78434940855323, 0.939945404913557, 0.772520473157416,
0.741128298453139, 0.736123748862602, 0.927206551410373, 0.673794358507734,
0.859872611464968, 0.763421292083712, 0.810282074613285, 0.871701546860782,
0.834849863512284, 0.786624203821656, 0.782984531392174, 1, 0.872611464968152,
0.748862602365787, 0.804367606915377, 0.79936305732484, 0.682893539581438,
0.761601455868971, 0.722929936305732, 0.767970882620564, 0.845313921747043,
0.79663330300273, 0.74294813466788, 0.840764331210191, 0.894904458598726,
0.787534121929026, 0.800272975432211, 0.883530482256597), Clout = c(0.367584745762712,
0.387358757062147, 0.748234463276836, 0.267302259887006, 0.491878531073446,
0.426906779661017, 0.518008474576271, 0.191031073446328, 0.466101694915254,
0.849223163841808, 0.545197740112994, 0.475988700564972, 0.548728813559322,
0.711511299435028, 0.538841807909604, 0.792372881355932, 0.49364406779661,
0.487641242937853, 0.64795197740113, 0.370409604519774, 0.771186440677966,
0.288488700564972, 0.211158192090395, 0.273658192090395, 0.420197740112994,
1, 0.531779661016949, 0.629237288135593, 0.646539548022599, 0.208686440677966,
0.189618644067797, 0.92090395480226, 0.632415254237288, 0.965042372881356,
0.34180790960452, 0.392302259887005, 0.604166666666666, 0.548375706214689,
0.401836158192091, 0.415254237288136, 0.364759887005649, 0.332980225988701,
0.354519774011299, 0.346398305084746, 0.52295197740113, 0.453389830508474,
0.777189265536723, 0.332980225988701, 0.436087570621469, 0.387358757062147
), Tone = c(0.953877551020408, 0.791836734693877, 0.583469387755102,
0.49765306122449, 0.971122448979592, 0.994183673469388, 0.626836734693878,
0.893061224489796, 0.34469387755102, 0.68530612244898, 0.970204081632653,
0.698265306122449, 0.959795918367347, 0.379183673469388, 0.988469387755102,
0.930408163265306, 0.0593877551020408, 0.744897959183674, 0.884387755102041,
0.803367346938776, 0.659285714285714, 0.422244897959184, 0.283571428571429,
0.252755102040816, 0.926530612244898, 0.988265306122449, 0.76469387755102,
0.525408163265306, 0.817040816326531, 0.891428571428571, 0.81265306122449,
0.451632653061224, 0.654285714285714, 0.727244897959184, 0.974591836734694,
0.467448979591837, 0.798775510204082, 0.501122448979592, 0.919795918367347,
0.744897959183674, 0.83234693877551, 0.931224489795918, 0.866326530612245,
0.448673469387755, 0.766530612244898, 0.326734693877551, 0.847959183673469,
0.685204081632653, 0.78765306122449, 0.847755102040816)), row.names = 2:51, class = "data.frame")
</code>```

答:
In order to avoid repetition and thus not using O(N^2), i would prefer using vectorized methods. We know that we need 1-2,1-3.. etc and these are the same as 2-1,3-1, upto the sign constant. We could do:</p>
```<code>index <- which(lower.tri(diag(nrow(df))), T)

a <- data.frame(user1 = df[index[,2],1],
      user2 = df[index[,1],1],
      diff = df[index[,2],-1] - df[index[,1],-1], row.names = NULL)

      user1            user2 diff.Authentic diff.Analytic  diff.Clout   diff.Tone
1 Adams_Alma     Aguilar_Pete    -0.18564126  -0.021383076 -0.01977401  0.16204082
2 Adams_Alma     Allred_Colin    -0.05506506  -0.025932666 -0.38064972  0.37040816
3 Adams_Alma Auchincloss_Jake    -0.90381041  -0.050955414  0.10028249  0.45622449
4 Adams_Alma     Axne_Cynthia    -0.06761152  -0.113284804 -0.12429379 -0.01724490
5 Adams_Alma    Baldwin_Tammy    -0.08248141  -0.006824386 -0.05932203 -0.04030612
6 Adams_Alma Barragán_Nanette    -0.07434944  -0.095996360 -0.15042373  0.32704082
</code>```

Body:
I have a large dataframe with users scores on a number of language dimensions, with a simplified version looking like the code below (I have included a dput replication data at the bottom of the post)

    user             Authentic   Analytic    Clout       Tone
2   Adams_Alma       0.05738848  0.7511374  0.3675847   0.95387755
3   Aguilar_Pete     0.24302974  0.7725205  0.3873588   0.79183673
4   Allred_Colin     0.11245353  0.7770701  0.7482345   0.58346939
5   Auchincloss_Jake 0.96119888  0.8020928  0.2673023   0.49765306
6   Axne_Cynthia     0.12500000  0.8644222  0.4918785   0.97112245

Using this data, I want to create a dataframe in which each row is the difference score of between a pair of users in the dataset, as seen below (though the actual dataframe is much larger).

    from        to                 diff_Authentic   diff_Analytic  diff_Clout  diff_Tone
1   Adams_Alma  Aguilar_Pete       0.9802260        0.123456       0.123456    0.123456
2   Adams_Alma  Allred_Colin       0.6193503        0.123456       0.123456    0.123456
3   Adams_Alma  Auchincloss_Jake   0.8997175        0.123456       0.123456    0.123456
4   Adams_Alma  Axne_Cynthia       0.8757062        0.123456       0.123456    0.123456
5   Adams_Alma  Baldwin_Tammy      0.9406780        0.123456       0.123456    0.123456
6   Adams_Alma  Barragán_Nanette   0.8495763        0.123456       0.123456    0.123456
7   Adams_Alma  Bass_Karen         0.8234463        0.123456       0.123456    0.123456
8   Adams_Alma  Beatty_Joyce       0.9014831        0.123456       0.123456    0.123456
9   Adams_Alma  Bennet_Michael     0.5183616        0.123456       0.123456    0.123456
10  Adams_Alma  Bera_Ami           0.8223870        0.123456       0.123456    0.123456

Using the code below, I am able to create a difference edgelist for one variable at a time, but my full dataframe has 90 variables I want differences for.

out <- with(norm_data, as.matrix(dist(setNames(norm_data$Authentic, norm_data$user))))
dif_g <- graph_from_adjacency_matrix (out, mode = 'undirected', weighted = TRUE)
dif_edge_list <- as_data_frame(dif_g, 'edges')
dif_edge_list$weight <- 1 - dif_edge_list$weight

I would like to have a single dataframe that has the difference scores for each pair of users across all variables. I'm assuming a loop might be the solution, but I can't figure out how to do this. Any help would be greatly appreciated. Let me know if you need any more info.

Dput Data:

Show in New WindowClear OutputExpand/Collapse Output
structure(list(user = structure(1:50, .Label = c("Adams_Alma",
"Aguilar_Pete", "Allred_Colin", "Auchincloss_Jake", "Axne_Cynthia",
"Baldwin_Tammy", "Barragán_Nanette", "Bass_Karen", "Beatty_Joyce",
"Bennet_Michael", "Bera_Ami", "Beyer_Donald", "Bishop_Sanford",
"Blumenthal_Richard", "Blunt_Rochester_Lisa", "Bonamici_Suzanne",
"Booker_Cory", "Bourdeaux_Carolyn", "Bowman_Jamaal", "Boyle_Brendan",
"Brown_Anthony", "Brown_Sherrod", "Brownley_Julia", "Bush_Cori",
"Bustos_Cheri", "Butterfield_George", "Cantwell_Maria", "Carbajal_Salud",
"Cárdenas_Tony", "Cardin_Benjamin", "Carper_Thomas", "Carson_André",
"Cartwright_Matthew", "Case_Ed", "Casey_Robert", "Casten_Sean",
"Castor_Kathy", "Castro_Joaquin", "Chu_Judy", "Cicilline_David",
"Clark_Katherine", "Clarke_Yvette", "Cleaver_Emanuel", "Clyburn_James",
"Cohen_Steve", "Connolly_Gerald", "Coons_Christopher", "Cooper_Jim",
"Correa_J", "Cortez_Masto_Catherine", "Costa_Jim", "Courtney_Joe",
"Craig_Angie", "Crist_Charlie", "Crow_Jason", "Cuellar_Henry",
"Davids_Sharice", "Davis_Danny", "Dean_Madeleine", "DeFazio_Peter",
"DeGette_Diana", "DeLauro_Rosa", "DelBene_Suzan", "Delgado_Antonio",
"Demings_Val", "DeSaulnier_Mark", "Deutch_Theodore", "Dingell_Debbie",
"Doggett_Lloyd", "Doyle_Michael", "Duckworth_Tammy", "Durbin_Richard",
"Escobar_Veronica", "Eshoo_Anna", "Espaillat_Adriano", "Evans_Dwight",
"Feinstein_Dianne", "Fletcher_Lizzie", "Foster_Bill", "Frankel_Lois",
"Gallego_Ruben", "Garamendi_John", "García_Jesús", "Garcia_Sylvia",
"Golden_Jared", "Gomez_Jimmy", "Gonzalez_Vicente", "Gottheimer_Josh",
"Green_Al", "Grijalva_Raúl", "Harder_Josh", "Hassan_Margaret",
"Hayes_Jahana", "Heinrich_Martin", "Higgins_Brian", "Himes_James",
"Hirono_Mazie", "Horsford_Steven", "Houlahan_Chrissy", "Hoyer_Steny",
"Huffman_Jared", "Jackson_Lee_Sheila", "Jacobs_Sara", "Jayapal_Pramila",
"Jeffries_Hakeem", "Johnson_Eddie", "Johnson_Henry", "Kaptur_Marcy",
"Keating_William", "Kelly_Mark", "Kelly_Robin", "Khanna_Ro",
"Kildee_Daniel", "Kilmer_Derek", "Kim_Andy", "Kind_Ron", "Kirkpatrick_Ann",
"Klobuchar_Amy", "Krishnamoorthi_Raja", "Kuster_Ann", "Lamb_Conor",
"Langevin_James", "Larsen_Rick", "Larson_John", "Lawrence_Brenda",
"Lawson_Al", "Leahy_Patrick", "Lee_Barbara", "Lee_Susie", "Leger_Fernandez_Teresa",
"Levin_Andy", "Levin_Mike", "Lieu_Ted", "Lofgren_Zoe", "Lowenthal_Alan",
"Luján_Ben", "Luria_Elaine", "Lynch_Stephen", "Malinowski_Tom",
"Maloney_Carolyn", "Maloney_Sean", "Manchin_Joe", "Manning_Kathy",
"Markey_Edward", "Matsui_Doris", "McBath_Lucy", "McCollum_Betty",
"McEachin_A", "McGovern_James", "McNerney_Jerry", "Meeks_Gregory",
"Menendez_Robert", "Meng_Grace", "Merkley_Jeff", "Mfume_Kweisi",
"Moore_Gwen", "Morelle_Joseph", "Moulton_Seth", "Mrvan_Frank",
"Murphy_Stephanie", "Murray_Patty", "Nadler_Jerrold", "Napolitano_Grace",
"Neal_Richard", "Neguse_Joe", "Newman_Marie", "Norcross_Donald",
"Norton_Eleanor", "O_Halleran_Tom", "Ocasio_Cortez_Alexandria",
"Omar_Ilhan", "Ossoff_Jon", "Padilla_Alejandro", "Pallone_Frank",
"Panetta_Jimmy", "Pappas_Chris", "Pascrell_Bill", "Payne_Donald",
"Pelosi_Nancy", "Perlmutter_Ed", "Peters_Gary", "Peters_Scott",
"Phillips_Dean", "Pingree_Chellie", "Plaskett_Stacey", "Pocan_Mark",
"Porter_Katie", "Pressley_Ayanna", "Price_David", "Quigley_Mike",
"Raskin_Jamie", "Reed_John", "Rice_Kathleen", "Rosen_Jacky",
"Ross_Deborah", "Roybal_Allard_Lucille", "Ruiz_Raul", "Ruppersberger_C",
"Rush_Bobby", "Ryan_Tim", "Sablan_Gregorio", "Sánchez_Linda",
"Sarbanes_John", "Scanlon_Mary", "Schakowsky_Janice", "Schatz_Brian",
"Schiff_Adam", "Schneider_Bradley", "Schrader_Kurt", "Schrier_Kim",
"Schumer_Charles", "Scott_David", "Scott_Robert", "Sewell_Terri",
"Shaheen_Jeanne", "Shelby_Richard", "Sherman_Brad", "Sherrill_Mikie",
"Sinema_Kyrsten", "Sires_Albio", "Slotkin_Elissa", "Smith_Adam",
"Smith_Tina", "Soto_Darren", "Spanberger_Abigail", "Speier_Jackie",
"Stabenow_Debbie", "Stanton_Greg", "Stevens_Haley", "Strickland_Marilyn",
"Suozzi_Thomas", "Swalwell_Eric", "Takano_Mark", "Tester_Jon",
"Thompson_Bennie", "Thompson_Mike", "Titus_Dina", "Tlaib_Rashida",
"Tonko_Paul", "Torres_Norma", "Torres_Ritchie", "Trahan_Lori",
"Trone_David", "Underwood_Lauren", "user", "Van_Hollen_Chris",
"Vargas_Juan", "Veasey_Marc", "Vela_Filemon", "Velázquez_Nydia",
"Warner_Mark", "Warnock_Raphael", "Warren_Elizabeth", "Wasserman_Schultz_Debbie",
"Waters_Maxine", "Watson_Coleman_Bonnie", "Welch_Peter", "Wexton_Jennifer",
"Whitehouse_Sheldon", "Wild_Susan", "Williams_Nikema", "Wilson_Frederica",
"Wyden_Ron", "Yarmuth_John"), class = "factor"), Authentic = c(0.0573884758364312,
0.243029739776952, 0.112453531598513, 0.961198884758364, 0.125,
0.139869888475836, 0.131737918215613, 0.174024163568773, 0.115706319702602,
0.325046468401487, 0.223048327137546, 0.087592936802974, 0.133364312267658,
0.190985130111524, 0.21003717472119, 0.0422862453531598, 0.153113382899628,
0.263708178438662, 0.157295539033457, 0.328996282527881, 0.139637546468401,
0.48025092936803, 0.26974907063197, 0.378020446096654, 0.153113382899628,
0.454693308550186, 0.0820167286245353, 0.130576208178439, 0.33317843866171,
0.263243494423792, 0.197490706319703, 0.295074349442379, 0.251626394052045,
0.303671003717472, 0.180065055762082, 0.155204460966543, 0.10246282527881,
0.237453531598513, 0.132434944237918, 0.151022304832714, 0.10339219330855,
0.991635687732342, 0.185176579925651, 0.263475836431227, 0.0669144981412639,
0.143587360594796, 0.127788104089219, 0.212360594795539, 0.45817843866171,
0.054135687732342), Analytic = c(0.751137397634213, 0.772520473157416,
0.777070063694267, 0.802092811646951, 0.86442220200182, 0.75796178343949,
0.847133757961783, 0.873976342129208, 0.816196542311192, 0.801182893539581,
0.809827115559599, 0.695177434030937, 0.803457688808007, 0.726569608735214,
0.774795268425842, 0.843039126478617, 0.788898999090082, 0.773885350318471,
0.79936305732484, 0.78434940855323, 0.939945404913557, 0.772520473157416,
0.741128298453139, 0.736123748862602, 0.927206551410373, 0.673794358507734,
0.859872611464968, 0.763421292083712, 0.810282074613285, 0.871701546860782,
0.834849863512284, 0.786624203821656, 0.782984531392174, 1, 0.872611464968152,
0.748862602365787, 0.804367606915377, 0.79936305732484, 0.682893539581438,
0.761601455868971, 0.722929936305732, 0.767970882620564, 0.845313921747043,
0.79663330300273, 0.74294813466788, 0.840764331210191, 0.894904458598726,
0.787534121929026, 0.800272975432211, 0.883530482256597), Clout = c(0.367584745762712,
0.387358757062147, 0.748234463276836, 0.267302259887006, 0.491878531073446,
0.426906779661017, 0.518008474576271, 0.191031073446328, 0.466101694915254,
0.849223163841808, 0.545197740112994, 0.475988700564972, 0.548728813559322,
0.711511299435028, 0.538841807909604, 0.792372881355932, 0.49364406779661,
0.487641242937853, 0.64795197740113, 0.370409604519774, 0.771186440677966,
0.288488700564972, 0.211158192090395, 0.273658192090395, 0.420197740112994,
1, 0.531779661016949, 0.629237288135593, 0.646539548022599, 0.208686440677966,
0.189618644067797, 0.92090395480226, 0.632415254237288, 0.965042372881356,
0.34180790960452, 0.392302259887005, 0.604166666666666, 0.548375706214689,
0.401836158192091, 0.415254237288136, 0.364759887005649, 0.332980225988701,
0.354519774011299, 0.346398305084746, 0.52295197740113, 0.453389830508474,
0.777189265536723, 0.332980225988701, 0.436087570621469, 0.387358757062147
), Tone = c(0.953877551020408, 0.791836734693877, 0.583469387755102,
0.49765306122449, 0.971122448979592, 0.994183673469388, 0.626836734693878,
0.893061224489796, 0.34469387755102, 0.68530612244898, 0.970204081632653,
0.698265306122449, 0.959795918367347, 0.379183673469388, 0.988469387755102,
0.930408163265306, 0.0593877551020408, 0.744897959183674, 0.884387755102041,
0.803367346938776, 0.659285714285714, 0.422244897959184, 0.283571428571429,
0.252755102040816, 0.926530612244898, 0.988265306122449, 0.76469387755102,
0.525408163265306, 0.817040816326531, 0.891428571428571, 0.81265306122449,
0.451632653061224, 0.654285714285714, 0.727244897959184, 0.974591836734694,
0.467448979591837, 0.798775510204082, 0.501122448979592, 0.919795918367347,
0.744897959183674, 0.83234693877551, 0.931224489795918, 0.866326530612245,
0.448673469387755, 0.766530612244898, 0.326734693877551, 0.847959183673469,
0.685204081632653, 0.78765306122449, 0.847755102040816)), row.names = 2:51, class = "data.frame")

Body:
In order to avoid repetition and thus not using O(N^2), i would prefer using vectorized methods. We know that we need 1-2,1-3.. etc and these are the same as 2-1,3-1, upto the sign constant. We could do:

index <- which(lower.tri(diag(nrow(df))), T)

a <- data.frame(user1 = df[index[,2],1],
      user2 = df[index[,1],1],
      diff = df[index[,2],-1] - df[index[,1],-1], row.names = NULL)

      user1            user2 diff.Authentic diff.Analytic  diff.Clout   diff.Tone
1 Adams_Alma     Aguilar_Pete    -0.18564126  -0.021383076 -0.01977401  0.16204082
2 Adams_Alma     Allred_Colin    -0.05506506  -0.025932666 -0.38064972  0.37040816
3 Adams_Alma Auchincloss_Jake    -0.90381041  -0.050955414  0.10028249  0.45622449
4 Adams_Alma     Axne_Cynthia    -0.06761152  -0.113284804 -0.12429379 -0.01724490
5 Adams_Alma    Baldwin_Tammy    -0.08248141  -0.006824386 -0.05932203 -0.04030612
6 Adams_Alma Barragán_Nanette    -0.07434944  -0.095996360 -0.15042373  0.32704082


问:
Extracting specific value from stderr_lines
This is my ansible script

```<code>- name: show1
  debug:
    msg: "{{response.stderr_lines}}"
</code>```

Here is the output

```<code>msg:
      - Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      - CustomJob [projects/123456/locations/us-central1/customJobs/112233445566] is submitted successfully.
      - ''
      - Your job is still active. You may view the status of your job with the command
      - ''
      - '  $ gcloud ai custom-jobs describe projects/123456/locations/us-central1/customJobs/112233445566'
      - ''
      - or continue streaming the logs with the command
      - ''
      - '  $ gcloud ai custom-jobs stream-logs projects/123456/locations/us-central1/customJobs/112233445566'
</code>```

Here I want to extract custom Job ID which is 112233445566

I used the select module like below

```<code>- name: show
  debug:
    msg: "{{train_custom_image_unmanaged_response.stderr_lines | select('search', 'describe') | list }}"
</code>```

and it gives me this output

```<code>msg:
  - '  $ gcloud ai custom-jobs describe projects/123456/locations/us-central1/customJobs/112233445566'
</code>```

But I just want the job id as specified above. Any idea about that ?

Thanks.

答:
You selected the line you are interested in. From that now you want to isolate the job id number in the end. You can do that using a regular expression like so:

```<code>- set_fact:
    line: "{{train_custom_image_unmanaged_response.stderr_lines | select('search', 'describe') | list }}"
- debug:
    msg: "{{ line | regex_search('.*/customJobs/(\\d+)', '\\1') }}"
</code>```

This will give you all the digits in the end of the line after /customJobs/. See https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#searching-strings-with-regular-expressions

Body:
This is my ansible script

- name: show1
  debug:
    msg: "{{response.stderr_lines}}"

Here is the output

msg:
      - Using endpoint [https://us-central1-aiplatform.googleapis.com/]
      - CustomJob [projects/123456/locations/us-central1/customJobs/112233445566] is submitted successfully.
      - ''
      - Your job is still active. You may view the status of your job with the command
      - ''
      - '  $ gcloud ai custom-jobs describe projects/123456/locations/us-central1/customJobs/112233445566'
      - ''
      - or continue streaming the logs with the command
      - ''
      - '  $ gcloud ai custom-jobs stream-logs projects/123456/locations/us-central1/customJobs/112233445566'

Here I want to extract custom Job ID which is 112233445566

I used the select module like below

- name: show
  debug:
    msg: "{{train_custom_image_unmanaged_response.stderr_lines | select('search', 'describe') | list }}"

and it gives me this output

msg:
  - '  $ gcloud ai custom-jobs describe projects/123456/locations/us-central1/customJobs/112233445566'

But I just want the job id as specified above. Any idea about that ?

Thanks.

Body:
You selected the line you are interested in. From that now you want to isolate the job id number in the end. You can do that using a regular expression like so:

- set_fact:
    line: "{{train_custom_image_unmanaged_response.stderr_lines | select('search', 'describe') | list }}"
- debug:
    msg: "{{ line | regex_search('.*/customJobs/(\\d+)', '\\1') }}"

This will give you all the digits in the end of the line after /customJobs/. See https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#searching-strings-with-regular-expressions


问:
Is there an accepted "name" for an event that simply reports back a "message"
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

```<code>var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();
</code>```

答:
Events are rather heavy weight for this king of task, especially if the frequency is high.
Even though I'm not directly answering your question, I want to give you an alternative to the event based solution:

The solution involves event streams using Rx Framework, and exposing and IObservable(T) instead of an event.

The solution goes like this: the DataImporter class will expose an IObservable<string> property, which internally is implemented by a Subject<T> which will be used to raise events.

```<code>public class DataImporter {
    private Subject<string> _StatusSubject = new Subject<string>();
    public IObservable<string> Status { get { return _StatusSubject; }
    ...
}
</code>```

How to raise an event in the stream:

```<code>void Foo()
{
    // Do some work
    _StatusSubject.OnNext("Some work has been done!")
}
</code>```

How to subscribe to the event stream:

```<code>var importer = new DataImporter();
importer.Status.Subscribe(message => Console.WriteLine(message));
</code>```

The advantage of using this approach is that you can use Linq operators to perform operations on the event stream in a very simple and straightforward manner.
Ex:

```<code>// Filter the stream of events, only to show short messages
importer.Status
        .Where (message => message.Length < 100)
        .Subscribe(message => Console.WriteLine(message));

// Add a timestamp to status messages
importer.Status
        .TimeStamp()
        .Subscribe(timestamped => Console.WriteLine(String.Format("Time:{0} Message: {1}", timestamped.Timestamp, timestamped.Value)));

// Buffer status messages each 5 secconds and return a list of messages
importer.Status
        .BufferWithTime(Timespan.FromSeconds(5))
        .Subscribe(list => Console.WriteLine(Strin.Join(new[] {Environment.Newline}, list));
</code>```

And many more ...

ContentLicense: CC BY-SA 3.0

Body:
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();

Body:
Events are rather heavy weight for this king of task, especially if the frequency is high.
Even though I'm not directly answering your question, I want to give you an alternative to the event based solution:

The solution involves event streams using Rx Framework, and exposing and IObservable(T) instead of an event.

The solution goes like this: the DataImporter class will expose an IObservable<string> property, which internally is implemented by a Subject<T> which will be used to raise events.

public class DataImporter {
    private Subject<string> _StatusSubject = new Subject<string>();
    public IObservable<string> Status { get { return _StatusSubject; }
    ...
}

How to raise an event in the stream:

void Foo()
{
    // Do some work
    _StatusSubject.OnNext("Some work has been done!")
}

How to subscribe to the event stream:

var importer = new DataImporter();
importer.Status.Subscribe(message => Console.WriteLine(message));

The advantage of using this approach is that you can use Linq operators to perform operations on the event stream in a very simple and straightforward manner.
Ex:

// Filter the stream of events, only to show short messages
importer.Status
        .Where (message => message.Length < 100)
        .Subscribe(message => Console.WriteLine(message));

// Add a timestamp to status messages
importer.Status
        .TimeStamp()
        .Subscribe(timestamped => Console.WriteLine(String.Format("Time:{0} Message: {1}", timestamped.Timestamp, timestamped.Value)));

// Buffer status messages each 5 secconds and return a list of messages
importer.Status
        .BufferWithTime(Timespan.FromSeconds(5))
        .Subscribe(list => Console.WriteLine(Strin.Join(new[] {Environment.Newline}, list));

And many more ...


问:
Pandas combine rows in groups to get rid of Nans
I want to do something similar to what pd.combine_first() does, but as a row-wise operation performed on a shared index. And to also add a new column in place of the old ones - while keeping the original_values of shared column names.

In this case the 'ts' column is one that I want to replace with time_now.

```<code>time_now = "2022-08-05"

row1 = {'unique_id':5,'ts': '2022-08-02','id2':2,'val':300, 'ffo1':55, 'debt':200}
row2 = {'unique_id':5,'ts': '2022-08-03' ,'id2':2, 'esg':True,'gov_rt':90}
row3 = {'unique_id':5,'ts': '2022-08-04','id2':2, 'rank':5,'buy_or_sell':'sell'}
df = pd.DataFrame([row1,row2,row3])

   unique_id          ts  id2    val  ffo1   debt   esg  gov_rt  rank  \
0          5  2022-08-02    2  300.0  55.0  200.0   NaN     NaN   NaN
1          5  2022-08-03    2    NaN   NaN    NaN  True    90.0   NaN
2          5  2022-08-04    2    NaN   NaN    NaN   NaN     NaN   5.0

  buy_or_sell
0         NaN
1         NaN
2        sell
</code>```

My desired output is below, using the new timestamp, but keeping the old ones based on their group index.

```<code>rows = [{'unique_id':5, 'ts':time_now ,'id2':2,'val':300, 'ffo1':55, 'debt':200,'esg':True,'gov_rt':90,'rank':5,'buy_or_sell':'sell', 'ts_1':'2022-08-02','ts_2':'2022-08-03', 'ts_3':'2022-08-04'}]
output = pd.DataFrame(rows)

   unique_id          ts  id2  val  ffo1  debt   esg  gov_rt  rank  \
0          5  2022-08-05    2  300    55   200  True      90     5

  buy_or_sell        ts_1        ts_2        ts_3
0        sell  2022-08-02  2022-08-03  2022-08-04
</code>```

The part below seems to work when run by itself. But I cannot get it to work inside of a function because of differences between index lengths.

```<code>

df2 = df.set_index('ts').stack().reset_index()
rows = dict(zip(df3['level_1'],df3[0]))
ts = df2['ts'].unique().tolist()
for cnt,value in enumerate(ts):
    rows['ts_{cnt}'] = value
# drop all rows
df2 = pd.DataFrame([rows])
df2['time'] = time
df2
</code>```

答:
The problem was that I forgot to put the dictionary into a list to create a records oriented dataframe. Additionally when using a similar function, the index might need to be dropped to be reset, as duplicated columns might be created.

I still wonder if there's a better way to do what I want, since it's kind of slow.

```<code>def func(df):
    df2 = df.set_index('ts').stack().reset_index()
    rows = dict(zip(df2['level_1'],df2[0]))
    ts = df2['ts'].unique().tolist()
    for cnt,value in enumerate(ts):
        rows[f'ts_{cnt}'] = value
    # drop all rows
    df2 = pd.DataFrame([rows])
    df2['time'] = time_now
    return df2

#run this
df.groupby('unique_id').apply(func)

</code>```

Body:
I want to do something similar to what pd.combine_first() does, but as a row-wise operation performed on a shared index. And to also add a new column in place of the old ones - while keeping the original_values of shared column names.

In this case the 'ts' column is one that I want to replace with time_now.

time_now = "2022-08-05"

row1 = {'unique_id':5,'ts': '2022-08-02','id2':2,'val':300, 'ffo1':55, 'debt':200}
row2 = {'unique_id':5,'ts': '2022-08-03' ,'id2':2, 'esg':True,'gov_rt':90}
row3 = {'unique_id':5,'ts': '2022-08-04','id2':2, 'rank':5,'buy_or_sell':'sell'}
df = pd.DataFrame([row1,row2,row3])

   unique_id          ts  id2    val  ffo1   debt   esg  gov_rt  rank  \
0          5  2022-08-02    2  300.0  55.0  200.0   NaN     NaN   NaN
1          5  2022-08-03    2    NaN   NaN    NaN  True    90.0   NaN
2          5  2022-08-04    2    NaN   NaN    NaN   NaN     NaN   5.0

  buy_or_sell
0         NaN
1         NaN
2        sell

My desired output is below, using the new timestamp, but keeping the old ones based on their group index.

rows = [{'unique_id':5, 'ts':time_now ,'id2':2,'val':300, 'ffo1':55, 'debt':200,'esg':True,'gov_rt':90,'rank':5,'buy_or_sell':'sell', 'ts_1':'2022-08-02','ts_2':'2022-08-03', 'ts_3':'2022-08-04'}]
output = pd.DataFrame(rows)

   unique_id          ts  id2  val  ffo1  debt   esg  gov_rt  rank  \
0          5  2022-08-05    2  300    55   200  True      90     5

  buy_or_sell        ts_1        ts_2        ts_3
0        sell  2022-08-02  2022-08-03  2022-08-04

The part below seems to work when run by itself. But I cannot get it to work inside of a function because of differences between index lengths.

df2 = df.set_index('ts').stack().reset_index()
rows = dict(zip(df3['level_1'],df3[0]))
ts = df2['ts'].unique().tolist()
for cnt,value in enumerate(ts):
    rows['ts_{cnt}'] = value
# drop all rows
df2 = pd.DataFrame([rows])
df2['time'] = time
df2

Body:
The problem was that I forgot to put the dictionary into a list to create a records oriented dataframe. Additionally when using a similar function, the index might need to be dropped to be reset, as duplicated columns might be created.

I still wonder if there's a better way to do what I want, since it's kind of slow.

def func(df):
    df2 = df.set_index('ts').stack().reset_index()
    rows = dict(zip(df2['level_1'],df2[0]))
    ts = df2['ts'].unique().tolist()
    for cnt,value in enumerate(ts):
        rows[f'ts_{cnt}'] = value
    # drop all rows
    df2 = pd.DataFrame([rows])
    df2['time'] = time_now
    return df2

#run this
df.groupby('unique_id').apply(func)


问:
VSCode practically unusable with slow intellisense without using extensions
VSCode on my Macbook Pro is practically unusable due to the intellisense being ungodly slow. This includes:

hovering to find typescript types, inferred and explicit types

autocomplete variables/functions/etc

autocomplete for using shortcuts

error lines shown in editor

For example, I will have an error show. Something like "variable not defined" or something simple. But then when I go to rewrite the code, it takes forever for VSCode to catch up. Sometimes I have to let it sit 40-50seconds before it catches up with my changes.
Hovering over typescript types is practically impossible at times and utterly useless. Below is a screenshot of the "lag" - changes were made, but it stuck like this for 30+ seconds:

It may be the specific project, because I can't recreate it for smaller projects. However, its only a 200k line project.

No specific extensions are slowing down VScode

I tried downgrading VsCode with no help

VSCODE VERSION: 1.47.3

答:
In my case, the issue was GitLens. I was able to isolate this issue by using the Command Palette (Control + Shift + P) to disable all extensions (this will not uninstall them), restarted Visual Studio, then checked if the issue persists.

The issue did indeed persist, so I went into the Extensions tab  and filtered by @disabled:

By reenabling my extensions one by one, I found GitLens to be the culprit.


问:
Is there any process to get the data directly from Cassandra to Aerospike?
Is there any process to get the data directly from Cassandra to Aerospike (without CSV file dump)?.</p>

答: I second the use of Spark.  You can build jobs to pull from each of your tables and work to parallelize your extraction and load, using the Spark framework and scalability patterns to your benefit.</p>


问:
Any way to do a local CVS proxy/server?
I have an online CVS repository that I need to check code into. However, the server is outside my control and is often down.

So, is there a way to set up some sort of local CVS server/proxy such that I can check my code into the local CVS server regularly and have the local CVS server batch commit the changes to the online CVS repo periodically?

The local repository could possibly run some other SCM system, if that was necessary to prevent conflict with CVS. Online commits could possibly be done manually, or via cron. I'm open to suggestions.

I guess that my main concern would be the problems faced in trying to set up some sort of repository 'hierarchy'.

PS: I'm running Linux all along the 'hierarchy'.

Edit: Found a similar item here.

答: This doesn't really answer the question, but it sounds like you need a distributed VCS system.</p>

OwnerDisplayName: sybreon

ContentLicense: CC BY-SA 2.5

Title: Any way to do a local CVS proxy/server?

LastEditorDisplayName: sybreon

OwnerDisplayName: mmyers


问:
iPhone: draw the objects along the curve
Good day, friends.

There is a task: to draw repeating objects (UIImageView and UILabel) along the curve (if more exactly, it's an arc).

What classes should be used for it?

答:
As an alternative to Android's Path, you can use either UIBezierPath or CGPath. The former is Objective-C, the later pure C. I recommend going with UIBezierPath as it's easier to use.

To rotate a view, use the transform property of UIView (see this question for an example on how to use it). But note that you then need to ignore the frame (it's undefined) and need to move the view by modifying the center instead.


问:
VueJS : Dynamically change the URL depending on filters
I have a project for which I use VueJS (2.x) for the frontend part.
I've made a component to do some filtering :

And I'd like to be able to change the URL according to the filters, so that I can share the URL and another user would land on the same search. At the stage of my screenshot, the URL should look like : my/long/url?username=test&email=@test. But I don't know how to achieve it.

Currently, when I add/remove a filter, I create a new URLSearchParams object that I commit to the vuex store and with a watch statement I query my backend again with the updated filters.

The thing is that my URL doesn't change, of course, because I do not pass by a this.$router.push(...) or whatever.

Maybe I started it wrong.

What is the good way of achieving this ? Knowing that routing to the same view with a new query part does trigger the error DuplicateNavigation...

Thanks in advance for your help :)

答:
I had achieved something similar to this by using the history.pushState
This basically allows you to modify your URL even if you are not using $router.push

You can follow the URL for more details
https://developer.mozilla.org/en-US/docs/Web/API/History/pushState


问:
Get URL from Open dialog of standard Swift document-based application
I am trying to extract the URL of the document a user has selected in the default "Open" dialogue of my document based macOS application. I understand, a fileWrapper is passed to the init method but is there a way of extracting the path/URL from said wrapper?

Thanks,

Lars

答:
The open panel gives you the URL if someone clicks the Open (OK) button. NSOpenPanel has a urls property that contains the URLs of the selected files.

SwiftUI file importers give you a URL if the open was successful.

```<code>.fileImporter(isPresented: $isImporting, allowedContentTypes:
    [.png, .jpeg, .tiff], onCompletion: { result in

    switch result {
        case .success(let url):
            // Use the URL to do something with the file.
        case .failure(let error):
            print(error.localizedDescription)
    }
})
</code>```

UPDATE

SwiftUI's document opening panel works differently than the file importer. You could try working with NSOpenPanel directly. The folllowing article should help:

Save And Open Panels In SwiftUI-Based macOS Apps

Body:
The open panel gives you the URL if someone clicks the Open (OK) button. NSOpenPanel has a urls property that contains the URLs of the selected files.

SwiftUI file importers give you a URL if the open was successful.

.fileImporter(isPresented: $isImporting, allowedContentTypes:
    [.png, .jpeg, .tiff], onCompletion: { result in

    switch result {
        case .success(let url):
            // Use the URL to do something with the file.
        case .failure(let error):
            print(error.localizedDescription)
    }
})

UPDATE

SwiftUI's document opening panel works differently than the file importer. You could try working with NSOpenPanel directly. The folllowing article should help:

Save And Open Panels In SwiftUI-Based macOS Apps


问:
Calculate weekly hours of operation in T-SQL from overlapping date/time data?
I am trying to calculate the number of hours of operation per week for each facility in a region. The part I am struggling with is that there are multiple programs each day that overlap which contribute to the total hours.

Here is a sample of the table I am working with:

location
program
date
start_time
end_time

a
1
09-22-21
14:45:00
15:45:00

a
2
09-22-21
15:30:00
16:30:00

b
88
09-22-21
10:45:00
12:45:00

b
89
09-22-21
10:45:00
14:45:00

I am hoping to get:

location
hours of operation

a
1.75

b
4

I've tried using SUM DATEDIFF with some WHERE statements but couldn't get them to work. What I have found is how to identify the overlapping ranges(Detect overlapping date ranges from the same table), but not how to sum the difference to get the desired outcome of total non-overlapping hours of operation.

答:
Here is an alternative method without having to round to nearest 15 minute increments:</p>
```<code>Declare @OperationSchedule table (
        ID       int Identity(1, 1)
      , Location char(1)
      , Program  int
      , OpDate   date
      , OpStart  time(0)
      , OpEnd    time(0)
        );

 Insert Into @OperationSchedule (Location, Program, OpDate, OpStart, OpEnd)
 Values ('a',  1, '09-22-21', '14:45:00', '15:45:00')
      , ('a',  2, '09-22-21', '15:30:00', '16:30:00')
      , ('b', 88, '09-22-21', '10:45:00', '12:45:00')
      , ('b', 89, '09-22-21', '10:45:00', '14:45:00')
      , ('c', 23, '09-22-21', '12:45:00', '13:45:00')
      , ('c', 24, '09-22-21', '14:45:00', '15:15:00')
      , ('3', 48, '09-22-21', '09:05:00', '13:55:00')
      , ('3', 49, '09-22-21', '14:25:00', '15:38:00')
      ;

   With overlappedData
     As (
 Select *
      , overlap_op = lead(os.OpStart, 1, os.OpEnd) Over(Partition By os.Location Order By os.ID)
   From @OperationSchedule os
        )
 Select od.Location
      , start_date = min(od.OpStart)
      , end_date = max(iif(od.OpEnd < od.overlap_op, od.OpEnd, od.overlap_op))
      , hours_of_operation = sum(datediff(minute, od.OpStart, iif(od.OpEnd < od.overlap_op, od.OpEnd, od.overlap_op)) / 60.0)
   From overlappedData                  od
  Group By
        od.Location;
</code>```

Body:
Here is an alternative method without having to round to nearest 15 minute increments:

Declare @OperationSchedule table (
        ID       int Identity(1, 1)
      , Location char(1)
      , Program  int
      , OpDate   date
      , OpStart  time(0)
      , OpEnd    time(0)
        );

 Insert Into @OperationSchedule (Location, Program, OpDate, OpStart, OpEnd)
 Values ('a',  1, '09-22-21', '14:45:00', '15:45:00')
      , ('a',  2, '09-22-21', '15:30:00', '16:30:00')
      , ('b', 88, '09-22-21', '10:45:00', '12:45:00')
      , ('b', 89, '09-22-21', '10:45:00', '14:45:00')
      , ('c', 23, '09-22-21', '12:45:00', '13:45:00')
      , ('c', 24, '09-22-21', '14:45:00', '15:15:00')
      , ('3', 48, '09-22-21', '09:05:00', '13:55:00')
      , ('3', 49, '09-22-21', '14:25:00', '15:38:00')
      ;

   With overlappedData
     As (
 Select *
      , overlap_op = lead(os.OpStart, 1, os.OpEnd) Over(Partition By os.Location Order By os.ID)
   From @OperationSchedule os
        )
 Select od.Location
      , start_date = min(od.OpStart)
      , end_date = max(iif(od.OpEnd < od.overlap_op, od.OpEnd, od.overlap_op))
      , hours_of_operation = sum(datediff(minute, od.OpStart, iif(od.OpEnd < od.overlap_op, od.OpEnd, od.overlap_op)) / 60.0)
   From overlappedData                  od
  Group By
        od.Location;


问:
Not able to find the reference tab to add Json.NET for C#
I created my first project and I am trying to work with JSON files. I am not able to see the tab of references in my Visual Studio. How can I retrieve the tab? I tried to Google and I cannot see the issue here.

This is my current Project Solution looks

[]

[]

答: its here, right click on dependencies

Body: its here, right click on dependencies


问:
React Parent To Child Component Props Update Issue
Let say i have two components one parent and another child
now i have a prop in child component called active which basically assign {active} class to child if its true now i wanted to change this prop from its parent component while rendering. take a look at some codes below

main code

```<code>import React from 'react';
import { List , Item } from "../Buttons";

export function Sample2() {
    return (
        <List>
            <Item>items</Item>
            <Item>items</Item>
            <Item>items</Item>
        </List>
    )
}
</code>```

component codes

commented line is what i am trying to achieve but its not allowed

```<code>export function List({ children }){
    const [index,setIndex] = useState(0)

    function getOptions(){
        return children.map((each,i)=>{
            //each.props.active = index == i
            return each
        })
    }

    return (
        <div className="list">
            {getOptions()}
        </div>
    )
}

export function Item({ active , children }){
    const classes ="item p-4 border-b" + (active?` active`:"")
    return (
        <div className={classes}>{children}</div>
    )
}
</code>```

now i wanted to know what is the way to achive this or i am not following react flow ? i am old in javascript but very much new to react so please explain what would be the best way to achive this

here's a screenshot of my codes

答:
Already tagged as duplicate, but for fast comprehension, here is how to do it :

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  return (
    <List>
      <Item>Element</Item>
      <Item>Element</Item>
      <Item>Element</Item>
    </List>
  );
};
const List = ({children}) => {
  const clonedChild = () => children.map((c, i) => React.cloneElement(c, {isActive: i === 0 ? 'active' : ''}))
  return (
    <>
    {clonedChild()}
    </>
  )
}

const Item = ({isActive}) => <div className={isActive ? 'active' : ''}>Item</div>

render(<App />, document.getElementById("root"));

</code>```

.active {
  background-color: brown;
}
```

An here is the repro on Stackblitz.

Body:
Let say i have two components one parent and another child
now i have a prop in child component called active which basically assign {active} class to child if its true now i wanted to change this prop from its parent component while rendering. take a look at some codes below

main code

import React from 'react';
import { List , Item } from "../Buttons";

export function Sample2() {
    return (
        <List>
            <Item>items</Item>
            <Item>items</Item>
            <Item>items</Item>
        </List>
    )
}

component codes

commented line is what i am trying to achieve but its not allowed

export function List({ children }){
    const [index,setIndex] = useState(0)

    function getOptions(){
        return children.map((each,i)=>{
            //each.props.active = index == i
            return each
        })
    }

    return (

            {getOptions()}

    )
}

export function Item({ active , children }){
    const classes ="item p-4 border-b" + (active?` active`:"")
    return (

{children}

    )
}

now i wanted to know what is the way to achive this or i am not following react flow ? i am old in javascript but very much new to react so please explain what would be the best way to achive this

here's a screenshot of my codes

Body:
Already tagged as duplicate, but for fast comprehension, here is how to do it :

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  return (
    <List>
      <Item>Element</Item>
      <Item>Element</Item>
      <Item>Element</Item>
    </List>
  );
};
const List = ({children}) => {
  const clonedChild = () => children.map((c, i) => React.cloneElement(c, {isActive: i === 0 ? 'active' : ''}))
  return (
    <>
    {clonedChild()}
    </>
  )
}

const Item = ({isActive}) => <div className={isActive ? 'active' : ''}>Item</div>

render(<App />, document.getElementById("root"));

.active {
  background-color: brown;
}

An here is the repro on Stackblitz.


问:
Go timeout for Read
I'd like to do something like unix's tail -f, but on the output produced by a process run through Go's Cmd facility.

My google-fu is not up to par, evidently, but I did find this article which lead me to write the following code, which almost works, with a bizarre twist I'm hoping I can get help with.

If it matters, I'm running this on a Mac.

First, here's the minimal program that's compiled to be the slowroll executable:

package main

import (
    "fmt"
    "time"
)

func main() {
    line := 1
    for {
        fmt.Println("This is line", line)
        line += 1
        time.Sleep(2 * time.Second)
    }
}
```
<p>When run, it produces the following output, one line every 2 seconds:</p>
```    > ./slowroll
    This is line 1
    This is line 2
    This is line 3
    This is line 4
```
<p>And so on.</p>
<p>Here's the package code that attempts to read this, but allowing timeouts so other things can be done:</p>
<pre class="lang-golang prettyprint-override"><code>package timeout_io

import (
    "bufio"
    "bytes"
    "context"
    "errors"
    "time"
)

const BufferSize = 4096

var ErrTimeout = errors.New("timeout")

type TimeoutReader struct {
    b *bufio.Reader
    t time.Duration
}

func NewTimeoutReader(stdOut *bytes.Buffer) *TimeoutReader {
    return &TimeoutReader{b: bufio.NewReaderSize(stdOut, BufferSize), t: 0}
}

func (r *TimeoutReader) SetTimeout(t time.Duration) time.Duration {
    prev := r.t
    r.t = t
    return prev
}

type CallResponse struct {
    Resp string
    Err  error
}

func helper(r *bufio.Reader) <-chan *CallResponse {
    respChan := make(chan *CallResponse, 1)

    go func() {
        resp, err := r.ReadString('\n')

        if err != nil {
            respChan <- &CallResponse{resp, err}
        } else {
            respChan <- &CallResponse{resp, nil}
        }

        return
    }()

    return respChan
}

func (r *TimeoutReader) ReadLineCtx(ctx context.Context) (string, error) {
    select {
    case <-ctx.Done():
        return "", ErrTimeout
    case respChan := <-helper(r.b):
        return respChan.Resp, respChan.Err
    }
}

func (r *TimeoutReader) ReadLine() (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), r.t)
    defer cancel()

    s, err := r.ReadLineCtx(ctx)
    if err != nil {
        return "", err
    }

    return s, nil
}
</code>```

Finally, here's the main code that calls ReadLine with timeout:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "os/exec"
    "sync"
    "time"

    "watcher/timeout_io"
)

func main() {
    var stdOut bytes.Buffer
    var stdErr bytes.Buffer
    runCommand := &exec.Cmd{
        Path:   "./slowroll",
        Stdout: &stdOut,
        Stderr: &stdErr,
    }

    var wg sync.WaitGroup

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := runCommand.Run()
        if err != nil {
            fmt.Println("failed due to error:", err)
            os.Exit(1)
        }
    }(&wg)

    wg.Add(1)

    stdOutReader := timeout_io.NewTimeoutReader(&stdOut)
    stdOutReader.SetTimeout(10 * time.Millisecond)
    index := 1
    for {
        s, err := stdOutReader.ReadLine()
        if err != nil {
            if err != timeout_io.ErrTimeout && err != io.EOF {
                fmt.Println("ReadLine got error", err)
                break
            }
        } else if len(s) > 0 {
            fmt.Println("index: ", index, " s: ", s)
            index += 1
            s = ""
        }
    }

    wg.Wait()
    fmt.Println("Done!")
}
```
<p>When run, it produces the following output:</p>
```    > go run watcher.go
    index:  1  s:  This is line 1

    index:  2  s:  This is line 2

    index:  3  s:  This is line 2

    index:  4  s:  This is line 3

    index:  5  s:  This is line 2

    index:  6  s:  This is line 3

    index:  7  s:  This is line 4

    index:  8  s:  This is line 2

    index:  9  s:  This is line 3

    index:  10  s:  This is line 4

    index:  11  s:  This is line 5
```

And so on.

Occasionally, some slowroll output lines don't show up at all; which lines get repeated is random.

So that's my mystery... I don't see where the (apparent) loop is happening that causes the lines to be produced multiple times.

Thanks very much in advance for any help!

答:
Simplify the code by creating a pipe and reading from that pipe:

```<code>cmd := exec.Command("./slowroll")
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

s := bufio.NewScanner(stdout)
for s.Scan() {
    fmt.Printf("%s\n", s.Bytes())
}
</code>```

If your goal is to monitor the combined output of stderr and stdin, then use the same pipe for both:

```<code>cmd := exec.Command("./slowroll")
combined, _ := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout // <-- use stdout pipe for stderr
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

s := bufio.NewScanner(combined)
for s.Scan() {
    fmt.Printf("%s\n", s.Bytes())
}
</code>```

The code in the question has a data race on the stdOut bytes.Buffer.

Title: Go timeout for Read

Body:
I'd like to do something like unix's tail -f, but on the output produced by a process run through Go's Cmd facility.

My google-fu is not up to par, evidently, but I did find this article which lead me to write the following code, which almost works, with a bizarre twist I'm hoping I can get help with.

If it matters, I'm running this on a Mac.

First, here's the minimal program that's compiled to be the slowroll executable:

package main

import (
    "fmt"
    "time"
)

func main() {
    line := 1
    for {
        fmt.Println("This is line", line)
        line += 1
        time.Sleep(2 * time.Second)
    }
}

When run, it produces the following output, one line every 2 seconds:

    > ./slowroll
    This is line 1
    This is line 2
    This is line 3
    This is line 4

And so on.

Here's the package code that attempts to read this, but allowing timeouts so other things can be done:

package timeout_io

import (
    "bufio"
    "bytes"
    "context"
    "errors"
    "time"
)

const BufferSize = 4096

var ErrTimeout = errors.New("timeout")

type TimeoutReader struct {
    b *bufio.Reader
    t time.Duration
}

func NewTimeoutReader(stdOut *bytes.Buffer) *TimeoutReader {
    return &TimeoutReader{b: bufio.NewReaderSize(stdOut, BufferSize), t: 0}
}

func (r *TimeoutReader) SetTimeout(t time.Duration) time.Duration {
    prev := r.t
    r.t = t
    return prev
}

type CallResponse struct {
    Resp string
    Err  error
}

func helper(r *bufio.Reader) <-chan *CallResponse {
    respChan := make(chan *CallResponse, 1)

    go func() {
        resp, err := r.ReadString('\n')

        if err != nil {
            respChan <- &CallResponse{resp, err}
        } else {
            respChan <- &CallResponse{resp, nil}
        }

        return
    }()

    return respChan
}

func (r *TimeoutReader) ReadLineCtx(ctx context.Context) (string, error) {
    select {
    case <-ctx.Done():
        return "", ErrTimeout
    case respChan := <-helper(r.b):
        return respChan.Resp, respChan.Err
    }
}

func (r *TimeoutReader) ReadLine() (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), r.t)
    defer cancel()

    s, err := r.ReadLineCtx(ctx)
    if err != nil {
        return "", err
    }

    return s, nil
}

Finally, here's the main code that calls ReadLine with timeout:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "os/exec"
    "sync"
    "time"

    "watcher/timeout_io"
)

func main() {
    var stdOut bytes.Buffer
    var stdErr bytes.Buffer
    runCommand := &exec.Cmd{
        Path:   "./slowroll",
        Stdout: &stdOut,
        Stderr: &stdErr,
    }

    var wg sync.WaitGroup

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := runCommand.Run()
        if err != nil {
            fmt.Println("failed due to error:", err)
            os.Exit(1)
        }
    }(&wg)

    wg.Add(1)

    stdOutReader := timeout_io.NewTimeoutReader(&stdOut)
    stdOutReader.SetTimeout(10 * time.Millisecond)
    index := 1
    for {
        s, err := stdOutReader.ReadLine()
        if err != nil {
            if err != timeout_io.ErrTimeout && err != io.EOF {
                fmt.Println("ReadLine got error", err)
                break
            }
        } else if len(s) > 0 {
            fmt.Println("index: ", index, " s: ", s)
            index += 1
            s = ""
        }
    }

    wg.Wait()
    fmt.Println("Done!")
}

When run, it produces the following output:

    > go run watcher.go
    index:  1  s:  This is line 1

    index:  2  s:  This is line 2

    index:  3  s:  This is line 2

    index:  4  s:  This is line 3

    index:  5  s:  This is line 2

    index:  6  s:  This is line 3

    index:  7  s:  This is line 4

    index:  8  s:  This is line 2

    index:  9  s:  This is line 3

    index:  10  s:  This is line 4

    index:  11  s:  This is line 5

And so on.

Occasionally, some slowroll output lines don't show up at all; which lines get repeated is random.

So that's my mystery... I don't see where the (apparent) loop is happening that causes the lines to be produced multiple times.

Thanks very much in advance for any help!

Body:
Simplify the code by creating a pipe and reading from that pipe:

cmd := exec.Command("./slowroll")
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

s := bufio.NewScanner(stdout)
for s.Scan() {
    fmt.Printf("%s\n", s.Bytes())
}

If your goal is to monitor the combined output of stderr and stdin, then use the same pipe for both:

cmd := exec.Command("./slowroll")
combined, _ := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout // <-- use stdout pipe for stderr
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

s := bufio.NewScanner(combined)
for s.Scan() {
    fmt.Printf("%s\n", s.Bytes())
}

The code in the question has a data race on the stdOut bytes.Buffer.


问:
How to load proj4 for lat/long in highmaps using typescript and react
I would like to reproduce this highmaps example in react using typescript. However, the lat/long points are not being displayed which seems related to proj4 package as it is working in this javascript demo.

I have tried it in a live demo. If I load the package as follows, it is not used but I do not know where it should be called:

```<code>import * as proj4 from "proj4";
</code>```

Thanks in advance!

答:
You can use proj4 property
https://api.highcharts.com/highmaps/chart.proj4

Example:

```<code>import proj4 from "proj4";
import highcharts from "highcharts";
import mapInit from "highcharts/modules/map";

mapInit(highcharts);

const chartOptions: highcharts.Options = {
            chart: {
                type: "map",
                map: "mexico",
                proj4: proj4,
            }
};
</code>```

Body:
I would like to reproduce this highmaps example in react using typescript. However, the lat/long points are not being displayed which seems related to proj4 package as it is working in this javascript demo.

I have tried it in a live demo. If I load the package as follows, it is not used but I do not know where it should be called:

import * as proj4 from "proj4";

Thanks in advance!

Body:
You can use proj4 property
https://api.highcharts.com/highmaps/chart.proj4

Example:

import proj4 from "proj4";
import highcharts from "highcharts";
import mapInit from "highcharts/modules/map";

mapInit(highcharts);

const chartOptions: highcharts.Options = {
            chart: {
                type: "map",
                map: "mexico",
                proj4: proj4,
            }
};


问:
I've already setup the ssh key, but VSCode keeps asking for password
I'm using a macbook(MacOS) to connect to a remote Ubuntu server.
I copied the public ssh key to the server using ssh-copy-id and checked that the ssh key works on the terminal. When I do ssh username@x.x.x.x, connection is made without asking for password).
However, when I try to connect to the server through Visual Studio Code, VSCode keeps asking for password. Is there a way to fix this?

Thanks in advance!

答:
In case you're having this problem in Windows, keep in mind that the public/private keys that you might use to connect to a remote machine from WSL aren't the same ones that VS Code will use to connect from Windows. You need to create a separate public/private key pair for Windows, and export that private key to the remote server too.

From VS Code remote debug tips and tricks:

In a Powershell window, create a public/private key pair just as you would in a Linux terminal:

```<code>ssh-keygen -t rsa -b 4096
</code>```

Then export it to the remote server:

```<code>export USER_AT_HOST="your-user-name-on-host@hostname"
export PUBKEYPATH="$HOME/.ssh/id_rsa.pub"

ssh $USER_AT_HOST "powershell New-Item -Force -ItemType Directory -Path \"\$HOME\\.ssh\"; Add-Content -Force -Path \"\$HOME\\.ssh\\authorized_keys\" -Value '$(tr -d '\n\r' < "$PUBKEYPATH")'"
</code>```

Make sure you can connect via passwordless SSH via PowerShell.

Finally, in VS Code. press Ctrl+Shift+P to open the command palette and select "Remote-SSH: Open SSH Configuration File..." and edit the config file like so:

```<code>Host [convenient name]
    HostName [hostname]
    User [username]
    IdentityFile C:\Users\[username]\.ssh\id_rsa*
</code>```

Then when you run "Remote-SSH: Connect to Host..." in VS Code and choose the host above, it should connect without prompting for a password.

Body:
In case you're having this problem in Windows, keep in mind that the public/private keys that you might use to connect to a remote machine from WSL aren't the same ones that VS Code will use to connect from Windows. You need to create a separate public/private key pair for Windows, and export that private key to the remote server too.

From VS Code remote debug tips and tricks:

In a Powershell window, create a public/private key pair just as you would in a Linux terminal:

ssh-keygen -t rsa -b 4096

Then export it to the remote server:

export USER_AT_HOST="your-user-name-on-host@hostname"
export PUBKEYPATH="$HOME/.ssh/id_rsa.pub"

ssh $USER_AT_HOST "powershell New-Item -Force -ItemType Directory -Path \"\$HOME\\.ssh\"; Add-Content -Force -Path \"\$HOME\\.ssh\\authorized_keys\" -Value '$(tr -d '\n\r' < "$PUBKEYPATH")'"

Make sure you can connect via passwordless SSH via PowerShell.

Finally, in VS Code. press Ctrl+Shift+P to open the command palette and select "Remote-SSH: Open SSH Configuration File..." and edit the config file like so:

Host [convenient name]
    HostName [hostname]
    User [username]
    IdentityFile C:\Users\[username]\.ssh\id_rsa*

Then when you run "Remote-SSH: Connect to Host..." in VS Code and choose the host above, it should connect without prompting for a password.