问:
Vue-Router4/TypeScript "No overload matches this call"
I'm trying to caoncatinate multiple vue-router 4 file.ts to the main vue-router(index.ts) using typescript, but it gives the error "TS2769: No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type 'RouteRecordRaw[]' is not assignable to parameter of type 'ConcatArray'.
The types returned by 'slice(...)' are incompatible between these types.
Type 'RouteRecordRaw[]' is not assignable to type 'never[]'...."

Here is my files.

DashboardRouter.ts

```<code>import { RouteRecordRaw } from "vue-router";
const DashboardRouter: Array<RouteRecordRaw> = [
{
  path: "/",
  redirect: "/dashboard",
  component: () => import("@/layout/Layout.vue"),
  children: [
    {
      path: "/dashboard",
      name: "dashboard",
      component: () => import("@/views/Dashboard.vue"),
     },
   ]
  },
];
export default DashboardRouter;
</code>```

GuestRouter.ts

```<code>import { RouteRecordRaw } from "vue-router";
const GuestRouter: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/auth/Login.vue")
  },
  {
    path: "/password-reset",
    name: "password-reset",
    component: () => import("@/views/auth/PasswordReset.vue")
  },
  {
   // the 404 route, when none of the above matches
    path: "/404",
    name: "error-404",
    component: () => import("@/views/error/Error404.vue")
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404"
  }
];
export default GuestRouter;
</code>```

Index.ts(Main Router)

```<code>import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { Mutations, Actions } from "@/store/enums/StoreEnums";
import DashboardRoute from "./DashboardRouter";
import GuestRoute from "./GuestRouter";

const routes: Array<RouteRecordRaw> = [].concat(GuestRoute, DashboardRoute);

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(() => {
  // reset config to initial state
  store.commit(Mutations.RESET_LAYOUT_CONFIG);

  // Scroll page to top on every route change
  setTimeout(() => {
    window.scrollTo(0, 0);
  }, 100);
});
export default router;
</code>```

答:
You need to split out the RouteRecordRaw and import it as a type, which is what it is:

```<code>import { createWebHistory, createRouter } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
</code>```

I had the same problem, just fixed it a few minutes ago.

Body:
I'm trying to caoncatinate multiple vue-router 4 file.ts to the main vue-router(index.ts) using typescript, but it gives the error "TS2769: No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type 'RouteRecordRaw[]' is not assignable to parameter of type 'ConcatArray'.
The types returned by 'slice(...)' are incompatible between these types.
Type 'RouteRecordRaw[]' is not assignable to type 'never[]'...."

Here is my files.

DashboardRouter.ts

import { RouteRecordRaw } from "vue-router";
const DashboardRouter: Array<RouteRecordRaw> = [
{
  path: "/",
  redirect: "/dashboard",
  component: () => import("@/layout/Layout.vue"),
  children: [
    {
      path: "/dashboard",
      name: "dashboard",
      component: () => import("@/views/Dashboard.vue"),
     },
   ]
  },
];
export default DashboardRouter;

GuestRouter.ts

import { RouteRecordRaw } from "vue-router";
const GuestRouter: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/auth/Login.vue")
  },
  {
    path: "/password-reset",
    name: "password-reset",
    component: () => import("@/views/auth/PasswordReset.vue")
  },
  {
   // the 404 route, when none of the above matches
    path: "/404",
    name: "error-404",
    component: () => import("@/views/error/Error404.vue")
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404"
  }
];
export default GuestRouter;

Index.ts(Main Router)

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { Mutations, Actions } from "@/store/enums/StoreEnums";
import DashboardRoute from "./DashboardRouter";
import GuestRoute from "./GuestRouter";

const routes: Array<RouteRecordRaw> = [].concat(GuestRoute, DashboardRoute);

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(() => {
  // reset config to initial state
  store.commit(Mutations.RESET_LAYOUT_CONFIG);

  // Scroll page to top on every route change
  setTimeout(() => {
    window.scrollTo(0, 0);
  }, 100);
});
export default router;

Body:
You need to split out the RouteRecordRaw and import it as a type, which is what it is:

import { createWebHistory, createRouter } from "vue-router";
import type { RouteRecordRaw } from "vue-router";

I had the same problem, just fixed it a few minutes ago.


来源: stackexchange

问:
how to make loops from smallest to largest number?
```<code>a = int(input("first number: "))
b = int(input("second number: "))
for x in range (a,b):
    print(x, end = ' ')
</code>```

I am making a program that would display a number from smallest to largest.

For example: the first number is 10 then the second number is 1.

My expected result is: 1,2,3,4,5,6,7,8,9.

The program that I did is not working if a is lower than b, but is working if the a is higher than b.

答:
If you want to count backwards then you can specify an additional stepsize of -1 as an argument to the range function as follows:</p>
```<code>In [1]: list(range(1,10))
Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]: list(range(10,1))
Out[2]: []

In [3]: list(range(10,1,-1))
Out[3]: [10, 9, 8, 7, 6, 5, 4, 3, 2]

</code>```

ContentLicense: CC BY-SA 4.0

Body:
a = int(input("first number: "))
b = int(input("second number: "))
for x in range (a,b):
    print(x, end = ' ')

I am making a program that would display a number from smallest to largest.

For example: the first number is 10 then the second number is 1.

My expected result is: 1,2,3,4,5,6,7,8,9.

The program that I did is not working if a is lower than b, but is working if the a is higher than b.

Body:
If you want to count backwards then you can specify an additional stepsize of -1 as an argument to the range function as follows:

In [1]: list(range(1,10))
Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]: list(range(10,1))
Out[2]: []

In [3]: list(range(10,1,-1))
Out[3]: [10, 9, 8, 7, 6, 5, 4, 3, 2]


答:
To count backwards, range has a step parameter: when set to -1, it will count backwards.

```<code>a = int(input("first number: "))
b = int(input("second number: "))

step = -1 if a > b else 1
for x in range (a, b, step):
    print(x, end = ' ')
</code>```

Title: how to make loops from smallest to largest number?

Body:
To count backwards, range has a step parameter: when set to -1, it will count backwards.

a = int(input("first number: "))
b = int(input("second number: "))

step = -1 if a > b else 1
for x in range (a, b, step):
    print(x, end = ' ')


问:
How do I open browser in specific "profile" using BATCH script in Windows?
Here is the shell script I have used to open the specific URL

```<code>   start microsoft-edge: https://stackoverflow.com/questions/ask
</code>```

However, I have multiple Profiles defined in Edge browser.

How do I open a browser based on the Profile name ? How do I pass Profile name or path in script?

答:
You can use --profile-directory="Profile name" to open Edge with specific profile.

The sample code for batch file is like this:

```<code>start "" "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" https://stackoverflow.com/questions/ask --profile-directory="Profile 1"
</code>```

Note: please edit the Edge path and profile name to your owns.

Body:
Here is the shell script I have used to open the specific URL

   start microsoft-edge: https://stackoverflow.com/questions/ask

However, I have multiple Profiles defined in Edge browser.

How do I open a browser based on the Profile name ? How do I pass Profile name or path in script?

Body:
You can use --profile-directory="Profile name" to open Edge with specific profile.

The sample code for batch file is like this:

start "" "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" https://stackoverflow.com/questions/ask --profile-directory="Profile 1"

Note: please edit the Edge path and profile name to your owns.


问:
How to sort arrays from the first character inputted by user followed by duplicates in VB.NET
i've been working on this

```<code>Public Sub Main()
        Dim str as String
        str = Console.ReadLine()
        str = str.ToLower()
        str = str.Replace(" ","")
        Dim mySort as Char() = str.ToCharArray()

        System.Array.Sort(mySort)

        For Each value As String In mySort
            Console.Write(value)
        Next
End Sub
</code>```

if the input is United States of America

the result will be aaacdeeefiimnorsstttu
(it sorted alphabetically from a to z)

what I expect is uniittteeedssaaaofmrc
(sorted from the first character inputted from user followed by the duplicates (if there's any))

what should i do to have such expected result ?

Thanks

答:
Here is my solution, I tried running it on dotnetfiddle.net</p>
```<code>Imports System

Public Module Module1
Public Sub Main()
    Dim txt,trm as String
    txt = Console.ReadLine()
    trm = txt.ToLower().trim().Replace(" ","")
    Dim chars as Char() = trm.ToCharArray()

    Dim i as integer = 0
    Dim j as integer = 0
    Dim temp as string = ""

    While (i < trm.Length)
        j = i + 1
        temp = temp + chars(i)

        While ( j < trm.Length)

            If (chars(i) = chars(j)) Then
                temp = temp + chars(j)
                chars(j)= " "
            End If

            j = j + 1
        End While

        i = i + 1
    End While

    temp = temp.Replace(" ","")
    Console.WriteLine(temp)
End Sub
End Module
</code>```

Body:
i've been working on this

Public Sub Main()
        Dim str as String
        str = Console.ReadLine()
        str = str.ToLower()
        str = str.Replace(" ","")
        Dim mySort as Char() = str.ToCharArray()

        System.Array.Sort(mySort)

        For Each value As String In mySort
            Console.Write(value)
        Next
End Sub

if the input is United States of America

the result will be aaacdeeefiimnorsstttu
(it sorted alphabetically from a to z)

what I expect is uniittteeedssaaaofmrc
(sorted from the first character inputted from user followed by the duplicates (if there's any))

what should i do to have such expected result ?

Thanks

Body:
Here is my solution, I tried running it on dotnetfiddle.net

Imports System

Public Module Module1
Public Sub Main()
    Dim txt,trm as String
    txt = Console.ReadLine()
    trm = txt.ToLower().trim().Replace(" ","")
    Dim chars as Char() = trm.ToCharArray()

    Dim i as integer = 0
    Dim j as integer = 0
    Dim temp as string = ""

    While (i < trm.Length)
        j = i + 1
        temp = temp + chars(i)

        While ( j < trm.Length)

            If (chars(i) = chars(j)) Then
                temp = temp + chars(j)
                chars(j)= " "
            End If

            j = j + 1
        End While

        i = i + 1
    End While

    temp = temp.Replace(" ","")
    Console.WriteLine(temp)
End Sub
End Module


问:
Getting error "title not defined " on EJS template engine with Express
I was learning NodeJS and I am using EJS as templating engine. But whenever I click on register button my Registration page I am getting an error that title is not defined.
Here is my code.

users.js

```<code>var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploads = multer({dest: './uploads'});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register',{
    'title': 'Register'
  });
});

router.get('/login', function(req, res, next) {
  res.render('login',{
    'title': 'Login'
  });
});

router.post('/register', uploads.single('profileImage'), function(req, res, next){
    var name = req.body.name;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var password2 = req.body.password2;

    //Check for image field

    if(req.file){
        console.log('Uploading file.....');

        var profileImageOriginalName = req.files.profileimage.originalname;
        var profileImageName = req.files.profileimage.name;
        var profileImageMime = req.files.profileimage.mimetype;
        var profileImagePath = req.files.profileimage.path;
        var profileImageExt  = req.files.profileimage.extension;
        var profileImageSize = req.files.profileimage.size;
    }
    else{
        //set a default image
        var profileImageName = 'noimage.png';
    }

    //Form Validation
    req.checkBody('name','This field is required').notEmpty();
    req.checkBody('email','This field is required').notEmpty();
    req.checkBody('email','Invalid Email').isEmail();
    req.checkBody('username','This field is required').notEmpty();
    req.checkBody('password','This field is required').notEmpty();
    req.checkBody('password2','Passwords do not match').equals(req.body.password);

    //check for errors
    var errors = req.validationErrors();
    if(errors){
        res.render('register',{
            errors: errors,
            name: name,
            email: email,
            username: username,
            password: password,
            password2: password2
        });
    }
    else{
        var newUser = new User({
            name: name,
            email: email,
            username: username,
            password: password,
            profileimage: profileImageName
        });
        //Create user
        /*User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });*/

        //success message
        req.flash('success', 'Your account registered successfully');
        res.location('/');
        res.redirect('/');
    }
});

module.exports = router;
</code>```

head.ejs

```<code><title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/bootstrap.css' />
<link rel='stylesheet' href='/stylesheets/style.css' />
</code>```

header.ejs

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Project name</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li <% if (title == "Members") { %>class="active" <% } %> ><a href="/">Members</a></li>
        <li <% if (title == "Register") { %>class="active" <% } %> ><a href="/users/register">Register</a></li>
        <li <% if (title == "Login") { %>class="active" <% } %> ><a href="/users/login">Log In</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="/users/logout">Log Out</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</nav>
</code>```

register.ejs

```<code><!DOCTYPE html>
<html>
  <head>
    <% include ./partials/head.ejs %>
  </head>
  <body>

    <div class="container">
        <% include ./partials/header.ejs %>
      <h1>Register</h1>
      <p>Please Register using the below form</p>
      <form method="post" action="/users/register" enctype="multipart/form-data">
        <div class="form-group">
          <label>Name</label>
          <input class="form-control" type="text" name="name" placeholder="Enter your name">
        </div>
        <div class="form-group">
          <label>Email</label>
          <input class="form-control" type="email" name="email" placeholder="Enter your email">
        </div>
        <div class="form-group">
          <label>Username</label>
          <input class="form-control" type="text" name="username" placeholder="Enter your username">
        </div>
        <div class="form-group">
          <label>Password</label>
          <input class="form-control" type="password" name="password" placeholder="Enter your Password">
        </div>
        <div class="form-group">
          <label>Confirm Password</label>
          <input class="form-control" type="password" name="password2" placeholder="Confirm your Password">
        </div>
        <div class="form-group">
          <label>Profile Image</label>
          <input class="form-control" type="file" name="profileImage">
        </div>
        <button class="btn btn-default" name="submit" type="submit" value="Register">Register</button>
      </form>
    </div>
  </body>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script type="text/javascript" src="/javascript/bootstrap.js"></script>
</html>
</code>```

I am not getting why this is happening. I have tried this solution but it's not working. Any help would be appreciated.

答:
you can change

code

```<code>router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
</code>```

to
code

```<code>router.get('/', function(req, res, next) {
  return res.send('respond with a resource');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was learning NodeJS and I am using EJS as templating engine. But whenever I click on register button my Registration page I am getting an error that title is not defined.
Here is my code.

users.js

var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploads = multer({dest: './uploads'});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register',{
    'title': 'Register'
  });
});

router.get('/login', function(req, res, next) {
  res.render('login',{
    'title': 'Login'
  });
});

router.post('/register', uploads.single('profileImage'), function(req, res, next){
    var name = req.body.name;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var password2 = req.body.password2;

    //Check for image field

    if(req.file){
        console.log('Uploading file.....');

        var profileImageOriginalName = req.files.profileimage.originalname;
        var profileImageName = req.files.profileimage.name;
        var profileImageMime = req.files.profileimage.mimetype;
        var profileImagePath = req.files.profileimage.path;
        var profileImageExt  = req.files.profileimage.extension;
        var profileImageSize = req.files.profileimage.size;
    }
    else{
        //set a default image
        var profileImageName = 'noimage.png';
    }

    //Form Validation
    req.checkBody('name','This field is required').notEmpty();
    req.checkBody('email','This field is required').notEmpty();
    req.checkBody('email','Invalid Email').isEmail();
    req.checkBody('username','This field is required').notEmpty();
    req.checkBody('password','This field is required').notEmpty();
    req.checkBody('password2','Passwords do not match').equals(req.body.password);

    //check for errors
    var errors = req.validationErrors();
    if(errors){
        res.render('register',{
            errors: errors,
            name: name,
            email: email,
            username: username,
            password: password,
            password2: password2
        });
    }
    else{
        var newUser = new User({
            name: name,
            email: email,
            username: username,
            password: password,
            profileimage: profileImageName
        });
        //Create user
        /*User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });*/

        //success message
        req.flash('success', 'Your account registered successfully');
        res.location('/');
        res.redirect('/');
    }
});

module.exports = router;

head.ejs

<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/bootstrap.css' />
<link rel='stylesheet' href='/stylesheets/style.css' />

header.ejs

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      Project name

        <li <% if (title == "Members") { %>class="active" <% } %> >Members

        <li <% if (title == "Register") { %>class="active" <% } %> >Register

        <li <% if (title == "Login") { %>class="active" <% } %> >Log In

Log Out

register.ejs

<!DOCTYPE html>

    <% include ./partials/head.ejs %>

        <% include ./partials/header.ejs %>

Register

Please Register using the below form

      <form method="post" action="/users/register" enctype="multipart/form-data">

          Name
          <input class="form-control" type="text" name="name" placeholder="Enter your name">

          Email
          <input class="form-control" type="email" name="email" placeholder="Enter your email">

          Username
          <input class="form-control" type="text" name="username" placeholder="Enter your username">

          Password
          <input class="form-control" type="password" name="password" placeholder="Enter your Password">

          Confirm Password
          <input class="form-control" type="password" name="password2" placeholder="Confirm your Password">

          Profile Image
          <input class="form-control" type="file" name="profileImage">

        <button class="btn btn-default" name="submit" type="submit" value="Register">Register</button>
      </form>

I am not getting why this is happening. I have tried this solution but it's not working. Any help would be appreciated.

Body:
you can change

code

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

to
code

router.get('/', function(req, res, next) {
  return res.send('respond with a resource');
});


问:
Android - How to start creating a launcher app?
I am going to start my new app which is going to be a Home Replacement.
I have been through the example provided by google. but i am still little bit confused.

like
Where should i start?
Should i create a normal activity by extending an Activity class then just set the background image(wallpaper) and use a grid view to show all applications?

How to make Android to treat my app as a launcher process?

so many question running in my mind and please don't advise me to go through Android Launcher because it has almost more than 100 classes and what i need is just a simple start after that i know what i want from my app.

答:
I would start by looking at the source for the launcher that ships with Android to get an idea of how it works and how the code is structured:

https://android.googlesource.com/platform/packages/apps/Launcher2


问:
Flutter & GraphQL

Not sure why am I getting this error.
Please help.

```<code>const express = require('express');
const graphqlHTTP = require('express-graphql');

const app = express();

app.use('/graphql', graphqlHTTP({
    graphiql: true
}));

app.listen(4000, () => {
    console.log('Listening to port 4000');
});
</code>```

答:
From their doc</p>
```<code>const { graphqlHTTP } = require('express-graphql');
</code>```

Title: Flutter & GraphQL

Body:
Not sure why am I getting this error.
Please help.

const express = require('express');
const graphqlHTTP = require('express-graphql');

const app = express();

app.use('/graphql', graphqlHTTP({
    graphiql: true
}));

app.listen(4000, () => {
    console.log('Listening to port 4000');
});

Body:
From their doc

const { graphqlHTTP } = require('express-graphql');


问:
How to update lazyColumn's item using the Flow list from room?
As below code showed, I got the list(type: Flow<List<T>>),

how can I use it to update lazyColumn's item, so when the room data changed, lazyColumn updates items accordingly?

Many thanks.

```<code>@Composable
fun SomeContent(context: Context) {
    // get the view model ref
    val viewModel: SomeViewModel =
        viewModel(factory = SomeViewModelFactory(Db.getInstance(context)))

    // get the list from room, it is a Flow list
    val list = viewModel.sumDao.getAllRows()

    LazyColumn(
    ) {
        // I need to use the list in below, but got errors, how to do?
        items(list.size) {
        SomeListItem(list[it])
        }
    }
}
</code>```

答:
You must collect your FlowList as follows

```<code>val list = viewModel.sumDao.getAllRows().collectAsState(initial = emptyList())
</code>```

Instead of items, use itemsIndexed

```<code>itemsIndexed(list) {idx, row -> SomeListItem(row)}
</code>```

Let me know if the above works.

Body:
As below code showed, I got the list(type: Flow<List<T>>),

how can I use it to update lazyColumn's item, so when the room data changed, lazyColumn updates items accordingly?

Many thanks.

@Composable
fun SomeContent(context: Context) {
    // get the view model ref
    val viewModel: SomeViewModel =
        viewModel(factory = SomeViewModelFactory(Db.getInstance(context)))

    // get the list from room, it is a Flow list
    val list = viewModel.sumDao.getAllRows()

    LazyColumn(
    ) {
        // I need to use the list in below, but got errors, how to do?
        items(list.size) {
        SomeListItem(list[it])
        }
    }
}

Body:
You must collect your FlowList as follows

val list = viewModel.sumDao.getAllRows().collectAsState(initial = emptyList())

Instead of items, use itemsIndexed

itemsIndexed(list) {idx, row -> SomeListItem(row)}

Let me know if the above works.


问:
how to add type annotation for mock function
I have two mocked functions named mockedUnload and mockedMiniApp in test.tsx file;

```<code>let mockedUnload;
let mockedMiniApp;

beforeEach(() => {
   mockedUnload = jest.fn(() => Promise.resolve());
   mockedMiniApp = jest.fn(() => Promise.resolve({unload: mockedUnload}));
};
</code>```

Obviously, the type of mockedUnload and mockedMiniApp is any. It maybe not a good practise, but I don't know what the type annotation I should assign to mockedUnload and mockedMiniApp. BTW, I have to wrapp these two functions into beforeEach for some reasons.
Thanks.

答:
You can type these two mock function by using jest.MockedFunction, which is available in the @types/jest module from version 24.9.0.

```<code>type Unload = () => Promise<void>;

let mockedUnload: jest.MockedFunction<Unload>;
let mockedMiniApp: jest.MockedFunction<() => Promise<{ unload: Unload }>>;

beforeEach(() => {
  mockedUnload = jest.fn(() => Promise.resolve());
  mockedMiniApp = jest.fn(() => Promise.resolve({ unload: mockedUnload }));
});
</code>```

Type definition:

```<code> /**
     * Wrap a function with mock definitions
     *
     * @example
     *
     *  import { myFunction } from "./library";
     *  jest.mock("./library");
     *
     *  const mockMyFunction = myFunction as jest.MockedFunction<typeof myFunction>;
     *  expect(mockMyFunction.mock.calls[0][0]).toBe(42);
     */
    type MockedFunction<T extends (...args: any[]) => any> = MockInstance<ReturnType<T>, ArgsType<T>> & T;
</code>```

Update: jest version < 24.9.0

Try:

```<code>type Unload = () => Promise<void>;

let mockedUnload: jest.Mock<ReturnType<Unload>>;
let mockedMiniApp: jest.Mock<Promise<{ unload: Unload }>>;

mockedUnload = jest.fn(() => Promise.resolve());
mockedMiniApp = jest.fn(() => Promise.resolve({ unload: mockedUnload }));

// or
let mockedUnload1: jest.MockInstance<ReturnType<Unload>>;
let mockedMiniApp1: jest.MockInstance<Promise<{ unload: Unload }>>;

mockedUnload = jest.fn(() => Promise.resolve());
mockedMiniApp = jest.fn(() => Promise.resolve({ unload: mockedUnload }));
</code>```

Body:
I have two mocked functions named mockedUnload and mockedMiniApp in test.tsx file;

let mockedUnload;
let mockedMiniApp;

beforeEach(() => {
   mockedUnload = jest.fn(() => Promise.resolve());
   mockedMiniApp = jest.fn(() => Promise.resolve({unload: mockedUnload}));
};

Obviously, the type of mockedUnload and mockedMiniApp is any. It maybe not a good practise, but I don't know what the type annotation I should assign to mockedUnload and mockedMiniApp. BTW, I have to wrapp these two functions into beforeEach for some reasons.
Thanks.

Body:
You can type these two mock function by using jest.MockedFunction, which is available in the @types/jest module from version 24.9.0.

type Unload = () => Promise<void>;

let mockedUnload: jest.MockedFunction<Unload>;
let mockedMiniApp: jest.MockedFunction<() => Promise<{ unload: Unload }>>;

beforeEach(() => {
  mockedUnload = jest.fn(() => Promise.resolve());
  mockedMiniApp = jest.fn(() => Promise.resolve({ unload: mockedUnload }));
});

Type definition:

 /**
     * Wrap a function with mock definitions
     *
     * @example
     *
     *  import { myFunction } from "./library";
     *  jest.mock("./library");
     *
     *  const mockMyFunction = myFunction as jest.MockedFunction<typeof myFunction>;
     *  expect(mockMyFunction.mock.calls[0][0]).toBe(42);
     */
    type MockedFunction<T extends (...args: any[]) => any> = MockInstance<ReturnType<T>, ArgsType<T>> & T;

Update: jest version < 24.9.0

Try:

type Unload = () => Promise<void>;

let mockedUnload: jest.Mock<ReturnType<Unload>>;
let mockedMiniApp: jest.Mock<Promise<{ unload: Unload }>>;

mockedUnload = jest.fn(() => Promise.resolve());
mockedMiniApp = jest.fn(() => Promise.resolve({ unload: mockedUnload }));

// or
let mockedUnload1: jest.MockInstance<ReturnType<Unload>>;
let mockedMiniApp1: jest.MockInstance<Promise<{ unload: Unload }>>;

mockedUnload = jest.fn(() => Promise.resolve());
mockedMiniApp = jest.fn(() => Promise.resolve({ unload: mockedUnload }));


问:
pyflink, ImportError: No module named pyflink
I am testing pyflink on

os: centos7

flink version: flink-1.14.3

virtualenv python version: Python 3.6.8

pip list:

apache-beam            2.27.0

apache-flink           1.14.3

apache-flink-libraries 1.14.3

avro-python3           1.9.2.1

certifi                2021.10.8

charset-normalizer     2.0.11

cloudpickle            1.2.2

crcmod                 1.7

dill                   0.3.1.1

docopt                 0.6.2

fastavro               0.23.6

future                 0.18.2

grpcio                 1.43.0

hdfs                   2.6.0

httplib2               0.17.4

idna                   3.3

mock                   2.0.0

numpy                  1.19.5

oauth2client           4.1.3

pandas                 1.1.5

pbr                    5.8.1

pip                    21.3.1

protobuf               3.17.3

py4j                   0.10.8.1

pyarrow                2.0.0

pyasn1                 0.4.8

pyasn1-modules         0.2.8

pydot                  1.4.2

pyflink                1.0

pymongo                3.12.3

pyparsing              3.0.7

python-dateutil        2.8.0

pytz                   2021.3

requests               2.27.1

rsa                    4.8

setuptools             59.6.0

six                    1.16.0

typing-extensions      3.7.4.3

urllib3                1.26.8

wheel                  0.37.1

I tried to run this command :

(virtualenv) [myuser@myvm flink-1.14.3] ./bin/flink run -py examples/python/table/word_count.py
And got the following error:

Caused by: java.io.IOException: Failed to execute the command: python -c import pyflink;import os;print(os.path.join(os.path.abspath(os.path.dirname(pyflink.file)), 'bin'))
output: Traceback (most recent call last):
File "", line 1, in
ImportError: No module named pyflink

I am sure pyflink package is already installed. Does anyone know why?

答:
To install PyFlink, you only need to execute:

python -m pip install apache-flink

and make sure you have a compatible Python version (>= 3.5).

The problem may be the Python Virtual Environment， refer to https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/python/faq/#preparing-python-virtual-environment

Also may be you can add option '-pyexec venv.zip/venv/bin/python3' and have a try


问:
Unexpected result of checking type of values in a list - with regards to Booleans
When I have a list containing different values, I tried to check the type of each value and got an unexpected output. It was the Booleans True and False which threw me off. Follows the code and the results.

```<code>trial_set = {1,2,3,4,None, True, False}

new_list = [type(x) for x in trial_set]
new_set = {type(x) for x in trial_set}

print(new_list)
print(new_set)
</code>```

Strange Boolean Type Behaviour

Questions:

Why does the  datatype appear first in the output though they are the last two elements in the list?

Why is there only one  datatype in output when I have two Booleans in the list?

I understand that Bool datatype is a substring of integer datatype and return 0 or 1 and I tried to figure this out from that angle but came up empty. Please help clarify.

Thank you in advance.

答:
The result is because of the way Python sets work as well as how Booleans work under the hood. Since True == 1 in python, only a single occurrence of 1 or True will appear, in this case 1.

Also, sets in python are unordered so when you iterate it with a comprehension to make a list, the order is not guaranteed to be as you typed it.

Body:
When I have a list containing different values, I tried to check the type of each value and got an unexpected output. It was the Booleans True and False which threw me off. Follows the code and the results.

trial_set = {1,2,3,4,None, True, False}

new_list = [type(x) for x in trial_set]
new_set = {type(x) for x in trial_set}

print(new_list)
print(new_set)

Strange Boolean Type Behaviour

Questions:

Why does the  datatype appear first in the output though they are the last two elements in the list?

Why is there only one  datatype in output when I have two Booleans in the list?

I understand that Bool datatype is a substring of integer datatype and return 0 or 1 and I tried to figure this out from that angle but came up empty. Please help clarify.

Thank you in advance.


问:
getting powershell to class ie and during a ui test take a screenshot of the ie window
So i'm running a ui test with power shell.

When i get an error i want to take a screen shot of just the ie window this can be done with alt print scrn

%{prtsc}

but it only takes a jpg of the active window.

I tryied this

 $h = (Get-Process iexplore).MainWindowHandle
 SetForegroundWindow((Get-Process -name iexplore).MainWindowHandle)
 sleep -sec 2
 $h = (Get-Process -id $pid).MainWindowHandle

Also any help with a way to identify ie error would be great thanks.

```<code>function screenshot
{
    param(
    [Switch]$OfWindow
    )
    begin {
        Add-Type -AssemblyName System.Drawing
        $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
            Where-Object { $_.FormatDescription -eq "JPEG" }
    }
    process {
        Start-Sleep -Milliseconds 250
        if ($OfWindow) {
        [Windows.Forms.Sendkeys]::SendWait("%{PrtSc}")
        } else {
            [Windows.Forms.Sendkeys]::SendWait("{PrtSc}")
        }

        Start-Sleep -Milliseconds 250
        $bitmap = [Windows.Forms.Clipboard]::GetImage()
        $ep = New-Object Drawing.Imaging.EncoderParameters
        $ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100)
        $screenCapturePathBase = "$pwd\ScreenCapture"
        $c = 0
        while (Test-Path "${screenCapturePathBase}${c}.jpg") {
            $c++}

        $bitmap.Save("${screenCapturePathBase}${c}.jpg", $jpegCodec, $ep)
    }
}
</code>```

答:
Setting the active window

There are a couple things you need to do differently.  First, you need to set the active window this way:

How to set foreground Window from Powershell event subscriber action

Getting the right window

Next, you need to deal with the fact that IE spawns at least two processes.  So you need to grab the right window.

```<code>$h = Get-Process | Where-Object {$_.MainWindowTitle -like "My website*"} | Select-Object -ExpandProperty MainWindowHandle
</code>```

Taking the screenshot

Now you can take the screenshot one of two ways.

Send PrtSc like JPBlanc showed you.

```<code>Add-Type -Assembly System.Windows.Forms
Start-Sleep -seconds 1

## Capture the current window
[System.Windows.Forms.Sendkeys]::SendWait("%{PrtSc}")
</code>```

Take-Screenshot script from PoschCode

Body:
So i'm running a ui test with power shell.

When i get an error i want to take a screen shot of just the ie window this can be done with alt print scrn

%{prtsc}

but it only takes a jpg of the active window.

I tryied this

 $h = (Get-Process iexplore).MainWindowHandle
 SetForegroundWindow((Get-Process -name iexplore).MainWindowHandle)
 sleep -sec 2
 $h = (Get-Process -id $pid).MainWindowHandle

Also any help with a way to identify ie error would be great thanks.

function screenshot
{
    param(
    [Switch]$OfWindow
    )
    begin {
        Add-Type -AssemblyName System.Drawing
        $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
            Where-Object { $_.FormatDescription -eq "JPEG" }
    }
    process {
        Start-Sleep -Milliseconds 250
        if ($OfWindow) {
        [Windows.Forms.Sendkeys]::SendWait("%{PrtSc}")
        } else {
            [Windows.Forms.Sendkeys]::SendWait("{PrtSc}")
        }

        Start-Sleep -Milliseconds 250
        $bitmap = [Windows.Forms.Clipboard]::GetImage()
        $ep = New-Object Drawing.Imaging.EncoderParameters
        $ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100)
        $screenCapturePathBase = "$pwd\ScreenCapture"
        $c = 0
        while (Test-Path "${screenCapturePathBase}${c}.jpg") {
            $c++}

        $bitmap.Save("${screenCapturePathBase}${c}.jpg", $jpegCodec, $ep)
    }
}

Body:
Setting the active window

There are a couple things you need to do differently.  First, you need to set the active window this way:

How to set foreground Window from Powershell event subscriber action

Getting the right window

Next, you need to deal with the fact that IE spawns at least two processes.  So you need to grab the right window.

$h = Get-Process | Where-Object {$_.MainWindowTitle -like "My website*"} | Select-Object -ExpandProperty MainWindowHandle

Taking the screenshot

Now you can take the screenshot one of two ways.

Send PrtSc like JPBlanc showed you.

Add-Type -Assembly System.Windows.Forms
Start-Sleep -seconds 1

## Capture the current window
[System.Windows.Forms.Sendkeys]::SendWait("%{PrtSc}")

Take-Screenshot script from PoschCode


问:
How to save result of /api/page to state
I'm trying to authenticate to Xero's API. I get a 'code' which is then exchanged for an access_token. I'm still new to NextJS and React so I'm likely not thinking about this correctly.

The code I have results in the right data being returned, however I don't know how to use it effectively in the rest of the app. I couldn't figure out how to use NextAuth in a custom provider so tried to roll my own.

The user clicks the button 'Connect to Xero' - this is a href to initiate the process and takes the user to Xero to login in the browser. User authenticates. Xero calls the callback

the callback at /api/callback responds

I extract the 'code' and then make the subsequent request to Xero to swap it for an access token.

This is where I get stuck - because the initial action is a href redirect, I'm not sure how to get the end API result back into my code as state/something usable. In effect Xero is calling the api/callback page and that's where the user is left.

I've tried to put useState hooks into the api/callback however that breaks the rule of hooks.

Any pointers greatly appreciated.

Code;

pages/index.js

```<code>import React from 'react'
import Layout from '../components/Layout'
import TopNav from '../components/TopNav'
import Link from 'next/link';

export default function Main(props) {

  const test = props.URL

  return (
    <>
      <Layout>
        <TopNav name="Main page"/>
        <p>this is the main page</p>

        <Link href={test} passHref={true}>
          <button className=' w-40 border rounded-md py-3 px-3 flex items-center justify-center text-sm font-medium sm:flex-1'>
            Connect to Xero
          </button>
        </Link>
      </Layout>
    </>
  )
}

export async function getStaticProps() {
  const XeroAuthURL = "https://login.xero.com/identity/connect/authorize?response_type=code&client_id="
  const client_ID = process.env.XERO_CLIENT_ID
  const redirect_uri = process.env.XERO_REDIRECT_URI
  const scope = "offline_access openid profile email accounting.settings"

  const URL = `${XeroAuthURL}${client_ID}&redirect_uri=${redirect_uri}&scope=${scope}`

  return {
    props: {
      URL: URL
    },
  };
}
</code>```

/api/callback.js

```<code>import axios from "axios"
const qs = require('qs');

export default async function callback(req, res) {

    try {
        //callback from Xero will deliver the code, scope + state (if given)
        //https://developer.xero.com/documentation/guides/oauth2/auth-flow/#2-users-are-redirected-back-to-you-with-a-code
        console.log(`REQ = ${JSON.stringify(req.query)}`)

       //exchange code for tokens - https://developer.xero.com/documentation/guides/oauth2/auth-flow/#3-exchange-the-code
        var data = qs.stringify({
            'code': req.query.code,
            'grant_type': 'authorization_code',
            'redirect_uri': 'http://localhost:3000/api/callback'
          });

        var config = {
            method: 'post',
            url: 'https://identity.xero.com/connect/token',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic **put your authorisation result here**'
            },
            data : data
        };

        try {
            const response = await axios(config)
            //response has the data I want to put into State
            console.log(JSON.stringify(response.data));
              //save data off here somehow???
              //tried redirecting but unsure if can pass the result
              res.redirect(307, '/')

        } catch (error) {
            console.error(error)
            res.status(error.status || 500).end(error.message)
        }

    } catch (error) {
      console.error(error)
      res.status(error.status || 500).end(error.message)
    }
  }
</code>```

答:
Added a not-secure cookie that I can use while testing. Do not use this in production as the cookie is not httpOnly and not secure.

```<code>import axios from "axios"
import Cookies from 'cookies'
const qs = require('qs');

export default async function callback(req, res) {

    const cookies = new Cookies(req,res)
    try {

        var data = qs.stringify({
            'code': req.query.code,
            'grant_type': 'authorization_code',
            'redirect_uri': 'http://localhost:3000/api/callback'
          });

        var config = {
            method: 'post',
            url: 'https://identity.xero.com/connect/token',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic **YOUR AUTH CODE HERE**'
            },
            data : data
        };

        try {
            var response = await axios(config)
            response.data.expires_at = Date.now() + response.data.expires_in*1000
              //save data off
              //TO DO - THIS IS REALLY BAD - ONLY USE THIS TEMPORARILY UNTIL HAVE GOT PERMSTORAGE SETUP
              cookies.set('myCookieName', JSON.stringify(response.data), {
                secure: false,
                httpOnly: false
              }
            )
              res.redirect(307, '/')
              //return ({ data: response.data })

        } catch (error) {
            console.error(error)
            res.status(error.status || 500).end(error.message)
        }

    } catch (error) {
      console.error(error)
      res.status(error.status || 500).end(error.message)
    }
  }
</code>```

Then in the index;

```<code>import React from 'react'
import Layout from '../components/Layout'
import TopNav from '../components/TopNav'
import Link from 'next/link';
import { getCookie } from 'cookies-next';

export default function Main(props) {

  //check for cookie
  //TO DO THIS IS REALLY BAD; CHANGE WHEN GET PERM STORAGE ORGANISED
  const cookie = getCookie('myCookieName');

  const URL = props.URL

  return (
    <>
      <Layout>
        <TopNav name="Main page"/>
        <p>this is the main page</p>

        <Link href={URL} passHref={true}>
          <button className=' w-40 border rounded-md py-3 px-3 flex items-center justify-center text-sm font-medium sm:flex-1'>
            Connect to Xero
          </button>
        </Link>
        <p>{cookie ? cookie : 'waiting for cookie...'}</p>
      </Layout>
    </>
  )
}

export async function getStaticProps() {
  const XeroAuthURL = "https://login.xero.com/identity/connect/authorize?response_type=code&client_id="
  const client_ID = process.env.XERO_CLIENT_ID
  const redirect_uri = process.env.XERO_REDIRECT_URI
  const scope = "offline_access openid profile email accounting.settings"

  //console.log(`URL - ${XeroAuthURL}${client_ID}&redirect_uri=${redirect_uri}&scope=${scope}`)
  const URL = `${XeroAuthURL}${client_ID}&redirect_uri=${redirect_uri}&scope=${scope}`

  return {
    props: {
      URL: URL,
    },
  };
}
</code>```

Body:
I'm trying to authenticate to Xero's API. I get a 'code' which is then exchanged for an access_token. I'm still new to NextJS and React so I'm likely not thinking about this correctly.

The code I have results in the right data being returned, however I don't know how to use it effectively in the rest of the app. I couldn't figure out how to use NextAuth in a custom provider so tried to roll my own.

The user clicks the button 'Connect to Xero' - this is a href to initiate the process and takes the user to Xero to login in the browser. User authenticates. Xero calls the callback

the callback at /api/callback responds

I extract the 'code' and then make the subsequent request to Xero to swap it for an access token.

This is where I get stuck - because the initial action is a href redirect, I'm not sure how to get the end API result back into my code as state/something usable. In effect Xero is calling the api/callback page and that's where the user is left.

I've tried to put useState hooks into the api/callback however that breaks the rule of hooks.

Any pointers greatly appreciated.

Code;

pages/index.js

import React from 'react'
import Layout from '../components/Layout'
import TopNav from '../components/TopNav'
import Link from 'next/link';

export default function Main(props) {

  const test = props.URL

  return (
    <>
      <Layout>
        <TopNav name="Main page"/>

this is the main page

        <Link href={test} passHref={true}>
          <button className=' w-40 border rounded-md py-3 px-3 flex items-center justify-center text-sm font-medium sm:flex-1'>
            Connect to Xero
          </button>
        </Link>
      </Layout>
    </>
  )
}

export async function getStaticProps() {
  const XeroAuthURL = "https://login.xero.com/identity/connect/authorize?response_type=code&client_id="
  const client_ID = process.env.XERO_CLIENT_ID
  const redirect_uri = process.env.XERO_REDIRECT_URI
  const scope = "offline_access openid profile email accounting.settings"

  const URL = `${XeroAuthURL}${client_ID}&redirect_uri=${redirect_uri}&scope=${scope}`

  return {
    props: {
      URL: URL
    },
  };
}

/api/callback.js

import axios from "axios"
const qs = require('qs');

export default async function callback(req, res) {

    try {
        //callback from Xero will deliver the code, scope + state (if given)
        //https://developer.xero.com/documentation/guides/oauth2/auth-flow/#2-users-are-redirected-back-to-you-with-a-code
        console.log(`REQ = ${JSON.stringify(req.query)}`)

       //exchange code for tokens - https://developer.xero.com/documentation/guides/oauth2/auth-flow/#3-exchange-the-code
        var data = qs.stringify({
            'code': req.query.code,
            'grant_type': 'authorization_code',
            'redirect_uri': 'http://localhost:3000/api/callback'
          });

        var config = {
            method: 'post',
            url: 'https://identity.xero.com/connect/token',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic **put your authorisation result here**'
            },
            data : data
        };

        try {
            const response = await axios(config)
            //response has the data I want to put into State
            console.log(JSON.stringify(response.data));
              //save data off here somehow???
              //tried redirecting but unsure if can pass the result
              res.redirect(307, '/')

        } catch (error) {
            console.error(error)
            res.status(error.status || 500).end(error.message)
        }

    } catch (error) {
      console.error(error)
      res.status(error.status || 500).end(error.message)
    }
  }

Body:
Added a not-secure cookie that I can use while testing. Do not use this in production as the cookie is not httpOnly and not secure.

import axios from "axios"
import Cookies from 'cookies'
const qs = require('qs');

export default async function callback(req, res) {

    const cookies = new Cookies(req,res)
    try {

        var data = qs.stringify({
            'code': req.query.code,
            'grant_type': 'authorization_code',
            'redirect_uri': 'http://localhost:3000/api/callback'
          });

        var config = {
            method: 'post',
            url: 'https://identity.xero.com/connect/token',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic **YOUR AUTH CODE HERE**'
            },
            data : data
        };

        try {
            var response = await axios(config)
            response.data.expires_at = Date.now() + response.data.expires_in*1000
              //save data off
              //TO DO - THIS IS REALLY BAD - ONLY USE THIS TEMPORARILY UNTIL HAVE GOT PERMSTORAGE SETUP
              cookies.set('myCookieName', JSON.stringify(response.data), {
                secure: false,
                httpOnly: false
              }
            )
              res.redirect(307, '/')
              //return ({ data: response.data })

        } catch (error) {
            console.error(error)
            res.status(error.status || 500).end(error.message)
        }

    } catch (error) {
      console.error(error)
      res.status(error.status || 500).end(error.message)
    }
  }

Then in the index;

import React from 'react'
import Layout from '../components/Layout'
import TopNav from '../components/TopNav'
import Link from 'next/link';
import { getCookie } from 'cookies-next';

export default function Main(props) {

  //check for cookie
  //TO DO THIS IS REALLY BAD; CHANGE WHEN GET PERM STORAGE ORGANISED
  const cookie = getCookie('myCookieName');

  const URL = props.URL

  return (
    <>
      <Layout>
        <TopNav name="Main page"/>
        <p>this is the main page</p>

        <Link href={URL} passHref={true}>
          <button className=' w-40 border rounded-md py-3 px-3 flex items-center justify-center text-sm font-medium sm:flex-1'>
            Connect to Xero
          </button>
        </Link>
        <p>{cookie ? cookie : 'waiting for cookie...'}</p>
      </Layout>
    </>
  )
}

export async function getStaticProps() {
  const XeroAuthURL = "https://login.xero.com/identity/connect/authorize?response_type=code&client_id="
  const client_ID = process.env.XERO_CLIENT_ID
  const redirect_uri = process.env.XERO_REDIRECT_URI
  const scope = "offline_access openid profile email accounting.settings"

  //console.log(`URL - ${XeroAuthURL}${client_ID}&redirect_uri=${redirect_uri}&scope=${scope}`)
  const URL = `${XeroAuthURL}${client_ID}&redirect_uri=${redirect_uri}&scope=${scope}`

  return {
    props: {
      URL: URL,
    },
  };
}


问:
Open Mat-Select Drop down in Angular when focus comes on Mat-Select
I want to open Mat-Select Drop down when I press Tab key if coming from previous field or Shift + Tab if coming from the next field after Drop Down. How to achieve this ?

Now, as in the image - Account Type is my Mat-Select Drop Down. So if I press tab key from Account Name focus will shift to Account Type but I want to open the Drop Down. Like Wise if I Press Shift + Tab key combination from Company I want to open Drop - Down of Account Type.

I went through all the Angular Material Select API's but not able to achieve my goal.

This is my Account Type Drop Down Code -

```<code><div class="row">
    <div class="col-lg-4 col-md-4 col-sm-12 col-label-line-height">
        <mat-label>Account Type </mat-label>
    </div>
    <div class="col-lg-8 col-md-8 col-sm-12">
        <mat-form-field>
            <mat-select formControlName="AccountTypeCode" [disabled]="this.DataService.LeaseCount" [(ngModel)]="AccountModel.AccountTypeCode">
                <mat-option *ngFor="let AccountType of this.AccountTypeList" [value]="AccountType.Code">
                {{ AccountType.Name }}
                </mat-option>
            </mat-select>
            <mat-error *ngIf="hasError('AccountTypeCode', 'required')">Account Type is required</mat-error>
            <mat-error *ngIf="hasError('CompanyCode', 'min')">Account Type is required</mat-error>
        </mat-form-field>
    </div>
</div>
</code>```

So far, I have tried -

```<code><div class="row">
    <div class="col-lg-4 col-md-4 col-sm-12 col-label-line-height">
        <mat-label>Account Type </mat-label>
    </div>
    <div class="col-lg-8 col-md-8 col-sm-12">
        <mat-form-field>
            <mat-select (open)="matSelectOpen($event)" formControlName="AccountTypeCode" [disabled]="this.DataService.LeaseCount" [(ngModel)]="AccountModel.AccountTypeCode">
                <mat-option *ngFor="let AccountType of this.AccountTypeList" [value]="AccountType.Code">
                {{ AccountType.Name }}
                </mat-option>
            </mat-select>
            <mat-error *ngIf="hasError('AccountTypeCode', 'required')">Account Type is required</mat-error>
            <mat-error *ngIf="hasError('CompanyCode', 'min')">Account Type is required</mat-error>
        </mat-form-field>
    </div>
</div>
</code>```

In .ts File -

```<code>matSelectOpen(e) {
    Console.log(e); //just to check whether function is called or not
}
</code>```

I have also tried with event as follows : -

(trigger)="matSelectOpen($event)"

(panelOpen)="matSelectOpen($event)"

Any help would be appreciated.

答:
try this：</p>
```<code> <mat-form-field appearance="fill">
        <mat-select (focus)="openedChange()">
          <mat-option *ngFor="let rcvFile of rcvFileList" [value]="rcvFile.src" placeholder="选择">

          </mat-option>
        </mat-select>
      </mat-form-field>
</code>```

Body:
I want to open Mat-Select Drop down when I press Tab key if coming from previous field or Shift + Tab if coming from the next field after Drop Down. How to achieve this ?

Now, as in the image - Account Type is my Mat-Select Drop Down. So if I press tab key from Account Name focus will shift to Account Type but I want to open the Drop Down. Like Wise if I Press Shift + Tab key combination from Company I want to open Drop - Down of Account Type.

I went through all the Angular Material Select API's but not able to achieve my goal.

This is my Account Type Drop Down Code -

        <mat-label>Account Type </mat-label>

        <mat-form-field>
            <mat-select formControlName="AccountTypeCode" [disabled]="this.DataService.LeaseCount" [(ngModel)]="AccountModel.AccountTypeCode">
                <mat-option *ngFor="let AccountType of this.AccountTypeList" [value]="AccountType.Code">
                {{ AccountType.Name }}
                </mat-option>
            </mat-select>
            <mat-error *ngIf="hasError('AccountTypeCode', 'required')">Account Type is required</mat-error>
            <mat-error *ngIf="hasError('CompanyCode', 'min')">Account Type is required</mat-error>
        </mat-form-field>

So far, I have tried -

        <mat-label>Account Type </mat-label>

        <mat-form-field>
            <mat-select (open)="matSelectOpen($event)" formControlName="AccountTypeCode" [disabled]="this.DataService.LeaseCount" [(ngModel)]="AccountModel.AccountTypeCode">
                <mat-option *ngFor="let AccountType of this.AccountTypeList" [value]="AccountType.Code">
                {{ AccountType.Name }}
                </mat-option>
            </mat-select>
            <mat-error *ngIf="hasError('AccountTypeCode', 'required')">Account Type is required</mat-error>
            <mat-error *ngIf="hasError('CompanyCode', 'min')">Account Type is required</mat-error>
        </mat-form-field>

In .ts File -

matSelectOpen(e) {
    Console.log(e); //just to check whether function is called or not
}

I have also tried with event as follows : -

(trigger)="matSelectOpen($event)"

(panelOpen)="matSelectOpen($event)"

Any help would be appreciated.

Body:
try this：

 <mat-form-field appearance="fill">
        <mat-select (focus)="openedChange()">
          <mat-option *ngFor="let rcvFile of rcvFileList" [value]="rcvFile.src" placeholder="选择">

          </mat-option>
        </mat-select>
      </mat-form-field>


问:
I have an string and i want to delete from a specific character to the end of the string in JavaScript
i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].

How can i do this?

答:
You can use substring which extract the characters between two specified index without changing the original string

const yourString = 'someRandomText&ab_channel=thisPartCanChange';
const newStr = yourString.substring(0, yourString.indexOf('&'));
console.log(newStr)```


问:
TypeORM migration with nx-Monorepo Issue
I tried this a lot but now I think I need some help.
I have a nx-monorepo with angular-frontend and nestjs backend. Now I added a Postgres-SQL database with TypeORM. Everything is working fine, connection to Database is running, api-calls coming in, etc.
But I can't add the generate migration script. I added a run-command for my backend-project:

```<code>    "generate-migration": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "ts-node ../../node_modules/.bin/typeorm migration:generate -n",
        "cwd": "apps/api"
      }
    }
</code>```

I can run the command by "npm run api:generate-migration" but it results with this error:

Error during migration generation:
/apps/api/src/model/base.entity.ts:1
import { __decorate, __metadata } from "tslib";
^^^^^^

SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1024:16)
at Module._compile (node:internal/modules/cjs/loader:1072:27)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1056:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Object.require.extensions. [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1059:12)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at /Users/IsabelleGlasmacher/Documents/Programme/save_easytonomy/src/util/DirectoryExportedClassesLoader.ts:41:22
ERROR: Something went wrong in @nrwl/run-commands - Command failed: ts-node ../../node_modules/.bin/typeorm migration:generate -n

ormConfig.json:

```<code>{
  ...
  "type": "postgres",
  "migrationsTableName": "migration",
  "migrations": ["src/migration/*.ts"],
  "cli": {
    "migrationsDir": "src/migration"
  },
  "ssl": false
}
</code>```

Does anybody know something about that and could help me? Please :)

答:
I am able to make a backend service using NX@13, NestJS@8 and TypeORM@0.2,

In project.json of game-api , I added some commands like this

```<code>"generate-migration": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "ts-node --project tsconfig.app.json ../../node_modules/.bin/typeorm migration:generate --pretty -f .env.local",
        "cwd": "apps/game-api"
      }
    },
</code>```

Code repository: https://github.com/coinconket/conketkemon

Body:
I tried this a lot but now I think I need some help.
I have a nx-monorepo with angular-frontend and nestjs backend. Now I added a Postgres-SQL database with TypeORM. Everything is working fine, connection to Database is running, api-calls coming in, etc.
But I can't add the generate migration script. I added a run-command for my backend-project:

    "generate-migration": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "ts-node ../../node_modules/.bin/typeorm migration:generate -n",
        "cwd": "apps/api"
      }
    }

I can run the command by "npm run api:generate-migration" but it results with this error:

Error during migration generation:
/apps/api/src/model/base.entity.ts:1
import { __decorate, __metadata } from "tslib";
^^^^^^

SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1024:16)
at Module._compile (node:internal/modules/cjs/loader:1072:27)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1056:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Object.require.extensions. [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1059:12)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at /Users/IsabelleGlasmacher/Documents/Programme/save_easytonomy/src/util/DirectoryExportedClassesLoader.ts:41:22
ERROR: Something went wrong in @nrwl/run-commands - Command failed: ts-node ../../node_modules/.bin/typeorm migration:generate -n

ormConfig.json:

{
  ...
  "type": "postgres",
  "migrationsTableName": "migration",
  "migrations": ["src/migration/*.ts"],
  "cli": {
    "migrationsDir": "src/migration"
  },
  "ssl": false
}

Does anybody know something about that and could help me? Please :)

Body:
I am able to make a backend service using NX@13, NestJS@8 and TypeORM@0.2,

In project.json of game-api , I added some commands like this

"generate-migration": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "ts-node --project tsconfig.app.json ../../node_modules/.bin/typeorm migration:generate --pretty -f .env.local",
        "cwd": "apps/game-api"
      }
    },

Code repository: https://github.com/coinconket/conketkemon


问:
Node stream pipeline stops prematurely
Think of this piece of code as a relay between a NAT-ted service (input) and an external service (output) that wants to communicate with the input.

This relay is on a public server and opens two ports in order to relay:

port 4040 where input connects and forwards the TCP traffic from target service

port 4041 where some external client connects to the relay

The relay should pipe what it receives from input on port 4040 to the external client on port 4041.

I can see both services connecting to the relay but the data flow just stops after, what I suspect the output socket closing. In the following example I used a stream.pipeline but I also tried with simple .pipe directly on the sockets with same results

import net from "net"
import stream from "stream";

```<code>export default () => {
    const inputServer = net.createServer();
    const outputServer = net.createServer();

    inputServer.listen(4040, "0.0.0.0", () => {
        console.log('TCP Server is running on port ' + 4040 + '.');
    });

    outputServer.listen(4041, "0.0.0.0", () => {
        console.log('TCP Server is running on port ' + 4041 + '.');
    });

    let inSocket = null;
    inputServer.on('connection', (sock) => {
        inSocket = sock;
    });

    outputServer.on('connection', (sock) => {
        if (inSocket) {
            stream.pipeline(inSocket, sock, (err) => {
                if (err) {
                    console.error('Pipeline failed.', err);
                } else {
                    console.log('Pipeline succeeded.');
                }
            })

            stream.pipeline(sock, inSocket, (err) => {
                if (err) {
                    console.error('Pipeline failed.', err);
                } else {
                    console.log('Pipeline succeeded.');
                }
            })
        }
    });
}
</code>```

My goal is to keep an open socket to the input service and relay with any output will connect.

答:
data flow just stops after, what I suspect the output socket closing

pipeline or .pipe() will automatically close the output stream when the input stream ends so it won't keep your input stream open for successive input stream connections.

Using .pipe(), you can override that behavior by passing an option:

```<code>inSocket.pipe(sock, {end: false});
</code>```

and

```<code>sock.pipe(inSocket, {end: false});
</code>```

You will then need some separate error handling for each stream as .pipe() doesn't do as complete error handling as pipeline() does.

In this way, you let each stream close itself when the client chooses rather than having the server close it when a given streaming operation is complete.

I don't see a similar option for pipeline().

I'm also curious how you plan to use this.  Do you intend for there to be one  long connected inSocket and many separate connections to the outputServer?  Do you intend or need more than one outputServer connection at once?  Or just one at at time.  Since you're not auto destroying, I wonder if you need to do some manual cleanup (unpiping, for example) when any socket disconnects?  .pipe() is also famous for not unwinding all its event listeners which can sometimes lead to GC issues if you don't manually clean up things properly.

Title: Node stream pipeline stops prematurely

Body:
Think of this piece of code as a relay between a NAT-ted service (input) and an external service (output) that wants to communicate with the input.

This relay is on a public server and opens two ports in order to relay:

port 4040 where input connects and forwards the TCP traffic from target service

port 4041 where some external client connects to the relay

The relay should pipe what it receives from input on port 4040 to the external client on port 4041.

I can see both services connecting to the relay but the data flow just stops after, what I suspect the output socket closing. In the following example I used a stream.pipeline but I also tried with simple .pipe directly on the sockets with same results

import net from "net"
import stream from "stream";

export default () => {
    const inputServer = net.createServer();
    const outputServer = net.createServer();

    inputServer.listen(4040, "0.0.0.0", () => {
        console.log('TCP Server is running on port ' + 4040 + '.');
    });

    outputServer.listen(4041, "0.0.0.0", () => {
        console.log('TCP Server is running on port ' + 4041 + '.');
    });

    let inSocket = null;
    inputServer.on('connection', (sock) => {
        inSocket = sock;
    });

    outputServer.on('connection', (sock) => {
        if (inSocket) {
            stream.pipeline(inSocket, sock, (err) => {
                if (err) {
                    console.error('Pipeline failed.', err);
                } else {
                    console.log('Pipeline succeeded.');
                }
            })

            stream.pipeline(sock, inSocket, (err) => {
                if (err) {
                    console.error('Pipeline failed.', err);
                } else {
                    console.log('Pipeline succeeded.');
                }
            })
        }
    });
}

My goal is to keep an open socket to the input service and relay with any output will connect.

Body:
data flow just stops after, what I suspect the output socket closing

pipeline or .pipe() will automatically close the output stream when the input stream ends so it won't keep your input stream open for successive input stream connections.

Using .pipe(), you can override that behavior by passing an option:

inSocket.pipe(sock, {end: false});

and

sock.pipe(inSocket, {end: false});

You will then need some separate error handling for each stream as .pipe() doesn't do as complete error handling as pipeline() does.

In this way, you let each stream close itself when the client chooses rather than having the server close it when a given streaming operation is complete.

I don't see a similar option for pipeline().

I'm also curious how you plan to use this.  Do you intend for there to be one  long connected inSocket and many separate connections to the outputServer?  Do you intend or need more than one outputServer connection at once?  Or just one at at time.  Since you're not auto destroying, I wonder if you need to do some manual cleanup (unpiping, for example) when any socket disconnects?  .pipe() is also famous for not unwinding all its event listeners which can sometimes lead to GC issues if you don't manually clean up things properly.


问:
How to reinitialize the Python console in PyCharm?
I've seen other IDEs have the option to right click and reinitialize the environment. Does anyone know if this is possible in PyCharm, and if so, how it's done?</p>

答:
I had tried "rerun" and found that it didn't reload the new environment.
I suggest that "new console" button could help you to reload the environment that it had installed the new packages.</p>


问:
Getting Module parse failed: Unexpected token (1:0) error when I try to import css file for a specific component in react
I am building a gym website using React and Django.
I am getting this error when I try to import external css file in my Homepage component.Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

```<code>> #mainDiv{
|     position: absolute;
|     top: 50%;
 @ ./src/components/HomePage.js 4:0-28
 @ ./src/components/App.js 3:0-34 10:90-98
 @ ./src/index.js 1:0-35

webpack 5.68.0 compiled with 1 error and 1 warning in 2286 ms
</code>```

This my component code:

```<code>    import ReactDom from "react-dom";
import Navbar from "./Navbar";
import React, { Component } from "react";
import "./css/Homepage.css";

export default class HomePage extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <body>
        {/*<Navbar />*/}
        <div id="mainDiv" className="container">
          <div id="Homepgbtn1" className="mainbtns">
            <button type="button" class="btn btn-success">
              Plans
            </button>
          </div>
          <div id="Homepgbtn2" className="mainbtns ">
            <button type="button" class="btn btn-success">
              Get Started
            </button>
          </div>
        </div>
        <div id="rbdiv">
          <button type="button" class="btn btn-light">
            Instagram
          </button>
          <button type="button" class="btn btn-light">
            Twitter
          </button>
          <button type="button" class="btn btn-light">
            Youtube
          </button>
        </div>
      </body>
    );
  }
}
</code>```

This is my webpack.config.js code:

```<code>const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  optimization: {
    minimize: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        // This has effect on the react lib size
        NODE_ENV: JSON.stringify("production"),
      },
    }),
  ],
};
</code>```

This is my package.json:

```<code>{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "babel-loader": "^8.2.3",
    "css-loader": "^6.6.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "webpack": "^5.68.0",
    "webpack-cli": "^4.9.2"
  },
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.16.7",
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "react-router-dom": "^5.2.0"
  }
}
</code>```

please help me out guys stuck on this thing from 36 hours

答:
Webpack doesn't understand CSS files out of box. You need to use css-loader with style-loader to handle CSS files.

```<code>module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      // Additional configuration to handle *.css files
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  // Other remaining configuration
};
</code>```

Body:
I am building a gym website using React and Django.
I am getting this error when I try to import external css file in my Homepage component.Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

> #mainDiv{
|     position: absolute;
|     top: 50%;
 @ ./src/components/HomePage.js 4:0-28
 @ ./src/components/App.js 3:0-34 10:90-98
 @ ./src/index.js 1:0-35

webpack 5.68.0 compiled with 1 error and 1 warning in 2286 ms

This my component code:

    import ReactDom from "react-dom";
import Navbar from "./Navbar";
import React, { Component } from "react";
import "./css/Homepage.css";

export default class HomePage extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (

        {/*<Navbar />*/}

            <button type="button" class="btn btn-success">
              Plans
            </button>

            <button type="button" class="btn btn-success">
              Get Started
            </button>

          <button type="button" class="btn btn-light">
            Instagram
          </button>
          <button type="button" class="btn btn-light">
            Twitter
          </button>
          <button type="button" class="btn btn-light">
            Youtube
          </button>

    );
  }
}

This is my webpack.config.js code:

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  optimization: {
    minimize: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        // This has effect on the react lib size
        NODE_ENV: JSON.stringify("production"),
      },
    }),
  ],
};

This is my package.json:

{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "babel-loader": "^8.2.3",
    "css-loader": "^6.6.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "webpack": "^5.68.0",
    "webpack-cli": "^4.9.2"
  },
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.16.7",
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "react-router-dom": "^5.2.0"
  }
}

please help me out guys stuck on this thing from 36 hours

Body:
Webpack doesn't understand CSS files out of box. You need to use css-loader with style-loader to handle CSS files.

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      // Additional configuration to handle *.css files
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  // Other remaining configuration
};


答:
A simplified version of the one suggested by @stack0114106 is

```<code>val df = Seq(("Ram",null,"MCA","Bangalore"),(null,"25",null,null),
             (null,"26","BE",null),("Raju","21","Btech","Chennai"))
        .toDF("name","age","degree","Place")
        .withColumn("null_count", lit(0))

val df2 = df.columns.foldLeft(df)((df,c) =>
            df.withColumn("null_count",
                when(col(c).isNull,$"null_count" + 1).otherwise($"null_count")
            )
        )
df2.show(false)
</code>```

the output is

```<code>+----+----+------+---------+----------+
|name|age |degree|Place    |null_count|
+----+----+------+---------+----------+
|Ram |null|MCA   |Bangalore|1         |
|null|25  |null  |null     |3         |
|null|26  |BE    |null     |2         |
|Raju|21  |Btech |Chennai  |0         |
+----+----+------+---------+----------+
</code>```

Title: How to count the number of missing values in each row of a data frame -spark scala?

Body:
I want to count the number of missing values in each row of a data frame in spark scala.

Code:

val samplesqlDF = spark.sql("SELECT * FROM sampletable")

samplesqlDF.show()

Input Dataframe:

    ------------------------------------------------------------------
   | name       |     age             |  degree    | Place            |
   | -----------------------------------------------------------------|
   | Ram        |                     |    MCA     | Bangalore        |
   |            |     25              |            |                  |
   |            |     26              |     BE     |                  |
   | Raju       |     21              |     Btech  |  Chennai         |
   -----------------------------------------------------------------

The Output Data frame (Row Level Count) as follows:

    -----------------------------------------------------------------
   | name       |     age   |  degree    | Place      |   rowcount   |
   | ----------------------------------------------------------------|
   | Ram        |           |    MCA     | Bangalore  |   1          |
   |            |     25    |            |            |   3          |
   |            |     26    |     BE     |            |   2          |
   | Raju       |     21    |    Btech   |  Chennai   |   0          |
   -----------------------------------------------------------------

I am a beginner to scala and spark. Thanks in advance.

Body:
A simplified version of the one suggested by @stack0114106 is

val df = Seq(("Ram",null,"MCA","Bangalore"),(null,"25",null,null),
             (null,"26","BE",null),("Raju","21","Btech","Chennai"))
        .toDF("name","age","degree","Place")
        .withColumn("null_count", lit(0))

val df2 = df.columns.foldLeft(df)((df,c) =>
            df.withColumn("null_count",
                when(col(c).isNull,$"null_count" + 1).otherwise($"null_count")
            )
        )
df2.show(false)

the output is

+----+----+------+---------+----------+
|name|age |degree|Place    |null_count|
+----+----+------+---------+----------+
|Ram |null|MCA   |Bangalore|1         |
|null|25  |null  |null     |3         |
|null|26  |BE    |null     |2         |
|Raju|21  |Btech |Chennai  |0         |
+----+----+------+---------+----------+


问:
Copy and paste same values from 2 columns
I was hoping to be able to have a macro that would be able to extract the ID from each of our orders and put them into table 3.

答:
Lookup Data (Excel Tables)

Option Explicit

Sub LookupData()

    Const lName As String = "Sheet1"
    Const ltName As String = "Table1"
    Const lcName As String = "Table 1"

    Const sName As String = "Sheet1"
    Const stName As String = "Table2"
    Const sclName As String = "Table 2"
    Const scvName As String = "ID"

    Const dName As String = "Sheet2"
    Const dtName As String = "Table3"
    Const dclName As String = "Table 3 (RESULTS)"
    Const dcvName As String = "ID"

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Lookup
    Dim lws As Worksheet: Set lws = wb.Worksheets(lName)
    Dim ltbl As ListObject: Set ltbl = lws.ListObjects(ltName)
    Dim lrCount As Long: lrCount = ltbl.Range.Rows.Count
    Dim lcl As ListColumn: Set lcl = ltbl.ListColumns(lcName) ' Lookup Column

    ' Source
    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim stbl As ListObject: Set stbl = sws.ListObjects(stName)
    Dim scl As ListColumn: Set scl = stbl.ListColumns(sclName)
    Dim slrg As Range: Set slrg = scl.DataBodyRange ' Lookup Column
    Dim scv As ListColumn: Set scv = stbl.ListColumns(scvName)
    Dim svrg As Range: Set svrg = scv.DataBodyRange
    Dim svData As Variant: svData = svrg.Value ' Value Array

    ' Destination
    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    Dim dtbl As ListObject: Set dtbl = dws.ListObjects(dtName)
    Dim drCount As Long: drCount = dtbl.Range.Rows.Count
    Dim dcl As ListColumn: Set dcl = dtbl.ListColumns(dclName) ' written to
    Dim dcv As ListColumn: Set dcv = dtbl.ListColumns(dcvName) ' written to

    ' Copy lookup column.
    dcl.DataBodyRange.Resize(lrCount - 1).Value = lcl.DataBodyRange.Value

    Dim lData As Variant: lData = lcl.DataBodyRange.Value ' Lookup Array
    Dim dvData As Variant: ReDim dvData(1 To lrCount - 1, 1 To 1) ' Value Array

    Dim sIndex As Variant
    Dim r As Long

    ' Match value data.
    For r = 1 To lrCount - 1
        sIndex = Application.Match(lData(r, 1), slrg, 0)
        If IsNumeric(sIndex) Then
            dvData(r, 1) = svData(sIndex, 1)
        End If
    Next r

    ' Copy value array to value range.
    dcv.DataBodyRange.Value = dvData

    If lrCount < drCount Then
        ' Resize and clear.
        dtbl.Resize dtbl.Range.Resize(lrCount)
        dtbl.DataBodyRange.Resize(drCount - lrCount).Offset(lrCount - 1).Clear
    End If

End Sub
```


问:
How to rotate a character by 90 degrees in python?
I'm trying to rotate the character | sideways by 90 degrees, think of a longer - and then print it.

would appreciate the help as to how I can do that?

答:
Can you just print an em dash, "—"? In many fonts, an em dash is as long as the font's letters are tall.

Here's some example code that "rotates" the "|" symbol in the console in a complete circle for a loading animation by replacing it with em dashes and forward and backward slashes.

import time
import sys

def loadingAnimation():
    #Run for 10 seconds
    timeToRun = time.time() + 10
    while time.time() < timeToRun:
        wheelAnim = ['|','/','—','\\']
        for frame in wheelAnim:
            sys.stdout.write('\rLoading... %s' % frame)
            #Hold each frame for 0.15 seconds
            time.sleep(0.15)
            sys.stdout.flush()

    sys.stdout.write('\rLoading... complete.\n')

loadingAnimation()
```


问:
CSS :after transition (on hover)
I am using :after to create a hover over design (long story, in WP with VC) and am not trying to get the :after CSS to fade in when someone hovers over the initial div.

Here is a fiddle - click here

Below is my approach:

```<code>.border-home:hover:after {
    position: absolute;
    top: 0%;
    left: 0;
    right: 0;
    bottom: 0;
    background: url(http://i.imgur.com/3Si5tIy.png) 50% 50% no-repeat;
    background-size: 190px 50px;
    content: '';
    cursor: pointer;
    background-color: rgba(127, 165, 61, 0.9);
}
</code>```

I am struggling to make the green background and read more button fade in smoothly.

How can I achieve that?

答:
The same as connexo

.style::after {
    width: 0;
    transition: width 0.5s;
}

.style:hover::after {
    width: 100%;
}
```

Title: CSS :after transition (on hover)

Body:
I am using :after to create a hover over design (long story, in WP with VC) and am not trying to get the :after CSS to fade in when someone hovers over the initial div.

Here is a fiddle - click here

Below is my approach:

.border-home:hover:after {
    position: absolute;
    top: 0%;
    left: 0;
    right: 0;
    bottom: 0;
    background: url(http://i.imgur.com/3Si5tIy.png) 50% 50% no-repeat;
    background-size: 190px 50px;
    content: '';
    cursor: pointer;
    background-color: rgba(127, 165, 61, 0.9);
}

I am struggling to make the green background and read more button fade in smoothly.

How can I achieve that?


问:
Math.sin() behaving strangely in javascript
For some reason when I input Math.PI and 3.14 I get completely different and even impossible results

Edit: Nevermind, I'm just dumb and didn't notice the e-16

答:
It gives ~10^-16 something very close to zero you can

console.log(Math.sin(Math.PI).toFixed(2))```


问:
create an html select via jquery with a while statement or similar
How do I write an html select statement via jquery?

Let's say I've got this in mind:

```<code><select id="mySelect">
  <option value="400">400</option>
  <option value="401">401</option>
  <option value="402">402</option>
  <option value="403">403</option>
</select>
</code>```

And I need it to be written from jquery.

I've tried this (without success)

```<code>$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410') {
   // do some code
   $('#div1').append('<option name="asdf" value = "1">Hey ' + i + ' is the value!</option>');
   i++;
}
$('#div2').append('</select>');
</code>```

答:
When using append jQuery appends the actual html elements instead of the html, its not like writing to a stream of HTML.

Also, appending to HTML attached to the document itself in small parts is extremely inefficient.  The following variation of your code should work and should be much faster:

```<code>var html = [];
html[html.length] = '<select name = "myshield2" id="myshieldSelect2">';
var i = 400;
while (i < '410') {
   // do some code
   html[html.length] = '<option name="asdf" value = "1">Hey ' + i + ' is the value!    </option>';
   i++;
}
html[html.length] = '</select>';
$('#div1').append(html.join(''));
</code>```

Here's an example of it in action: JSBin Example

Body:
How do I write an html select statement via jquery?

Let's say I've got this in mind:

<select id="mySelect">
  <option value="400">400</option>
  <option value="401">401</option>
  <option value="402">402</option>
  <option value="403">403</option>
</select>

And I need it to be written from jquery.

I've tried this (without success)

$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410') {
   // do some code
   $('#div1').append('<option name="asdf" value = "1">Hey ' + i + ' is the value!</option>');
   i++;
}
$('#div2').append('</select>');

Body:
When using append jQuery appends the actual html elements instead of the html, its not like writing to a stream of HTML.

Also, appending to HTML attached to the document itself in small parts is extremely inefficient.  The following variation of your code should work and should be much faster:

var html = [];
html[html.length] = '<select name = "myshield2" id="myshieldSelect2">';
var i = 400;
while (i < '410') {
   // do some code
   html[html.length] = '<option name="asdf" value = "1">Hey ' + i + ' is the value!    </option>';
   i++;
}
html[html.length] = '</select>';
$('#div1').append(html.join(''));

Here's an example of it in action: JSBin Example


问:
How to convert negative zero to positive zero in C?
Hello I'm learning Objective C and I was doing the classic Calculator example.

Problem is that I'm getting a negative zero when I multiply zero by any negative number, and I put the result into a (double) type!

To see what was going on, I played with the debugger and this is what I got:

(gdb) print -2*0

$1 = 0

(gdb) print (double) -2 * 0

$2 = -0

In the second case when I cast it to a double type, it turns into negative zero! How can I fix that in my application? I need to work with doubles.
How can I fix the result so I get a zero when the result should be zero?

答:
GCC was seemingly optimizing out the simple fix of negzero += 0.0 as noted above until I realized that -fno-signed-zeros was in place.   Duh.

But in the process I did find that this will fix a signed zero, even when -fno-signed-zeros is set:

if (negzero > -DBL_MIN && negzero < DBL_MIN && signbit(negzero))
   negzero = 0.0;
```
<p>or as a macro:</p>
<pre class="lang-c prettyprint-override"><code>#define NO_NEG_ZERO(a) ( (a) > -DBL_MIN && (a) < DBL_MIN && signbit(a) ? 0.0 : (a) )

negzero = NO_NEG_ZERO(negzero)
</code>```

Note that the comparitor is < and > (not <= or >=) so a really is zero! (OR it is a subnormal number...but nevermind the guy behind the curtain.)

Maybe this answer is slightly less correct in the sense that a value of between DBL_MIN and -DBL_MIN will be converted to 0.0, in which case this isn't the way if you need to support subnormal numbers.

If you do need subnormal numbers (!) then perhaps your the kind of person who plays with -fno-signed-zeros, too.

The lesson here for me and subnormal-numbers-guy is this: if you play outside of spec then expect out-of-spec results ;)

(Sorry, that was not PC.  It could be subnormal-numbers-person...but I digress.)

Body:
GCC was seemingly optimizing out the simple fix of negzero += 0.0 as noted above until I realized that -fno-signed-zeros was in place.   Duh.

But in the process I did find that this will fix a signed zero, even when -fno-signed-zeros is set:

if (negzero > -DBL_MIN && negzero < DBL_MIN && signbit(negzero))
   negzero = 0.0;

or as a macro:

#define NO_NEG_ZERO(a) ( (a) > -DBL_MIN && (a) < DBL_MIN && signbit(a) ? 0.0 : (a) )

negzero = NO_NEG_ZERO(negzero)

Note that the comparitor is < and > (not <= or >=) so a really is zero! (OR it is a subnormal number...but nevermind the guy behind the curtain.)

Maybe this answer is slightly less correct in the sense that a value of between DBL_MIN and -DBL_MIN will be converted to 0.0, in which case this isn't the way if you need to support subnormal numbers.

If you do need subnormal numbers (!) then perhaps your the kind of person who plays with -fno-signed-zeros, too.

The lesson here for me and subnormal-numbers-guy is this: if you play outside of spec then expect out-of-spec results ;)

(Sorry, that was not PC.  It could be subnormal-numbers-person...but I digress.)


答:
Here I have set up a test of your problem

console.log(Math.sin(3.14));
console.log(Math.sin(Math.PI));```
</div>
</div>
</p>
<p>When run, I get this result:</p>
```0.0015926529164868282
1.2246467991473532e-16
```

The 2nd number is a really really small positive number. It is essentially 0. The first number is slightly larger, but 3.14 is a rounded value of PI, and that's why you get the difference

Title: Math.sin() behaving strangely in javascript

Body:
For some reason when I input Math.PI and 3.14 I get completely different and even impossible results

Edit: Nevermind, I'm just dumb and didn't notice the e-16

Body:
Here I have set up a test of your problem

console.log(Math.sin(3.14));
console.log(Math.sin(Math.PI));

When run, I get this result:

0.0015926529164868282
1.2246467991473532e-16

The 2nd number is a really really small positive number. It is essentially 0. The first number is slightly larger, but 3.14 is a rounded value of PI, and that's why you get the difference


问:
Targeting active processes in Windows Power Automate actions
I have created an action to shut down several processes. Why? I am using Dragon Pro voice-to-text and Voice Computer in my adaptive technology stack. Unfortunately, the former crashes regularly, and when this happens, it doesn't shut down cleanly. I have the following action in Windows Power Automate, using this trick to listen for a shortcut key.

I tried targeting each process by its ID, but it seems that the ID changes each time the process runs a new. So then I tried by process name, but that doesn't seem to work. How do I properly target these processes?

答:
Can I suggest using a PowerShell script?  Using PAD seems like a bit of overkill to achieve such a thing but I guess if it's baked into your entire solution then this will work nicely and we all know there is an action within PAD to run a PowerShell script.</p>
```<code>$processes = Get-Process

Foreach ($process in $processes) {
    if ( $process.Name -eq "natspeak" ) {
        Stop-Process -Name $process.Name
    }
}
</code>```

Body:
Can I suggest using a PowerShell script?  Using PAD seems like a bit of overkill to achieve such a thing but I guess if it's baked into your entire solution then this will work nicely and we all know there is an action within PAD to run a PowerShell script.

$processes = Get-Process

Foreach ($process in $processes) {
    if ( $process.Name -eq "natspeak" ) {
        Stop-Process -Name $process.Name
    }
}


问:
Why are my Laravel failed jobs not showing up in the failed_jobs table?
I followed the docs to create a job and forced failure with this in my handle():

```<code>throw new \Exception("Error Processing the job", 1);
</code>```

The result is a failed job as expected, but the failed job is not showing up in the failed_job table. When processing, it is showing up in the jobs table.

```<code>[2020-12-15 07:37:18][6] Processing: App\Jobs\IntroEmailJob
[2020-12-15 07:37:18][6] Failed:     App\Jobs\IntroEmailJob
</code>```

Laravel 8.0

EDIT:
Found this in the logs:

```<code>General error: 1364 Field 'uuid' doesn't have a default value
</code>```

I created the failed_jobs table just as the docs explained:

```<code>php artisan queue:failed-table

php artisan migrate
</code>```

答:
I had this issue with Laravel 8 where a record of failed jobs weren't being stored in the "failed_jobs" table.

In my case the issue was that the records weren't being stored because of some kind of UUID / ID issue. Turns out my failed_jobs migration was from Laravel 7.

All you need to do is upgrade this migration to match Laravel 8 or replace this:

$table->uuid('id')->primary();
```
<p>with this:</p>
<pre class="lang-php prettyprint-override"><code>$table->id();
</code>```

Body:
I followed the docs to create a job and forced failure with this in my handle():

throw new \Exception("Error Processing the job", 1);

The result is a failed job as expected, but the failed job is not showing up in the failed_job table. When processing, it is showing up in the jobs table.

[2020-12-15 07:37:18][6] Processing: App\Jobs\IntroEmailJob
[2020-12-15 07:37:18][6] Failed:     App\Jobs\IntroEmailJob

Laravel 8.0

EDIT:
Found this in the logs:

General error: 1364 Field 'uuid' doesn't have a default value

I created the failed_jobs table just as the docs explained:

php artisan queue:failed-table

php artisan migrate

Body:
I had this issue with Laravel 8 where a record of failed jobs weren't being stored in the "failed_jobs" table.

In my case the issue was that the records weren't being stored because of some kind of UUID / ID issue. Turns out my failed_jobs migration was from Laravel 7.

All you need to do is upgrade this migration to match Laravel 8 or replace this:

$table->uuid('id')->primary();

with this:

$table->id();