问:
How can I close my dropdown menu when sveltekit route changes?
I have a <SideBar /> component and onDestroy() doesn't seem to fire on route changes.

I need to close the menu when the route changes otherwise the menu stays open which is a bad UX.

```<code><script>
    import { page } from '$app/stores';
    import { onDestroy } from 'svelte';
    let isMainNavOpen = true;
    let isGroupNavOpen = false;
    function toggleGroupMenu(e) {
        e.preventDefault();

        isGroupNavOpen = !isGroupNavOpen;
    }

    $: currentPath = $page.url.pathname;
</script>

    <nav>
        <header class="groups" class:closed={!isGroupNavOpen}>
            <div class="dropdown">
                <a href="#" class="toggler" on:click|preventDefault={toggleGroupMenu}>
                    <img src="/icons/chevron.svg" alt="" border="0" />
                </a>
                <ul>
                    {#each groupMenu as item, i}
                        <li class:active={currentPath === item.path}>
                            <a href="/groups/{item.id}"
                                ><img
                                    class="avatar"
                                    src="/icons/avatar.group.png"
                                    alt=""
                                    border="0"
                                />{item.name}</a
                            >
                        </li>
                    {/each}
                </ul>
                <a href="/groups" class="button secondary outlined">Explore Groups</a>
            </div>
        </header>
    </nav>

<style>
    nav {
        padding: 1.2rem;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
    }

    nav header {
        color: #fff;
        display: flex;
        flex-direction: column;
    }

    .groups.closed li:not(:first-child) {
        display: none;
    }

    .groups .toggler {
        position: absolute;
        top: 2.5rem;
        right: 1rem;
        margin-left: 1.4rem;
    }

    .groups .toggler img {
        transform: rotate(180deg);
    }

    .groups.closed .toggler img {
        transform: rotate(0deg);
    }

    .groups ul {
        width: 100%;
        max-height: 22rem;
        overflow-y: auto;
        background-color: #060536;
        color: #fff;
        border-radius: 0.8rem;
    }

    .groups ul .active {
        background-color: #34326d;
    }

    .groups .dropdown {
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        background-color: #060536;
    }

    header.groups {
        padding: 0;
        position: relative;
        overflow: visible;
    }

    .groups .avatar {
        width: 5rem;
        display: block;
        margin-right: 1.4rem;
    }

    .groups li {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .groups li a {
        padding: 1rem;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-grow: 1;
        color: #fff;
        text-decoration: none;
        font-weight: 600;
        word-break: break-all;
    }

    .groups .button {
        font-weight: 600;
        font-size: 1.4rem;
        width: 80%;
        margin: 1rem auto;
    }

    .groups.closed .button {
        display: none;
    }

    nav ul {
        display: flex;
        flex-direction: column;
    }

    nav ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        flex: 1;
    }
</style>
</code>```

I probably also need an underlay where if they click off the menu it closes too.

答:
Use the "navigating" store from svelte-kit in a reactive statement

$: if($navigating) //code;

Body:
I have a <SideBar /> component and onDestroy() doesn't seem to fire on route changes.

I need to close the menu when the route changes otherwise the menu stays open which is a bad UX.

                    {#each groupMenu as item, i}

                            {item.name}

                    {/each}

                Explore Groups

I probably also need an underlay where if they click off the menu it closes too.


来源: stackexchange

问:
How to wrap long messages using Editor in Xamarin Forms
I am using Editor control and wish to wrap long messages (Like Whatsapp).
I have explored few sites and got nothing . If this feature is not yet in Xamarin Forms , can I know any alternative for the same ?

My XAML

```<code><Editor Grid.Row="0" Grid.Column="0" Text="{Binding TextMessage}"
                            TextColor="{StaticResource StartColor}" HorizontalOptions="FillAndExpand"
                            FontSize="14" TextChanged="Editor_TextChanged"
                            FontFamily="{StaticResource DefaultFont}" IsEnabled="True"/>
</code>```

OUTPUT-

答:
For those who are still facing issues, I have a case where the line does not wrap as long as there is no break line (Enter). Solution was to change parent layout from StackLayout to Grid. With grid, now it works.
If you want the height to change dynamically when you have more lines, you can use the above solution:

```<code>AutoSize="TextChanges"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Editor control and wish to wrap long messages (Like Whatsapp).
I have explored few sites and got nothing . If this feature is not yet in Xamarin Forms , can I know any alternative for the same ?

My XAML

<Editor Grid.Row="0" Grid.Column="0" Text="{Binding TextMessage}"
                            TextColor="{StaticResource StartColor}" HorizontalOptions="FillAndExpand"
                            FontSize="14" TextChanged="Editor_TextChanged"
                            FontFamily="{StaticResource DefaultFont}" IsEnabled="True"/>

OUTPUT-

Body:
For those who are still facing issues, I have a case where the line does not wrap as long as there is no break line (Enter). Solution was to change parent layout from StackLayout to Grid. With grid, now it works.
If you want the height to change dynamically when you have more lines, you can use the above solution:

AutoSize="TextChanges"


问:
How to get more dynamic growing Hourly Python Facebook Prophet Forecast
im currently trying to build a good forecast on Hourly Based Data with Python and Prophet.

After cleaning all the data and resampling missing values, i already got a much better result.
I also included cap and floor and a own changepoint_prior_scale.

When i plot the prediction result over the actual data it fits until there are peaks.
Could anybody give me tips to make prophet predict these peaks in July better ?

It seems like the peaks are there but to low.

Here is the part of my code to generate the model and predict the future:

df['cap']=130
df['floor']=0
model = Prophet(changepoint_prior_scale=0.1, growth='logistic').fit(df)
future = model.make_future_dataframe(periods=15*24, freq='H')
future['cap']=130
future['floor']=0
forecast = model.predict(future)
plot1 = model.plot(forecast)
```

And here is a image of the plot:

答:
I will suggest you to start with looking on the components of the forecast (trend, seasonality) to get the overview of the model. You can do this using:

```<code>m.plot_components(forecast)
</code>```

In your model you are using only changepoint_prior_scale greater than default (0.05) what means that you enable trend to be more flexible.

It will be worth to play with different seasonality parameters - for example try to smooth yearly seasonality adding to the model parameters yearly_seasonality=20 (10 by default).

Knowing that in July you have always the peak, you can try also to use Prophet holiday effect - which is well described here.

Body:
im currently trying to build a good forecast on Hourly Based Data with Python and Prophet.

After cleaning all the data and resampling missing values, i already got a much better result.
I also included cap and floor and a own changepoint_prior_scale.

When i plot the prediction result over the actual data it fits until there are peaks.
Could anybody give me tips to make prophet predict these peaks in July better ?

It seems like the peaks are there but to low.

Here is the part of my code to generate the model and predict the future:

df['cap']=130
df['floor']=0
model = Prophet(changepoint_prior_scale=0.1, growth='logistic').fit(df)
future = model.make_future_dataframe(periods=15*24, freq='H')
future['cap']=130
future['floor']=0
forecast = model.predict(future)
plot1 = model.plot(forecast)

And here is a image of the plot:

Body:
I will suggest you to start with looking on the components of the forecast (trend, seasonality) to get the overview of the model. You can do this using:

m.plot_components(forecast)

In your model you are using only changepoint_prior_scale greater than default (0.05) what means that you enable trend to be more flexible.

It will be worth to play with different seasonality parameters - for example try to smooth yearly seasonality adding to the model parameters yearly_seasonality=20 (10 by default).

Knowing that in July you have always the peak, you can try also to use Prophet holiday effect - which is well described here.


问:
Vim cannot change the statusline appearance when a new window is open for some filetype
I wrote a few function to ask vim to set different statusline style for current and non-current window using setl for each type of window.

The basic idea is that vim will draw an "activated" statusline upon entering a new window (WinEnter), while turn the statusline of the previous window (WinLeave) into "deactivated" one.

Although switching between windows work as expected, a newly opened window will sometimes get the "deactivated" statusline defined.

I upload a short video on youtube showing the behaviour I mention, please take a look.

Edit: Here is the code:

```<code>autocmd VimEnter * call SttLine_Activate()
autocmd WinNew   * call SttLine_NewAuto()
autocmd WinEnter * call SttLine_Activate()
autocmd WinLeave * call SttLine_Deactivate()

" + Status line
"--------------
set laststatus=2
set noshowmode

" * Get the current mode
let g:currentmode={
            \ 'n'  : 'NORMAL',
            \ 'v'  : 'VISUAL',
            \ 'V'  : 'V·LINE',
            \ '' : 'V·BLOCK',
            \ 's'  : 'SELECT',
            \ 'S'  : 'S·LINE',
            \ '' : 'S·BLOCK',
            \ 'i'  : 'INSERT',
            \ 'R'  : 'REPLACE',
            \ 'r'  : 'REPLACE',
            \ 'Rv' : 'V·REPLACE',
            \ 'c'  : 'COMMAND',
            \ 't'  : 'TERM',
            \}

" * Status line for current window
function! SttLine_Activate()
    if (winnr()==winnr())
        setl statusline=

        setl statusline+=\%#StatusBlockColour#
        setl statusline+=\ %{g:currentmode[mode()]}
        setl statusline+=\ %0*

        setl statusline+=\%#StatusLineColour#
        setl statusline+=\ %p%%\(%L)\ ≡\ L%l\:%c\ \|

        setl statusline+=\%#StatusFileColour#
        setl statusline+=\ %f\ %m
        setl statusline+=%=

        setl statusline+=\%#StatusBlockColour#
        setl statusline+=\ ⌨\ %{&fileformat}:\ %y
        setl statusline+=\ %{&fileencoding?&fileencoding:&encoding}
        setl statusline+=\ %0*
    endif
endfunction

" * Status line for non-current window
function! SttLine_Deactivate()
    setl statusline=

    setl statusline+=\%#StatusBlockGrey#
    setl statusline+=\ %{g:currentmode[mode()]}
    setl statusline+=\ %0*

    setl statusline+=\%#StatusLineGrey#
    setl statusline+=\ %p%%\(%L)\ ≡\ L%l\:%c\ \|

    setl statusline+=\%#StatusFileGrey#
    setl statusline+=\ %f\ %m
    setl statusline+=%=

    setl statusline+=\%#StatusBlockGrey#
    setl statusline+=\ ⌨\ %{&fileformat}:\ %y
    setl statusline+=\ %{&fileencoding?&fileencoding:&encoding}
    setl statusline+=\ %0*
endfunction

" * Auto detect current window (switching window)
function! SttLine_NewAuto()
    let winID = winnr()
    let nWin  = bufnr("$")+1

    let iwin     = 0
    let hasnetrw = 0
    while (iwin < nWin)
        wincmd w
        if (getbufvar(iwin, "&filetype") == "netrw")
            let hasnetrw += 1
        endif

        let iwin += 1
    endwhile

    if (hasnetrw>0)
        vert res
        vert res -25
    endif
endfunction
</code>```

答:
Here's how you can define different status line for active and inactive windows. Change StatuslineActive and StatuslineNotActive  functions with you desired status line.

```<code>" Return the active status line configuration
function! StatuslineActive() abort
  let l:statusline ='['. mode() . '] %f'  " [ mode ] + filename
  let l:statusline.=' Active'
  return l:statusline
endfunction

" Return the inactive status line configuration
function! StatuslineNotActive() abort
  let l:statusline ='[' . mode() .'] %f' " [ mode ] + filename
  let l:statusline.=' Not Active'
  return l:statusline
endfunction
set statusline=%!StatuslineActive()

" Set the corresponding status line when entering and leaving windows
augroup set_active_statusline
  autocmd!
  autocmd WinEnter * :setlocal statusline=%!StatuslineActive()
  autocmd WinLeave * :setlocal statusline=%!StatuslineNotActive()
augroup END

</code>```

Here it is in action:

Body:
I wrote a few function to ask vim to set different statusline style for current and non-current window using setl for each type of window.

The basic idea is that vim will draw an "activated" statusline upon entering a new window (WinEnter), while turn the statusline of the previous window (WinLeave) into "deactivated" one.

Although switching between windows work as expected, a newly opened window will sometimes get the "deactivated" statusline defined.

I upload a short video on youtube showing the behaviour I mention, please take a look.

Edit: Here is the code:

autocmd VimEnter * call SttLine_Activate()
autocmd WinNew   * call SttLine_NewAuto()
autocmd WinEnter * call SttLine_Activate()
autocmd WinLeave * call SttLine_Deactivate()

" + Status line
"--------------
set laststatus=2
set noshowmode

" * Get the current mode
let g:currentmode={
            \ 'n'  : 'NORMAL',
            \ 'v'  : 'VISUAL',
            \ 'V'  : 'V·LINE',
            \ '' : 'V·BLOCK',
            \ 's'  : 'SELECT',
            \ 'S'  : 'S·LINE',
            \ '' : 'S·BLOCK',
            \ 'i'  : 'INSERT',
            \ 'R'  : 'REPLACE',
            \ 'r'  : 'REPLACE',
            \ 'Rv' : 'V·REPLACE',
            \ 'c'  : 'COMMAND',
            \ 't'  : 'TERM',
            \}

" * Status line for current window
function! SttLine_Activate()
    if (winnr()==winnr())
        setl statusline=

        setl statusline+=\%#StatusBlockColour#
        setl statusline+=\ %{g:currentmode[mode()]}
        setl statusline+=\ %0*

        setl statusline+=\%#StatusLineColour#
        setl statusline+=\ %p%%\(%L)\ ≡\ L%l\:%c\ \|

        setl statusline+=\%#StatusFileColour#
        setl statusline+=\ %f\ %m
        setl statusline+=%=

        setl statusline+=\%#StatusBlockColour#
        setl statusline+=\ ⌨\ %{&fileformat}:\ %y
        setl statusline+=\ %{&fileencoding?&fileencoding:&encoding}
        setl statusline+=\ %0*
    endif
endfunction

" * Status line for non-current window
function! SttLine_Deactivate()
    setl statusline=

    setl statusline+=\%#StatusBlockGrey#
    setl statusline+=\ %{g:currentmode[mode()]}
    setl statusline+=\ %0*

    setl statusline+=\%#StatusLineGrey#
    setl statusline+=\ %p%%\(%L)\ ≡\ L%l\:%c\ \|

    setl statusline+=\%#StatusFileGrey#
    setl statusline+=\ %f\ %m
    setl statusline+=%=

    setl statusline+=\%#StatusBlockGrey#
    setl statusline+=\ ⌨\ %{&fileformat}:\ %y
    setl statusline+=\ %{&fileencoding?&fileencoding:&encoding}
    setl statusline+=\ %0*
endfunction

" * Auto detect current window (switching window)
function! SttLine_NewAuto()
    let winID = winnr()
    let nWin  = bufnr("$")+1

    let iwin     = 0
    let hasnetrw = 0
    while (iwin < nWin)
        wincmd w
        if (getbufvar(iwin, "&filetype") == "netrw")
            let hasnetrw += 1
        endif

        let iwin += 1
    endwhile

    if (hasnetrw>0)
        vert res
        vert res -25
    endif
endfunction

Body:
Here's how you can define different status line for active and inactive windows. Change StatuslineActive and StatuslineNotActive  functions with you desired status line.

" Return the active status line configuration
function! StatuslineActive() abort
  let l:statusline ='['. mode() . '] %f'  " [ mode ] + filename
  let l:statusline.=' Active'
  return l:statusline
endfunction

" Return the inactive status line configuration
function! StatuslineNotActive() abort
  let l:statusline ='[' . mode() .'] %f' " [ mode ] + filename
  let l:statusline.=' Not Active'
  return l:statusline
endfunction
set statusline=%!StatuslineActive()

" Set the corresponding status line when entering and leaving windows
augroup set_active_statusline
  autocmd!
  autocmd WinEnter * :setlocal statusline=%!StatuslineActive()
  autocmd WinLeave * :setlocal statusline=%!StatuslineNotActive()
augroup END

Here it is in action:


问:
How to iterate over array and save data using hooks
Tha idea is iterate over a array and save (or update) values.

```<code>const [skills, setSkills] = useState([]);

useEffect(() => {
    Object.entries(array).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills({ ...skills, [k]: v })
    });
}, [array]);
</code>```

The output is:

```<code>The skill is:  1  and value:  30
The skill is:  2  and value:  40
The skill is:  3  and value:  90
</code>```

That's ok and I assume that "skills" should be:

```<code>{1: 30, 2: 40, 3: 90}
   1: 30
   2: 40
   3: 90
</code>```

but actually, it only saving the last input. I mean, I see the following:

```<code>{3: 90}
   3: 90
</code>```

Please, somebody can explain why? And how to do it the right way?
Thanks!!!

答:
You can do:</p>
```<code>const [skills, setSkills] = useState([])

useEffect(() => {
  setSkills([
    ...skills,
    ...Object.entries(json_h).map(([k, v]) => ({[k]: v})),
  ])
}, [json_h])
</code>```

Body:
Tha idea is iterate over a array and save (or update) values.

const [skills, setSkills] = useState([]);

useEffect(() => {
    Object.entries(array).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills({ ...skills, [k]: v })
    });
}, [array]);

The output is:

The skill is:  1  and value:  30
The skill is:  2  and value:  40
The skill is:  3  and value:  90

That's ok and I assume that "skills" should be:

{1: 30, 2: 40, 3: 90}
   1: 30
   2: 40
   3: 90

but actually, it only saving the last input. I mean, I see the following:

{3: 90}
   3: 90

Please, somebody can explain why? And how to do it the right way?
Thanks!!!

Body:
You can do:

const [skills, setSkills] = useState([])

useEffect(() => {
  setSkills([
    ...skills,
    ...Object.entries(json_h).map(([k, v]) => ({[k]: v})),
  ])
}, [json_h])


问:
Activating conda environment from bash script
I would like to change my conda environment from a bash script.
I want to run bash script_yxz, where 'script_xyz' is like:

```<code>#!/bin/bash

conda activate my_env
</code>```

and switch to my_env.

This already works if I run source script_yxz.
But I have the problem that I am not able to 'source' on remote machines with 'sshpass'.

To better understand my purposes, my goal is to run on my terminal

```<code>sshpass -p "password" ssh -o user@server "bash script_xyz"
</code>```

and changing the environment on the server.
This is why I need to use bash instead of source.

I have read a lot of solutions on various forums but none of them works.

答:
You can use bash,zsh or any shell aliases for this purposes. You just add

```<code>alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'
</code>```

line into the .bashrc,.zshrc or .any_other_shell_rc.

"N.B. My environment name is MyPy38". So,replace it according name as well as the path /home/$USER/anaconda3.
Also you can create separate file for aliases. Just create a file called .bash_aliases and add

```<code>if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi
</code>```

lines to .bashrc,.zshrc or .any_other_shell_rc and keep the command

```<code>alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'
</code>```

into the .bash_aliases. Now,  source ~/.zshrc ~/.bashrc or just close and open a new terminal. Run the command my_conda and BOOM!

Also, you can add some other aliases for jupyter-notebook jupyter-lab spyder etc. like

```<code># Just activate my conda
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

# Open Jupyter Notebook in my Env
alias my_jupn='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-notebook'

# Open Jupyter Lab in my Env
alias my_jupl='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-lab'

# Open Spyder in my Env
alias my_spyder='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && spyder'

</code>```

To confirm active environment name python code

```<code>import sys
print(sys.executable)
</code>```

Body:
I would like to change my conda environment from a bash script.
I want to run bash script_yxz, where 'script_xyz' is like:

#!/bin/bash

conda activate my_env

and switch to my_env.

This already works if I run source script_yxz.
But I have the problem that I am not able to 'source' on remote machines with 'sshpass'.

To better understand my purposes, my goal is to run on my terminal

sshpass -p "password" ssh -o user@server "bash script_xyz"

and changing the environment on the server.
This is why I need to use bash instead of source.

I have read a lot of solutions on various forums but none of them works.

Body:
You can use bash,zsh or any shell aliases for this purposes. You just add

alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

line into the .bashrc,.zshrc or .any_other_shell_rc.

"N.B. My environment name is MyPy38". So,replace it according name as well as the path /home/$USER/anaconda3.
Also you can create separate file for aliases. Just create a file called .bash_aliases and add

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

lines to .bashrc,.zshrc or .any_other_shell_rc and keep the command

alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

into the .bash_aliases. Now,  source ~/.zshrc ~/.bashrc or just close and open a new terminal. Run the command my_conda and BOOM!

Also, you can add some other aliases for jupyter-notebook jupyter-lab spyder etc. like

# Just activate my conda
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

# Open Jupyter Notebook in my Env
alias my_jupn='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-notebook'

# Open Jupyter Lab in my Env
alias my_jupl='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-lab'

# Open Spyder in my Env
alias my_spyder='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && spyder'

To confirm active environment name python code

import sys
print(sys.executable)


问:
What's an example of Ruby code that's "too clever"?
I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?</p>

答:
Cucumber (or RSpec Stories)

Quoted from the above RSpec Stories link:

Based around plain text descriptions
  of application behaviour, it lets you
  write integration tests with good
  reuse and good diagnostic reporting.

For example, here's a story I wrote to
  check the login process.

```<code>Story: login as an existing user
    As an unauthenticated user
    I want to log in to Expectnation
    So I can see my account details

    Scenario: login details are correct
            Given an event provider
            And my test@example.org account
            When I log in with email test@example.org and password foofoo
            Then I will be logged in
            And I will be shown the account page
</code>```

The words such as "Given", "When" and
  "Then" are cues to the story runner to
  execute some code. Behind the story
  sits a collection of steps. Here's a
  couple of steps from this test:

```<code>  Given "my $email account" do |email|
    @user = find_or_create_user_by_email({:email => email,
      :password => 'foofoo',
      :password_confirmation => 'foofoo'})
  end

  When "I log in with email $email and password $password" do |email, password|
    post '/user/account/authenticate',
      :user => {:email => email, :password => password}
  end
</code>```

Notice how a clever bit of string
  matching allows you to pass parameters
  from the story prose.

With a small bit of bolting together, the prose stories are then run as code and the tests executed.

OwnerDisplayName: amsterdam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: amsterdam

Body:
Cucumber (or RSpec Stories)

Quoted from the above RSpec Stories link:

Based around plain text descriptions
  of application behaviour, it lets you
  write integration tests with good
  reuse and good diagnostic reporting.

For example, here's a story I wrote to
  check the login process.

Story: login as an existing user
    As an unauthenticated user
    I want to log in to Expectnation
    So I can see my account details

    Scenario: login details are correct
            Given an event provider
            And my test@example.org account
            When I log in with email test@example.org and password foofoo
            Then I will be logged in
            And I will be shown the account page

The words such as "Given", "When" and
  "Then" are cues to the story runner to
  execute some code. Behind the story
  sits a collection of steps. Here's a
  couple of steps from this test:

  Given "my $email account" do |email|
    @user = find_or_create_user_by_email({:email => email,
      :password => 'foofoo',
      :password_confirmation => 'foofoo'})
  end

  When "I log in with email $email and password $password" do |email, password|
    post '/user/account/authenticate',
      :user => {:email => email, :password => password}
  end

Notice how a clever bit of string
  matching allows you to pass parameters
  from the story prose.

With a small bit of bolting together, the prose stories are then run as code and the tests executed.

OwnerDisplayName: dbr

LastEditorDisplayName: dbr


问:
Why Am I Getting 502 Error After Adding Require In Express JS File?
I am trying to require a js file in my express api but I am getting a 502 error whenever I do. The file getJSON.js is in the same directory as my express js file but for some reason I am having trouble accessing it:

```<code>docapi.js:
const http = require('http');
const getJSON = require('getJSON.js'):
const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!\n');
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
</code>```

Here is the file I am trying to require:

```<code>getJSON.js:
test() {
  console.log("Hello again.")
}
</code>```

Sorry for such an easy question, but I haven't found an explanation anywhere else. Can anyone tell me what I am doing wrong, please?

答:
502 is a Bad Gateway error.

Your reverse proxy server can't connect to the Node.js server because the Node.js server fails to start due to the syntax errors in your files.

First: getJSON.js.

A function declaration starts with the function keyword, but you omitted it.

The syntax you are using is for declaring a method, which is only allowed inside a class or object.

Second, you followed your call to require with a colon instead of a semi-colon.

You should have an error report when you tried to start the server (be it locally or on whatever service you are deploying the code to). You really should examine that before resorting to SO.

You should also make use of tools like ESLint which will pick up this kind of error and will integrate with common IDEs (such as the popular, and free, Visual Studio Code).

Once your fix your syntax errors, you need a relative path (e.g. starting with ./) to require a file in the same directory.

You also need to export the function for the assignment from require to do anything useful.

Body:
I am trying to require a js file in my express api but I am getting a 502 error whenever I do. The file getJSON.js is in the same directory as my express js file but for some reason I am having trouble accessing it:

docapi.js:
const http = require('http');
const getJSON = require('getJSON.js'):
const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!\n');
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Here is the file I am trying to require:

getJSON.js:
test() {
  console.log("Hello again.")
}

Sorry for such an easy question, but I haven't found an explanation anywhere else. Can anyone tell me what I am doing wrong, please?


问:
Difference between a node being node != null and node.next == null?
I'm reading up on linked lists here and I'm kind of confused. I've drawn it out but it still looks like they are the same thing.

Traversing through a linked list:

```<code>Node tmp = head;
while(tmp != null) {
     tmp = tmp.next;
}
</code>```

My thought process for the while loop: tmp starts at head. Now while tmp points to a next node, tmp moves on to pointing to the node next to it. And it goes on until tmp is not pointing to another node next to it.

Adding to the end of a linked list:

```<code>public void addLast(AnyType item)
{
   if(head == null) addFirst(item);
   else
   {
      Node<AnyType> tmp = head;
      while(tmp.next != null)
            tmp = tmp.next;

      tmp.next = new Node<AnyType>(item, null);
   }
}
</code>```

My thought process for the while loop: tmp starts at head. Now while tmp points to a next node, tmp moves on to pointing to the node next to it. And it goes on until tmp is not pointing to another node next to it. Then it breaks out of the loop and assigns tmp to point next to a new Node.

答:
long story short tmp.nxt basically check if there is a link connecting the next node .so in the iterative loop if there are n nodes then it will run n-1 times .
but node!=null will run n times cuz node!=null is checking the existance of the node.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm reading up on linked lists here and I'm kind of confused. I've drawn it out but it still looks like they are the same thing.

Traversing through a linked list:

Node tmp = head;
while(tmp != null) {
     tmp = tmp.next;
}

My thought process for the while loop: tmp starts at head. Now while tmp points to a next node, tmp moves on to pointing to the node next to it. And it goes on until tmp is not pointing to another node next to it.

Adding to the end of a linked list:

public void addLast(AnyType item)
{
   if(head == null) addFirst(item);
   else
   {
      Node<AnyType> tmp = head;
      while(tmp.next != null)
            tmp = tmp.next;

      tmp.next = new Node<AnyType>(item, null);
   }
}

My thought process for the while loop: tmp starts at head. Now while tmp points to a next node, tmp moves on to pointing to the node next to it. And it goes on until tmp is not pointing to another node next to it. Then it breaks out of the loop and assigns tmp to point next to a new Node.


问:
How can I do ' IIF(MyColumn LIKE '%search%',1,0) ' in MongoDb?
I want to show 1 or 0 depending if a field in the json document has a specific word.

In SQL, I would use IIF(MyColumn LIKE '%search%',1,0)

How can I do it in MongoDb, under the $project section?

答:
One example of returning a 0/1 field value, determined by a regex match or not, could be:

db.collection.find({},
{
  "foundIt": {
    "$cond": [
      {
        "$regexMatch": {
          "input": "$key",
          "regex": "tion"
        }
      },
      1,
      0
    ]
  },
  "key": 1,
  "_id": 0
})
```

Try it on mongoplayground.net.

Body:
One example of returning a 0/1 field value, determined by a regex match or not, could be:

db.collection.find({},
{
  "foundIt": {
    "$cond": [
      {
        "$regexMatch": {
          "input": "$key",
          "regex": "tion"
        }
      },
      1,
      0
    ]
  },
  "key": 1,
  "_id": 0
})

Try it on mongoplayground.net.


问:
Pandas: how to index dataframe for certain value or string without knowing the column name
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

```<code>fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons
</code>```

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

```<code>print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)
</code>```

Which results in:

```<code>Int64Index([1], dtype='int64')
</code>```

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

答:
You can try a simple search yourself.

```<code>coordinates = []
indices = df.index
columns = df.columns
for index in indices: # df is the DataFrame
         for col in columns:
             if df[col][index] == 'Mangos':
                 coordinates.append((index, col))
coordinates
</code>```

Output:

[(1, 'column3')]

Body:
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)

Which results in:

Int64Index([1], dtype='int64')

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

Body:
You can try a simple search yourself.

coordinates = []
indices = df.index
columns = df.columns
for index in indices: # df is the DataFrame
         for col in columns:
             if df[col][index] == 'Mangos':
                 coordinates.append((index, col))
coordinates

Output:

[(1, 'column3')]


问:
multiple marker on MapMyIndia in React Js
I am trying to show multiple markers on MapMyIndia in React,
I used mapmyindia-react package.

```<code>  <div className="w-100 overflow-hidden">
      <Maps
        markers={[
          {
            position: [21.145664, 72.759782],

            draggable: true,
            title: "Marker title",
            onClick: (e) => {
              console.log("clicked ");
            },
            onDragend: (e) => {
              console.log("dragged");
            },
          },
        ]}
      />
    </div>

</code>```

Please help

答:
```<code>  markers={[
    {
        position: [18.5314, 73.845],
        draggable: true,
        title: "Marker 1"
    },
    {
        position: [18.5414, 73.845],
        draggable: true,
        title: "Marker 2"
    }
  ]}
</code>```

Body:
I am trying to show multiple markers on MapMyIndia in React,
I used mapmyindia-react package.

      <Maps
        markers={[
          {
            position: [21.145664, 72.759782],

            draggable: true,
            title: "Marker title",
            onClick: (e) => {
              console.log("clicked ");
            },
            onDragend: (e) => {
              console.log("dragged");
            },
          },
        ]}
      />

Please help


问:
Import "speech_recognition" could not be resolved
I installed the speech recognition and the pyttsx3 libraries

```<code>pip install SpeechRecognition
pip install pyttsx3
</code>```

but when i try to import them it gives two errors

```<code>Import "speech_recognition" could not be resolved
Import "pyttsx3" could not be resolved
</code>```

heres my code

```<code>import speech_recognition as sr
import pyttsx3

audio = sr.Recognizer()
</code>```

答:
Usually this happens because of virtual env or interpreter issues. Possible fixes:

Make sure that the interpreter you are using inside your IDE, is the same  as the one in which you installed the libraries.

Same as above in case of virtual env.

If your IDE is VS Code, then open the settings.json file and set python server to Jedi instead of Microsoft/Pylance.

I faced similar issues, was unable to diagnose the exact cause, but somehow the popular CodeRunner extension and VS code's recommended python extensions were in conflict. Therefore, i disabled the former and the program executed without any issues

Body:
I installed the speech recognition and the pyttsx3 libraries

pip install SpeechRecognition
pip install pyttsx3

but when i try to import them it gives two errors

Import "speech_recognition" could not be resolved
Import "pyttsx3" could not be resolved

heres my code

import speech_recognition as sr
import pyttsx3

audio = sr.Recognizer()


问:
VisualStudio says GitHub repository already exists but Github says it does not
I'm trying to create a new GitHub repo by Visual Studio Code, but when I created it got this message:

But actually i have no repo (public or private) named "INF256-Tarea-1" as you can see here:

This is what Git Output says:

```<code>Looking for git in: C:\Program Files\Git\cmd\git.exe
Using git 2.27.0.windows.1 from C:\Program Files\Git\cmd\git.exe
> git rev-parse --git-dir
Open repository: c:\Users\lilkimo\Desktop\Universidad\INF256\INF256-Tarea-1
> git fetch
> git status -z -u
> git symbolic-ref --short HEAD
> git rev-parse master
> git rev-parse --symbolic-full-name master@{u}
fatal: no upstream configured for branch 'master'
> git for-each-ref --sort -committerdate --format %(refname) %(objectname)
> git remote --verbose
> git check-ignore -v -z --stdin
> git config --get commit.template
> git status -z -u
> git symbolic-ref --short HEAD
> git rev-parse master
> git rev-parse --symbolic-full-name master@{u}
fatal: no upstream configured for branch 'master'
> git for-each-ref --sort -committerdate --format %(refname) %(objectname)
> git remote --verbose
> git config --get commit.template
</code>```

I do nothing strange, only click the 'Initialize Repository' Button, make the commit and push it.

答:
This is a vscode (Git) BUG!!!!
My way is

create a repository on github.com

Vscode Clone Git from github

rename local fileName and copy .git

create a folder with your repository name

copy you .git folder to your location

Body:
I'm trying to create a new GitHub repo by Visual Studio Code, but when I created it got this message:

But actually i have no repo (public or private) named "INF256-Tarea-1" as you can see here:

This is what Git Output says:

Looking for git in: C:\Program Files\Git\cmd\git.exe
Using git 2.27.0.windows.1 from C:\Program Files\Git\cmd\git.exe
> git rev-parse --git-dir
Open repository: c:\Users\lilkimo\Desktop\Universidad\INF256\INF256-Tarea-1
> git fetch
> git status -z -u
> git symbolic-ref --short HEAD
> git rev-parse master
> git rev-parse --symbolic-full-name master@{u}
fatal: no upstream configured for branch 'master'
> git for-each-ref --sort -committerdate --format %(refname) %(objectname)
> git remote --verbose
> git check-ignore -v -z --stdin
> git config --get commit.template
> git status -z -u
> git symbolic-ref --short HEAD
> git rev-parse master
> git rev-parse --symbolic-full-name master@{u}
fatal: no upstream configured for branch 'master'
> git for-each-ref --sort -committerdate --format %(refname) %(objectname)
> git remote --verbose
> git config --get commit.template

I do nothing strange, only click the 'Initialize Repository' Button, make the commit and push it.


问:
I'm writing a C program and I can't figure out how to insert "Press any key to continue..." and have it continue after any key and not just enter
I'm writing a menu driven program with a switch statement and while loop. My prof wants us to include "Press any key to continue..." and says to use getchar() for this. He says we will lose points if it requires us to press enter, which is what happens for me when I use the getchar().

I have seen many posts about using getch() with , however this is not working because I am using a C program compiled and executed with cygwin.

Thanks in advance

EDIT
Updating since I have not seen any answer for this specific question using Unix/Linux...
Emailed my prof and he got back to me with this...

"Unix/Linux issues. The keyboard input/output is buffered, i.e., your program might not get the character immediately after a user presses a key. Usually, the Operating System (OS) will send characters pressed after an ENTER key is pressed. If you want your program to get the character immediately after the user pressed it, run the following command in your shell (command window or Terminal). You only need to run it once after you first open your shell
stty -icanon min 1

I did this command in the shell before compiling and it still didn't work.

I then used getchar(); twice in a row since a scanf was used previously and doesn't consume the enter used and passes it to the first getchar();

Now it works and I can press ANY key to continue...

答:
For Linux I use the following code.

```<code>#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getch (void)
{
// Declare variables.
    int c = {0};
    struct termios oldt = {0};
    struct termios newt = {0};

// Get terminal attributes.
    tcgetattr(STDIN_FILENO, &oldt);
// Store attributes.
    newt = oldt;
// Set terminal to non-buffered.
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
// Get user input.
    c = getchar();
// Reset terminal attributes.
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

// Return character.
    return(c);
}
</code>```

For Windoze, just use #include <conio.h>.

Body:
For Linux I use the following code.

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getch (void)
{
// Declare variables.
    int c = {0};
    struct termios oldt = {0};
    struct termios newt = {0};

// Get terminal attributes.
    tcgetattr(STDIN_FILENO, &oldt);
// Store attributes.
    newt = oldt;
// Set terminal to non-buffered.
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
// Get user input.
    c = getchar();
// Reset terminal attributes.
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

// Return character.
    return(c);
}

For Windoze, just use #include <conio.h>.


问:
My page reloads, and the added task wont register
I am creating a to do list for my exam. For some reason the page keep reload when I click add task, and the tasks wont register. I am new to Vue.js and Javascript.
I have problems with finding the issue. It is a simple code, not to complex, but the add task part is not working.

Here is my code:

```<code><template >
  <section class="todolist">
   <h1 class="title">{{ title }}</h1>
    <form class="container">
        <h3 class="container__title">New Task </h3>
        <input class="container__input" type="text" placeholder="Enter task" v-model="task">
        <button class="container__button" @click="addPlanningTask">Add Task</button>
        <h3 class="container__title-second">To Do List</h3>
        <ul>
            <li v-for="(task, index) in tasks" :key="index">
             <span>{{ task.name }} </span>
             <button class="todolist__button" @click="deletePlanningTask">Remove</button>
            </li>
       </ul>
         <h4 class="container__list-title" v-if="task.length === 0">
             List is empty!</h4>
    </form>

    </section>
      <div class="guestlist">
        <h4 class="guestlist__title">{{ invited }}</h4>
        <span>{{ guestList }}</span>
        <button class="guestlist__button" @click="toggleGuestList">Guestlist</button>
      <div v-if="isGuestListVisible === true">
       <ul>
        <li v-for="guest in people" :key="guest.id.value">
            {{ guest.name.first }} {{ guest.name.last }}</li>
      </ul>
      </div>
     </div>
</template>
</code>```

答:
```<code>export default {
    props: {
            titleName: {
                type: String,
                default: 'todolist',
            },
    },
data() {
            return {
                title: 'Planning the party!',
                task: '',
                tasks: [{
                    name: ''
                }],
                invited: 'Who is invited?',
                guestList: '',
                people: [],
                name: '',
                isGuestListVisible: false

            }
        },
        created() {
            this.addGuest();
        },

        methods: {
            async addGuest() {
                const url = 'https://randomuser.me/api/?page=2&results=8';
                const res = await fetch(url);
                const { results }   = await res.json();
                this.people = results;

            },
             toggleGuestList() {
                this.isGuestListVisible = !this.isGuestListVisible;
             },
             addPlanningTask() {
            if(this.task.length === 0)
              return;

             this.tasks.push({
             name: this.task
             });
         },

        deletePlanningTask(index) {
        this.tasks.splice(index, 1);
        },
        },
      };
    </script>

</code>```

Body:
I am creating a to do list for my exam. For some reason the page keep reload when I click add task, and the tasks wont register. I am new to Vue.js and Javascript.
I have problems with finding the issue. It is a simple code, not to complex, but the add task part is not working.

Here is my code:

<template >

{{ title }}

    <form class="container">

New Task

        <input class="container__input" type="text" placeholder="Enter task" v-model="task">
        <button class="container__button" @click="addPlanningTask">Add Task</button>

To Do List

             {{ task.name }}
             <button class="todolist__button" @click="deletePlanningTask">Remove</button>

             List is empty!

    </form>

{{ invited }}

        {{ guestList }}
        <button class="guestlist__button" @click="toggleGuestList">Guestlist</button>

            {{ guest.name.first }} {{ guest.name.last }}

</template>


问:
Unable to activate Dart Devtools
enter image description hereOn opening dart devtools in VS its showing Dart devtools exited with code 255 .
I even tried to activating it from terminal in VS by typing flutter pub global activate devtools but its showing could not find a command named “global” for “flutter pub”
error shown on terminal
error again shown after activating devtools

答:
To activate devtools, use this command</p>
```<code>dart pub global activate devtools
</code>```

Title: Unable to activate Dart Devtools

Body:
To activate devtools, use this command

dart pub global activate devtools


答:
Have you looked at the console for your server process? It's probably spewing out errors.

You need a semicolon (;), not a colon (:) after require()

Then, you'd get "can't resolve getJSON.js" since what using an absolute path in require would refer to a module in node_modules. Instead, if docapi.js and getJSON.js are in the same directory, you'll want
```<code>const getJSON = require('./getJSON.js');
</code>```

Thirdly, the syntax in getJSON.js is invalid: You'll want e.g.
```<code>function test() {
   console.log("Hello again.")
}
</code>```

And to be able to call that function from the other file, you'll need to export it:
```<code>module.exports = function test() {
   console.log("Hello again.")
}
</code>```

After which you could do
```<code>const getJSON = require('./getJSON.js');
getJSON();
</code>```
in the other file.

Title: Why Am I Getting 502 Error After Adding Require In Express JS File?

Body:
Have you looked at the console for your server process? It's probably spewing out errors.

You need a semicolon (;), not a colon (:) after require()

Then, you'd get "can't resolve getJSON.js" since what using an absolute path in require would refer to a module in node_modules. Instead, if docapi.js and getJSON.js are in the same directory, you'll want

const getJSON = require('./getJSON.js');

Thirdly, the syntax in getJSON.js is invalid: You'll want e.g.

function test() {
   console.log("Hello again.")
}

And to be able to call that function from the other file, you'll need to export it:

module.exports = function test() {
   console.log("Hello again.")
}

After which you could do

const getJSON = require('./getJSON.js');
getJSON();

in the other file.


问:
Get ardupilot output channels
How do we get output channel values of an ardupilot from dronekit-python?

We can get input channels from vehicle.channels but I couldn't find anything similar for output channels.

EDIT:

```<code>from time import sleep
from dronekit import connect
import dronekit_sitl

sitl = dronekit_sitl.start_default()
connection_string = sitl.connection_string()

vehicle = connect(connection_string,wait_ready=True)

while not vehicle.is_armable:
    sleep(1)
    print"Initializing"

vehicle.armed = True
while not vehicle.armed:
    print "Arming"
    sleep(1)
print "Armed"

@vehicle.on_attribute('ch1out')
def ch1out_listener(self, name, msg):
    print '%s attribute is: %s' % (name, msg)

for i in range(1000,2000,100):
    vehicle.channels.overrides['3']=i
    sleep(1)

vehicle.close()
</code>```

It should print ch1out everytime I update channel 3 but it is not.

答:
The way to do this is to create a new vehicle class. You can do this following the example given in dronekit.

Then connect using your new class:

```<code>     vehicle = connect(connection_string, wait_ready=True,
     vehicle_class=MyVehicle) def raw_servo_callback(self, attr_name,
     value):
         print(value)
    vehicle.add_attribute_listener('raw_servo', raw_servo_callback)
</code>```

Here is the class for the above example:

```<code>from dronekit import Vehicle

class RawSERVO(object):
    """
    :param ch1out: servo1
    :param ch3out: servo3
    """
    def __init__(self, ch1out=None, ch3out=None):
        """
        RawIMU object constructor.
        """
        self.ch1out = ch1out
        self.ch3out = ch3out

    def __str__(self):
        """
        String representation used to print
        """
        return "{},{}".format(self.ch1out, self.ch3out)

class MyVehicle(Vehicle):
    def __init__(self, *args):
        super(MyVehicle, self).__init__(*args)

        # Create an Vehicle.raw_servo object with initial values set to None.
        self._raw_servo = RawSERVO()

        # Create a message listener using the decorator.
        @self.on_message('SERVO_OUTPUT_RAW')
        def listener(self, name, message):
            """
            The listener is called for messages that contain the string specified in the decorator,
            passing the vehicle, message name, and the message.

            The listener writes the message to the (newly attached) ``vehicle.raw_servo`` object
            and notifies observers.
            """
            self._raw_servo.ch1out=message.servo1_raw
            self._raw_servo.ch3out=message.servo3_raw

            # Notify all observers of new message (with new value)
            #   Note that argument `cache=False` by default so listeners
            #   are updated with every new message
            self.notify_attribute_listeners('raw_servo', self._raw_servo)

    @property
    def raw_servo(self):
        return self._raw_servo
</code>```

Title: Get ardupilot output channels

Body:
How do we get output channel values of an ardupilot from dronekit-python?

We can get input channels from vehicle.channels but I couldn't find anything similar for output channels.

EDIT:

from time import sleep
from dronekit import connect
import dronekit_sitl

sitl = dronekit_sitl.start_default()
connection_string = sitl.connection_string()

vehicle = connect(connection_string,wait_ready=True)

while not vehicle.is_armable:
    sleep(1)
    print"Initializing"

vehicle.armed = True
while not vehicle.armed:
    print "Arming"
    sleep(1)
print "Armed"

@vehicle.on_attribute('ch1out')
def ch1out_listener(self, name, msg):
    print '%s attribute is: %s' % (name, msg)

for i in range(1000,2000,100):
    vehicle.channels.overrides['3']=i
    sleep(1)

vehicle.close()

It should print ch1out everytime I update channel 3 but it is not.

Body:
The way to do this is to create a new vehicle class. You can do this following the example given in dronekit.

Then connect using your new class:

     vehicle = connect(connection_string, wait_ready=True,
     vehicle_class=MyVehicle) def raw_servo_callback(self, attr_name,
     value):
         print(value)
    vehicle.add_attribute_listener('raw_servo', raw_servo_callback)

Here is the class for the above example:

from dronekit import Vehicle

class RawSERVO(object):
    """
    :param ch1out: servo1
    :param ch3out: servo3
    """
    def __init__(self, ch1out=None, ch3out=None):
        """
        RawIMU object constructor.
        """
        self.ch1out = ch1out
        self.ch3out = ch3out

    def __str__(self):
        """
        String representation used to print
        """
        return "{},{}".format(self.ch1out, self.ch3out)

class MyVehicle(Vehicle):
    def __init__(self, *args):
        super(MyVehicle, self).__init__(*args)

        # Create an Vehicle.raw_servo object with initial values set to None.
        self._raw_servo = RawSERVO()

        # Create a message listener using the decorator.
        @self.on_message('SERVO_OUTPUT_RAW')
        def listener(self, name, message):
            """
            The listener is called for messages that contain the string specified in the decorator,
            passing the vehicle, message name, and the message.

            The listener writes the message to the (newly attached) ``vehicle.raw_servo`` object
            and notifies observers.
            """
            self._raw_servo.ch1out=message.servo1_raw
            self._raw_servo.ch3out=message.servo3_raw

            # Notify all observers of new message (with new value)
            #   Note that argument `cache=False` by default so listeners
            #   are updated with every new message
            self.notify_attribute_listeners('raw_servo', self._raw_servo)

    @property
    def raw_servo(self):
        return self._raw_servo


问:
How do I replace custom BBCode style tag with a hyperlink
I've got a bunch of text which can contain custom tags in this format:

```<code>[MYLINK ID="1234" URL="http://mywebsite.com" TEXT="Website link"]
</code>```

The text can contain multiple links.  What I'm trying to do is to translate the tags to normal html links and grab the IDs in C# code.  The resulting replaced tag should be in this format:

```<code><a href="http://mywebsite.com?id=1234">Website link</a>
</code>```

So to clarify, if I had the following chunk of text:

```<code>This is a test [MYLINK ID="1234" URL="http://mywebsite.com" TEXT="website link"] with some more text and [MYLINK ID="2345" URL="http://mywebsite2.com" TEXT="another link"] here too.
</code>```

It should translate to this:

```<code>This is a test <a href="http://mywebsite.com?id=1234">website link</a> with some more text and <a href="http://mywebsite2.com?id=2345">another link</a> here too.
</code>```

EDIT: Been faffing with Regex for the last couple of hours and have managed to get the following to match the tag but don't know what to do next...

```<code>\[MYLINK ID=\"(.*?)\" URL=\"(.*?)\" TEXT=\"(.*?)\"\]
</code>```

Any help would be greatly appreciated. Cheers,

答:
Thanks - I literally just got it as you were posting, doing something very similar...</p>
```<code>string pattern = @"\[MYLINK ID=\""(.*?)\"" URL=\""(.*?)\"" TEXT=\""(.*?)\""\]";
text = Regex.Replace(text, pattern, x => $"<a href='{x.Groups[2].Value}?id={x.Groups[1].Value}'>{x.Groups[3].Value}</a>");
</code>```

Body:
I've got a bunch of text which can contain custom tags in this format:

[MYLINK ID="1234" URL="http://mywebsite.com" TEXT="Website link"]

The text can contain multiple links.  What I'm trying to do is to translate the tags to normal html links and grab the IDs in C# code.  The resulting replaced tag should be in this format:

Website link

So to clarify, if I had the following chunk of text:

This is a test [MYLINK ID="1234" URL="http://mywebsite.com" TEXT="website link"] with some more text and [MYLINK ID="2345" URL="http://mywebsite2.com" TEXT="another link"] here too.

It should translate to this:

This is a test website link with some more text and another link here too.

EDIT: Been faffing with Regex for the last couple of hours and have managed to get the following to match the tag but don't know what to do next...

\[MYLINK ID=\"(.*?)\" URL=\"(.*?)\" TEXT=\"(.*?)\"\]

Any help would be greatly appreciated. Cheers,

Body:
Thanks - I literally just got it as you were posting, doing something very similar...

string pattern = @"\[MYLINK ID=\""(.*?)\"" URL=\""(.*?)\"" TEXT=\""(.*?)\""\]";
text = Regex.Replace(text, pattern, x => $"<a href='{x.Groups[2].Value}?id={x.Groups[1].Value}'>{x.Groups[3].Value}</a>");


问:
struct with default members initializers cannot be inside class and used as default argument
The following code does not compile:

```<code>#include <iostream>

struct toto {
  struct options final {
    bool option1 = false;
    bool option2 = false;
  };

  static void func(const options &opt = {}) {
    std::cout << "option1 = " << opt.option1 << std::endl;
    std::cout << "option2 = " << opt.option2 << std::endl;
  }
};

int main() {
  toto::func();
}
</code>```

I get the following errors:

```<code>test-default-member-init.cc:12:42: error: default member initializer for 'option1' needed within definition of enclosing class 'toto' outside of member functions
  static void func(const options &opt = {}) {
                                         ^
test-default-member-init.cc:8:10: note: default member initializer declared here
    bool option1 = false;
         ^
test-default-member-init.cc:19:14: error: too few arguments to function call, single argument 'opt' was not specified
  toto::func();
  ~~~~~~~~~~ ^
test-default-member-init.cc:12:3: note: 'func' declared here
  static void func(const options &opt = {}) {
  ^
2 errors generated.
</code>```

But if I move the options struct outside of my enclosing toto struct, it does compile:

```<code>#include <iostream>

struct options final {
  bool option1 = false;
  bool option2 = false;
};

struct toto {
  static void func(const options &opt = {}) {
    std::cout << "option1 = " << opt.option1 << std::endl;
    std::cout << "option2 = " << opt.option2 << std::endl;
  }
};

int main() {
  toto::func();
}
</code>```

I'm using clang on OSX, and compile the code snippet this way:

```<code>$ clang --version
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

$ c++ -std=c++17 -stdlib=libc++ -o test-default-member-init test-default-member-init.cc
</code>```

Can someone explain me why the first code snipped it does not compile, and if there is any solution to get it working?

答:
I had a similar issue, It only happens on XCode. The only workaround that I found is to have 2 functions, one with a parameter and another one without it.
Call the second function/constructor from the first one with the default value.

Header

```<code>        struct CreateEntityParams
        {
            bool serializable = true;
        };
        explicit Entity(
            EntityId id,
            std::string name,
            Entity * parent = nullptr
        );
        explicit Entity(
            EntityId id,
            std::string name,
            CreateEntityParams const params
            Entity * parent = nullptr
        );
</code>```

Cpp

```<code>    Entity::Entity(
        EntityId id,
        std::string name,
        Entity * parent
    )
        : Entity(id, name, parent, CreateEntityParams {})
    {}

    Entity::Entity(
        EntityId const id,
        std::string name,
        CreateEntityParams const & params,
        Entity * parent
    )
        : mId(id)
        , mName(std::move(name))
        , mParent(parent)
        , mSerializable(params.serializable)
    {}
</code>```

Body:
The following code does not compile:

#include <iostream>

struct toto {
  struct options final {
    bool option1 = false;
    bool option2 = false;
  };

  static void func(const options &opt = {}) {
    std::cout << "option1 = " << opt.option1 << std::endl;
    std::cout << "option2 = " << opt.option2 << std::endl;
  }
};

int main() {
  toto::func();
}

I get the following errors:

test-default-member-init.cc:12:42: error: default member initializer for 'option1' needed within definition of enclosing class 'toto' outside of member functions
  static void func(const options &opt = {}) {
                                         ^
test-default-member-init.cc:8:10: note: default member initializer declared here
    bool option1 = false;
         ^
test-default-member-init.cc:19:14: error: too few arguments to function call, single argument 'opt' was not specified
  toto::func();
  ~~~~~~~~~~ ^
test-default-member-init.cc:12:3: note: 'func' declared here
  static void func(const options &opt = {}) {
  ^
2 errors generated.

But if I move the options struct outside of my enclosing toto struct, it does compile:

#include <iostream>

struct options final {
  bool option1 = false;
  bool option2 = false;
};

struct toto {
  static void func(const options &opt = {}) {
    std::cout << "option1 = " << opt.option1 << std::endl;
    std::cout << "option2 = " << opt.option2 << std::endl;
  }
};

int main() {
  toto::func();
}

I'm using clang on OSX, and compile the code snippet this way:

$ clang --version
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

$ c++ -std=c++17 -stdlib=libc++ -o test-default-member-init test-default-member-init.cc

Can someone explain me why the first code snipped it does not compile, and if there is any solution to get it working?

Body:
I had a similar issue, It only happens on XCode. The only workaround that I found is to have 2 functions, one with a parameter and another one without it.
Call the second function/constructor from the first one with the default value.

Header

        struct CreateEntityParams
        {
            bool serializable = true;
        };
        explicit Entity(
            EntityId id,
            std::string name,
            Entity * parent = nullptr
        );
        explicit Entity(
            EntityId id,
            std::string name,
            CreateEntityParams const params
            Entity * parent = nullptr
        );

Cpp

    Entity::Entity(
        EntityId id,
        std::string name,
        Entity * parent
    )
        : Entity(id, name, parent, CreateEntityParams {})
    {}

    Entity::Entity(
        EntityId const id,
        std::string name,
        CreateEntityParams const & params,
        Entity * parent
    )
        : mId(id)
        , mName(std::move(name))
        , mParent(parent)
        , mSerializable(params.serializable)
    {}


问:
How do I create a custom input svelte component and reuse prop types?
I'm trying to create a wrapped version of an input component with a label, I want it to have all the same attributes as the normal input field, as well as the "label".

I'm slightly confused about how to import the type definition and to type the attributes properly.

```<code><style>
    input {
        width: 100%;
        display: block;
    }
</style>

<script lang="typescript">
    import { SvelteInputProps } from 'svelte'
    export let label: string = ''
    type $$Props = SvelteInputProps;
</script>

<label>
    {label}
    <input {...$$props} />
</label>

</code>```

like this in react:

```<code>interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
    label: string
}

export default function Input (props: Props) {
    const { label, ...inputProps } = props;
    return (
        <label>
            {label}
            <input {...inputProps}></input>
        </label>
    )
}
</code>```

答: If you use svelte for vscode, there's a namespace already declared in the global scope (pretty much like the HTML typings provided by vscode), which is svelte.JSX.SvelteInputProps, I think that's what you're looking for. If you don't like the idea of rely on in-editor types (which is pretty reasonable) you can install the types directly in your project. If you wan't the very same interface, this is the project, but there are alternatives on definetely typed or go for js-dom types.

Body:
I'm trying to create a wrapped version of an input component with a label, I want it to have all the same attributes as the normal input field, as well as the "label".

I'm slightly confused about how to import the type definition and to type the attributes properly.

    {label}
    <input {...$$props} />

like this in react:

interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
    label: string
}

export default function Input (props: Props) {
    const { label, ...inputProps } = props;
    return (

            {label}
            <input {...inputProps}></input>

    )
}


问:
Sending HTML email using SAP Workflow "Send Mail" activity
We have a SAP workflow which uses "Send Mail" activity to send an email to relevant users.

I want to include hyperlinks in this email so that the user can be taken to particular site upon clicking the link in the email.

 Click here to view details

However, when the email is viewed in the email client, it is shown in RAW format.

How do I specify Send Mail to send out the email in HTML format??

答:
I’m not a workflow literate, but depending on what you want to do, you will have to code a little bit.

First, if you are just trying to add the hyperlink, you may try putting the following XML tag in your Send Mail task (don’t break the line).

```<code><A HREF="&URL&">Link<(><<)>/A>
</code>```

Then, if your e-mail is arriving as plain text, you may have to change the configuration on SCOT transaction, from RAW to HTM. (see explanation link below)

If that don’t work as expected, try coding a custom function module to receive the recipients and hyperlinks, and send the e-mail using SO_DOCUMENT_SEND_API1 FM (or SO_NEW_DOCUMENT_ATT_SEND_API1 FM, or even CL_BCS class ), so that you will have full control over e-mail sending.

Finally, take a look at the following POSTS from SDN

SCOT transaction discussion on workflow hyperlinks: http://forums.sdn.sap.com/thread.jspa?messageID=1152432#1152432

And how to use the FM or classes to send emails from workflow step:
http://forums.sdn.sap.com/thread.jspa?threadID=1948769

Body:
I’m not a workflow literate, but depending on what you want to do, you will have to code a little bit.

First, if you are just trying to add the hyperlink, you may try putting the following XML tag in your Send Mail task (don’t break the line).

<A HREF="&URL&">Link<(><<)>/A>

Then, if your e-mail is arriving as plain text, you may have to change the configuration on SCOT transaction, from RAW to HTM. (see explanation link below)

If that don’t work as expected, try coding a custom function module to receive the recipients and hyperlinks, and send the e-mail using SO_DOCUMENT_SEND_API1 FM (or SO_NEW_DOCUMENT_ATT_SEND_API1 FM, or even CL_BCS class ), so that you will have full control over e-mail sending.

Finally, take a look at the following POSTS from SDN

SCOT transaction discussion on workflow hyperlinks: http://forums.sdn.sap.com/thread.jspa?messageID=1152432#1152432

And how to use the FM or classes to send emails from workflow step:
http://forums.sdn.sap.com/thread.jspa?threadID=1948769


问:
Flutter: Preventing size change to child widgets in GridView
I have code that uses GridView to create a list of items with number of columns based on devices orientation or width.

GridView.count(
  crossAxisCount: columnCount(context),
  childAspectRatio: 8.0,
  padding: const EdgeInsets.all(4.0),
  mainAxisSpacing: 10.0,
  crossAxisSpacing: 10.0,
  children: <Widget>[...textsWidgets],
);
```

The problem is, the children (textsWidgets) changes size upon resizing the window of the application during runtime. Is there a way to prevent children from changing size when resizing the window of the application during runtime?

答:
You can simply wrap a GridView with ConstrainedBox to prevent it from growing with the window, like:

ConstrainedBox(
  constraints: BoxConstraints(maxWidth: 320),
  child: GridView.count(…),
)
```

Body:
I have code that uses GridView to create a list of items with number of columns based on devices orientation or width.

GridView.count(
  crossAxisCount: columnCount(context),
  childAspectRatio: 8.0,
  padding: const EdgeInsets.all(4.0),
  mainAxisSpacing: 10.0,
  crossAxisSpacing: 10.0,
  children: <Widget>[...textsWidgets],
);

The problem is, the children (textsWidgets) changes size upon resizing the window of the application during runtime. Is there a way to prevent children from changing size when resizing the window of the application during runtime?


问:
Is there a more concise way to write this? (Need to connect relation upon creation in Prisma)
```<code>model Case{
  id String @id @default(uuid())
  caseId Int @unique @default(autoincrement())
  title String
  status Status[]

}

model Status{
  id String @id @default(uuid())
  statusId Int @unique @default(autoincrement())
  title String
  caseId Int
  story Story[]
  case Case? @relation(fields: [caseId],references: [caseId], onDelete: Cascade)
}
</code>```

So let's say I have two Prisma Models like this. Case is the bigger one, so that one can be created with just the title. Now, I want it so that for someone to create a status, it needs to come with the caseId. So the post body is like this

```<code>{
  "caseId": 1,
  "title": "string"
}
</code>```

As such, right now my create code is like this

```<code>async create(status: CreateStatusDto) {
    const {caseId, ... rest} = status
    if(!caseId){
      throw new BadRequestException('Please Input Case Id')
    }
    return await this.prismaService.status.create({
      data: {
        ...rest,
        case: {
          connect: {
            caseId: caseId
          }
        }
      }
    })
  }
</code>```

And it's not exactly pretty, so I'm looking for a better way to write it. Any suggestions?

答:
First of all, you could use a ValidationPipe to check if caseId is valid.

Second, you might wanna take a look at Exception Filters as they would make your code cleaner and your life easier (your exception should inform what happened, and not "ask" for the user to fix it, as you're doing).

As for Prisma, here's an example from Prisma's doc on nested writes:

const createUserAndPost = await prisma.user.create({
  data: {
    email: 'elsa@prisma.io',
    name: 'Elsa Prisma',
    posts: {
      create: [
        { title: 'How to make an omelette' },
        { title: 'How to eat an omelette' },
      ],
    },
  },
})
```

Body:
model Case{
  id String @id @default(uuid())
  caseId Int @unique @default(autoincrement())
  title String
  status Status[]

}

model Status{
  id String @id @default(uuid())
  statusId Int @unique @default(autoincrement())
  title String
  caseId Int
  story Story[]
  case Case? @relation(fields: [caseId],references: [caseId], onDelete: Cascade)
}

So let's say I have two Prisma Models like this. Case is the bigger one, so that one can be created with just the title. Now, I want it so that for someone to create a status, it needs to come with the caseId. So the post body is like this

{
  "caseId": 1,
  "title": "string"
}

As such, right now my create code is like this

async create(status: CreateStatusDto) {
    const {caseId, ... rest} = status
    if(!caseId){
      throw new BadRequestException('Please Input Case Id')
    }
    return await this.prismaService.status.create({
      data: {
        ...rest,
        case: {
          connect: {
            caseId: caseId
          }
        }
      }
    })
  }

And it's not exactly pretty, so I'm looking for a better way to write it. Any suggestions?


问:
How to refer to a merged cell in a formula (or to a "bottom-up" range)
I've got this (long) table on Google Sheets:

The cells of column B may be vertically merged, but the number of rows for each multi-cell is random.

Since, for each multi-cell, the top cell is the one containing the value, I need to use a formula which refers, for instance, to the cell B1 in the cells A1 and A2, to the cell B3 in the cells A3, A4 and A5, and so forth.

I thought to build a kind of bottom-up coalesce. E.g. if I'm in cell A10, I want to go from $B10 towards the top until I find a non-null value (i.e. until $B7).
For doing this, I tried to insert the above formula in A10:

```<code>=INDEX($B10:$B$1,MATCH(FALSE,ISBLANK($B10:$B$1),FALSE))
</code>```

but it doesn't accept a range starting from a lower position with respect to the endpoint. Or, better, such range will be automatically flipped to $B$1:$B10. It follows that the first non-empty value is the one of $B$1 and the returned value in A10 is 3 instead of 1.

Is there a way to express such inverted range? In case it isn't possible, how can I solve this problem?

答:
in A10 or any other row you can use:

```<code>=INDEX(VLOOKUP(ROW(), IF(B:B<>"", {ROW(B:B), B:B}), 2))
</code>```

if you want to fill the whole A column with B values use this in A1:

```<code>=INDEX(VLOOKUP(ROW(B:B), IF(B:B<>"", {ROW(B:B), B:B}), 2))
</code>```

Body:
I've got this (long) table on Google Sheets:

The cells of column B may be vertically merged, but the number of rows for each multi-cell is random.

Since, for each multi-cell, the top cell is the one containing the value, I need to use a formula which refers, for instance, to the cell B1 in the cells A1 and A2, to the cell B3 in the cells A3, A4 and A5, and so forth.

I thought to build a kind of bottom-up coalesce. E.g. if I'm in cell A10, I want to go from $B10 towards the top until I find a non-null value (i.e. until $B7).
For doing this, I tried to insert the above formula in A10:

=INDEX($B10:$B$1,MATCH(FALSE,ISBLANK($B10:$B$1),FALSE))

but it doesn't accept a range starting from a lower position with respect to the endpoint. Or, better, such range will be automatically flipped to $B$1:$B10. It follows that the first non-empty value is the one of $B$1 and the returned value in A10 is 3 instead of 1.

Is there a way to express such inverted range? In case it isn't possible, how can I solve this problem?

Body:
in A10 or any other row you can use:

=INDEX(VLOOKUP(ROW(), IF(B:B<>"", {ROW(B:B), B:B}), 2))

if you want to fill the whole A column with B values use this in A1:

=INDEX(VLOOKUP(ROW(B:B), IF(B:B<>"", {ROW(B:B), B:B}), 2))


问:
Cell color changing in Excel using C#
I am using a Windows application for exporting a data table to Excel. It's working. Now I want to give some color for particular text in the cell. How shall I do this?</p>

答:
For C#, using the Workbook class (which implements the Workbook Interface) can provide lots of tools for coloring.  I used Workbook (templateWorkbook in below example) as follows to set colors:</p>
```<code>var copyFormating = templateWorkbook.Worksheets[sheetName].Cells[9,0].GetStyle();
copyFormating.ForegroundColor = System.Drawing.Color.Gold;
copyFormating.Font.Color = System.Drawing.Color.Black;
copyFormating.HorizontalAlignment = TextAlignmentType.Center;
</code>```

Title: Cell color changing in Excel using C#

Body:
For C#, using the Workbook class (which implements the Workbook Interface) can provide lots of tools for coloring.  I used Workbook (templateWorkbook in below example) as follows to set colors:

var copyFormating = templateWorkbook.Worksheets[sheetName].Cells[9,0].GetStyle();
copyFormating.ForegroundColor = System.Drawing.Color.Gold;
copyFormating.Font.Color = System.Drawing.Color.Black;
copyFormating.HorizontalAlignment = TextAlignmentType.Center;


问:
Convert List of Lists to int array
I have input of list of lists which i want to convert into int array which can help for my logic

list of Lists "lst" has input [[1,0,1],[1,1,0],[0,0,1]]

output array should be like {{1,0,1},{1,1,0},{0,0,1}}

```<code>int[] arr = new int[lst.size()];

for(int i=0;i<lst.size();i++){
    for(int j=0;j<lst.size();j++){
        arr[i] =  lst.get(i).get(j);
    }
}
</code>```

答:
Here are two ways.

The data

```<code>List<List<Integer>> list = List.of(List.of(1,0,1),
                                   List.of(1,1,0),
                                   List.of(0,0,1));
</code>```

allocate an Array of arrays for the number of rows.

iterate over the rows of the data.

create an array to hold the inner array contents

fill it and assign to the array of arrays.

```<code>int[][] arr = new int[list.size()][];
for (int i = 0; i < list.size(); i++) {
    List<Integer> lst = list.get(i);
    int [] temp = new int[lst.size()];
    for (int k = 0; k < lst.size(); k++) {
        temp[k] = lst.get(k);
    }
    arr[i] = temp;
}

System.out.println(Arrays.deepToString(arr));
</code>```

Or

stream the lists of lists

then stream each of those lists, mapping to an int and creating an array.

the put those arrays in an Array of arrays.

```<code>int[][] arr = list.stream()
               .map(ls->ls.stream().mapToInt(a->a).toArray())
               .toArray(int[][]::new);

System.out.println(Arrays.deepToString(arr));
</code>```

Both print

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

Title: Convert List of Lists to int array

Body:
I have input of list of lists which i want to convert into int array which can help for my logic

list of Lists "lst" has input [[1,0,1],[1,1,0],[0,0,1]]

output array should be like {{1,0,1},{1,1,0},{0,0,1}}

int[] arr = new int[lst.size()];

for(int i=0;i<lst.size();i++){
    for(int j=0;j<lst.size();j++){
        arr[i] =  lst.get(i).get(j);
    }
}

Body:
Here are two ways.

The data

List<List<Integer>> list = List.of(List.of(1,0,1),
                                   List.of(1,1,0),
                                   List.of(0,0,1));

allocate an Array of arrays for the number of rows.

iterate over the rows of the data.

create an array to hold the inner array contents

fill it and assign to the array of arrays.

int[][] arr = new int[list.size()][];
for (int i = 0; i < list.size(); i++) {
    List<Integer> lst = list.get(i);
    int [] temp = new int[lst.size()];
    for (int k = 0; k < lst.size(); k++) {
        temp[k] = lst.get(k);
    }
    arr[i] = temp;
}

System.out.println(Arrays.deepToString(arr));

Or

stream the lists of lists

then stream each of those lists, mapping to an int and creating an array.

the put those arrays in an Array of arrays.

int[][] arr = list.stream()
               .map(ls->ls.stream().mapToInt(a->a).toArray())
               .toArray(int[][]::new);

System.out.println(Arrays.deepToString(arr));

Both print

[[1, 0, 1], [1, 1, 0], [0, 0, 1]]


答:
you can use instead a wrap widget and use a sizedbox or a container as children and define the with and the height like this:

```<code>Wrap(
          spacing : 10.0,
          runSpacing : 10.0,
          children: <Widget>[
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
          ],
        )
</code>```

this is how it looks in small size window:

this is how it looks in big size window:

Title: Flutter: Preventing size change to child widgets in GridView

Body:
you can use instead a wrap widget and use a sizedbox or a container as children and define the with and the height like this:

Wrap(
          spacing : 10.0,
          runSpacing : 10.0,
          children: <Widget>[
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
            Container(
                width: 100,
                height: 100,
                color: Colors.indigo,
                child: Center(child: Text('data'))
            ),
          ],
        )

this is how it looks in small size window:

this is how it looks in big size window:


问:
Stop full organization data export google admin console
I have exported the data of my complete organization (multiple accounts) from my google admin console. I want to pause/stop the data export now. What are the options to do this?

答:
Based on my experience it is not possible. You need to contact Google Workspace Support for them to assist you on cancelling the task on the backend (it usually takes from 24 to 72 hours).

As a workaround you could remove the admin roles from the admin account that started the export, or if it was you, you could just give super admin rights to another user and ask to be removed as super admin temporarily because that would cancel the data export according to the official documentation.

Once it is cancelled you can ask the other person to give your super admin rights back, but be aware that the Admin console can take from 24 to 48 hours to give you full access as super admin again.

"If your Google Account loses super admin privileges while an export you started is running, the export is automatically canceled. No data is exported and other super admins receive an email notification that the export was unsuccessful".