问:
Resizing chart before downloading as image
I access the chart canvas to offer users to download image versions of generated charts, like this:

```<code>canvas.toBlob(function(blob) {
  let img = URL.createObjectURL(blob);
  let a = document.createElement('a');
  a.href = img;
  a.download = 'chart.png';
  a.click();
});
</code>```

This approach works but since the chart dimensions are responsive to the users device (which is a good thing), the dimensions of the downloaded chart are also dependent on the user window size, resolution etc. This is not ideal in most cases because the user is likely to want to share the image on social media etc, where standard dimensions are preferable (like a 16/9 ratio).

What is the best approach to this problem? I looked at resizing the chart before generating the image (and then restoring the original dimensions afterwards), but this is a bit complicated - hopefully there is a better solution?

答:
Here's how I solved the problem. I'm sure there's a better solution, but it does the job:</p>
```<code>var button; // link to download chart
var canvas; // the chart canvas to download

button.addEventListener('click', _ => {
        let resized = adjustCanvasWidth(canvas);
        setTimeout(_ => {
            canvas.toBlob(blob => {
                    const img = URL.createObjectURL(blob);
                    const downloadLink = document.createElement('a');
                    downloadLink.href = img;
                    downloadLink.download = CHARTFILENAME + '.png';
                    downloadLink.click();

                    if(resized) {
                        canvas.parentElement.style.width = 'auto';
                        resizeChart(canvas);
                    }
            });
        }, 1000);
});

function adjustCanvasWidth(canvas) {
    let maxWidth = Math.round(canvas.clientHeight * 16 / 9);
    if(canvas.parentElement.clientWidth > maxWidth) {
        canvas.parentElement.style.width = maxWidth + 'px';
        return resizeChart(canvas);
    }
}

function resizeChart(canvas) {
    let charts = Object.values(Chart.instances).filter(chart => {
        return chart.canvas == canvas;
    });
    if(charts.length == 1) {
        let chart = charts[0];
        chart.resize();
        return true;
    }
}
</code>```

Body:
I access the chart canvas to offer users to download image versions of generated charts, like this:

canvas.toBlob(function(blob) {
  let img = URL.createObjectURL(blob);
  let a = document.createElement('a');
  a.href = img;
  a.download = 'chart.png';
  a.click();
});

This approach works but since the chart dimensions are responsive to the users device (which is a good thing), the dimensions of the downloaded chart are also dependent on the user window size, resolution etc. This is not ideal in most cases because the user is likely to want to share the image on social media etc, where standard dimensions are preferable (like a 16/9 ratio).

What is the best approach to this problem? I looked at resizing the chart before generating the image (and then restoring the original dimensions afterwards), but this is a bit complicated - hopefully there is a better solution?

Body:
Here's how I solved the problem. I'm sure there's a better solution, but it does the job:

var button; // link to download chart
var canvas; // the chart canvas to download

button.addEventListener('click', _ => {
        let resized = adjustCanvasWidth(canvas);
        setTimeout(_ => {
            canvas.toBlob(blob => {
                    const img = URL.createObjectURL(blob);
                    const downloadLink = document.createElement('a');
                    downloadLink.href = img;
                    downloadLink.download = CHARTFILENAME + '.png';
                    downloadLink.click();

                    if(resized) {
                        canvas.parentElement.style.width = 'auto';
                        resizeChart(canvas);
                    }
            });
        }, 1000);
});

function adjustCanvasWidth(canvas) {
    let maxWidth = Math.round(canvas.clientHeight * 16 / 9);
    if(canvas.parentElement.clientWidth > maxWidth) {
        canvas.parentElement.style.width = maxWidth + 'px';
        return resizeChart(canvas);
    }
}

function resizeChart(canvas) {
    let charts = Object.values(Chart.instances).filter(chart => {
        return chart.canvas == canvas;
    });
    if(charts.length == 1) {
        let chart = charts[0];
        chart.resize();
        return true;
    }
}


来源: stackexchange

问:
How to return a multidimensional array of numbers in descending order?
I am new to JS and I am tring to sort a multidimensional array and I want to return the array in descending order -

Input -

```<code>let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
</code>```

Expected Ouput

```<code>[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]
</code>```

I have tried sort

```<code>let result = input.sort((a, b) => a - b)
</code>```

But I am getting the same array sent back to me

```<code>[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
</code>```

I have also tried a for loop with the sort method

```<code>for(let i = 0; i < input.length; i++){
  let inputArr = input[i]
  let output = inputArr.sort((a,b) => a - b)

  console.log(output)
}
</code>```

But I get returned

```<code>[1,2,3] 6 times (the length of the original array?)
</code>```

How do I return the array values in descending order?

Thanks

答:
The sort operation expects numbers. You can apply the .sort() array method on input using concatenated inner array elements converted into a number - +arr.join('') - as in the following demo:

let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ];

const sorted = input.sort( (a,b) => +b.join('') - +a.join('') );

console.log( sorted );
//OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]```

NOTE

You may also use parseInt( arr.join('') ) in place of +arr.join('').

ContentLicense: CC BY-SA 4.0

Body:
I am new to JS and I am tring to sort a multidimensional array and I want to return the array in descending order -

Input -

let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

Expected Ouput

[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]

I have tried sort

let result = input.sort((a, b) => a - b)

But I am getting the same array sent back to me

[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

I have also tried a for loop with the sort method

for(let i = 0; i < input.length; i++){
  let inputArr = input[i]
  let output = inputArr.sort((a,b) => a - b)

  console.log(output)
}

But I get returned

[1,2,3] 6 times (the length of the original array?)

How do I return the array values in descending order?

Thanks

Body:
The sort operation expects numbers. You can apply the .sort() array method on input using concatenated inner array elements converted into a number - +arr.join('') - as in the following demo:

let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ];

const sorted = input.sort( (a,b) => +b.join('') - +a.join('') );

console.log( sorted );
//OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]

NOTE

You may also use parseInt( arr.join('') ) in place of +arr.join('').


问:
How to replace only missing value of specific column from datafarm 1 by value matched from data frame 2
I have two dataframes as shown below:

```<code>structure(list(ID = c("a", "a", "c", "d", "a", "f"), a1 = c("2001",
"2000", "2000", "1998", "2006", "2002"), value = c("100", NA,
"200", NA, "400", "500")), class = "data.frame", row.names = c(NA,
-6L))

ID2 <- c("x","a","c","d","n","f","g","m")
a2 <- c(2000,2000,2000,2000,2000,2000,2000,2000)
value2 <- c(100, 1000, 20000, 1000, 400,500,1,1)

  ID   a1 value
1  a 2001   100
2  a 2000  <NA>
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500

  ID2   a2 value2
1   x 2000    100
2   a 2000   1000
3   c 2000  20000
4   d 2000   1000
5   n 2000    400
6   f 2000    500
7   g 2000      1
8   m 2000      1
</code>```

what I want to do: I want to replace only missing value in column value of data frame 1 by corresponding value from value2 column of dataframe 2. the year and ID should match. I tried the following code using left_join; however, this gave me the wrong result

```<code>r <- left_join(data, data2, by=c("ID"="ID2","a1"="a2"))
</code>```

Any suggetsion?

expected result

```<code>  ID   a1 value
1  a 2001   100
2  a 2000  **1000**
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500
</code>```

答:
Here's a tidyverse approach.

Note that because your a1 and value from dataframe 1 is character, I've also changed the corresponding columns of dataframe 2 to character.

What you need to do is to left_join them together, and coalesce the value with value2.

```<code>library(tidyverse)

ID2 <- c("x","a","c","d","n","f","g","m")
a2 <- c("2000","2000","2000","2000","2000","2000","2000","2000")
value2 <- c("100", "1000", "20000", "1000", "400","500","1","1")
df2 <- data.frame(ID2, a2, value2)

left_join(df1, df2, by = c("ID" = "ID2", "a1" = "a2")) %>%
  transmute(ID = ID, a1 = a1, value = coalesce(value, value2))

  ID   a1 value
1  a 2001   100
2  a 2000  1000
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500
</code>```

Body:
I have two dataframes as shown below:

structure(list(ID = c("a", "a", "c", "d", "a", "f"), a1 = c("2001",
"2000", "2000", "1998", "2006", "2002"), value = c("100", NA,
"200", NA, "400", "500")), class = "data.frame", row.names = c(NA,
-6L))

ID2 <- c("x","a","c","d","n","f","g","m")
a2 <- c(2000,2000,2000,2000,2000,2000,2000,2000)
value2 <- c(100, 1000, 20000, 1000, 400,500,1,1)

  ID   a1 value
1  a 2001   100
2  a 2000  <NA>
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500

  ID2   a2 value2
1   x 2000    100
2   a 2000   1000
3   c 2000  20000
4   d 2000   1000
5   n 2000    400
6   f 2000    500
7   g 2000      1
8   m 2000      1

what I want to do: I want to replace only missing value in column value of data frame 1 by corresponding value from value2 column of dataframe 2. the year and ID should match. I tried the following code using left_join; however, this gave me the wrong result

r <- left_join(data, data2, by=c("ID"="ID2","a1"="a2"))

Any suggetsion?

expected result

  ID   a1 value
1  a 2001   100
2  a 2000  **1000**
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500

Body:
Here's a tidyverse approach.

Note that because your a1 and value from dataframe 1 is character, I've also changed the corresponding columns of dataframe 2 to character.

What you need to do is to left_join them together, and coalesce the value with value2.

library(tidyverse)

ID2 <- c("x","a","c","d","n","f","g","m")
a2 <- c("2000","2000","2000","2000","2000","2000","2000","2000")
value2 <- c("100", "1000", "20000", "1000", "400","500","1","1")
df2 <- data.frame(ID2, a2, value2)

left_join(df1, df2, by = c("ID" = "ID2", "a1" = "a2")) %>%
  transmute(ID = ID, a1 = a1, value = coalesce(value, value2))

  ID   a1 value
1  a 2001   100
2  a 2000  1000
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500


问:
I am changing the state of the REACT component from another component but no refresh
I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in  and I change the state when "onSubmit:" happened
but the Users REACT component didn't reload .
What is wrong with this approach?</p>
```<code>import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect }  from 'react';
import { useFormik } from 'formik';
function unique_id() {
    return uuidv4()
}
var PlayersBackend='/players';
const validate = values => {
    const errors = {};
    if (values.firstName === 0 || values.firstName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.firstName = 'Required';
    } else if (values.firstName.length === 0) {
        errors.firstName = 'The message must be no empty';
    }

    if (values.lastName === 0 || values.lastName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.lastName = 'Required';
    } else if (values.lastName.length === 0) {

        errors.lastName = 'The message must be no empty';
    }
    return errors;
};
const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })

};

const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            <label htmlFor="firstName">First Name</label>
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            <label htmlFor="lastName">Last Name</label>
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
        return <div>Loading...</div>;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                <ul>
                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (
                        <li className="d-flex justify-content-start" key={unique_id()}>
                            {player.firstName} {player.lastName}
                        </li>
                    ))}

                </ul>
            );

        }
        else return  (<ul> </ul> )

    }

}
</code>```

答:
Update: After seeing the answer about useEffect, which hints me a new idea to achieve the refreshing.

In Users,

const [refreshCounter, compUsersState] = useState(0);

useEffect(() => {
    fetch(PlayersBackend)
      .then((response) => response.json())
      .then(
        (data) => {
          setIsLoaded(true);
          setPlayers(data);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, [refreshCounter]);
```
<p>By adding the counter state into the dependency array, you can be sure that the <code>useEffect</code> is triggered every time the counter gets incremented.</p>
<hr />
<p>I recommend passing <code>setPlayers</code> function to <code><AddPlayerForm></code>, and trigger the function to add a new player to the <code>users</code> list, after successfully added a player.</p>
<p>In <code>Users</code>,</p>
<pre class="lang-js prettyprint-override"><code><AddPlayerForm compUsersState={compUsersState} setPlayers={setPlayers} />
</code>```

In AddPlayerForm,

const AddPlayerForm = ({compUsersState, setPlayers}) => {
  const formik = useFormik({
    initialValues: { firstName: "", lastName: "" },
    validate,
    onSubmit: (values, { resetForm }) => {
      addPlayer(values.firstName, values.lastName).then();
      resetForm();
      console.log(compUsersState.compUsersState);
      compUsersState.compUsersState((p) => p + 1);
      const newPlayer = values; // Or change the format
      setPlayers((p) => [...p, newPlayer])
    },
  });
  ...
```

I can see you are trying to refresh the Users component by calling compUsersState((p) => p + 1), and I think it is working.
If you are not sure, inspect the element with React Developer Tool and check the state has been successfully changed.

But the actual problem is that the users state didn't get updated. So the UI looks the same as before.

Body:
I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in  and I change the state when "onSubmit:" happened
but the Users REACT component didn't reload .
What is wrong with this approach?

import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect }  from 'react';
import { useFormik } from 'formik';
function unique_id() {
    return uuidv4()
}
var PlayersBackend='/players';
const validate = values => {
    const errors = {};
    if (values.firstName === 0 || values.firstName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.firstName = 'Required';
    } else if (values.firstName.length === 0) {
        errors.firstName = 'The message must be no empty';
    }

    if (values.lastName === 0 || values.lastName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.lastName = 'Required';
    } else if (values.lastName.length === 0) {

        errors.lastName = 'The message must be no empty';
    }
    return errors;
};
const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })

};

const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            First Name
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            Last Name
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        return
Error: {error.message}
;
    } else if (!isLoaded) {
        return
Loading...
;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (

                            {player.firstName} {player.lastName}

                    ))}

            );

        }
        else return  (

 )

    }

}

Body:
Update: After seeing the answer about useEffect, which hints me a new idea to achieve the refreshing.

In Users,

const [refreshCounter, compUsersState] = useState(0);

useEffect(() => {
    fetch(PlayersBackend)
      .then((response) => response.json())
      .then(
        (data) => {
          setIsLoaded(true);
          setPlayers(data);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, [refreshCounter]);

By adding the counter state into the dependency array, you can be sure that the useEffect is triggered every time the counter gets incremented.

I recommend passing setPlayers function to <AddPlayerForm>, and trigger the function to add a new player to the users list, after successfully added a player.

In Users,

<AddPlayerForm compUsersState={compUsersState} setPlayers={setPlayers} />

In AddPlayerForm,

const AddPlayerForm = ({compUsersState, setPlayers}) => {
  const formik = useFormik({
    initialValues: { firstName: "", lastName: "" },
    validate,
    onSubmit: (values, { resetForm }) => {
      addPlayer(values.firstName, values.lastName).then();
      resetForm();
      console.log(compUsersState.compUsersState);
      compUsersState.compUsersState((p) => p + 1);
      const newPlayer = values; // Or change the format
      setPlayers((p) => [...p, newPlayer])
    },
  });
  ...

I can see you are trying to refresh the Users component by calling compUsersState((p) => p + 1), and I think it is working.
If you are not sure, inspect the element with React Developer Tool and check the state has been successfully changed.

But the actual problem is that the users state didn't get updated. So the UI looks the same as before.


问:
Sharing data across processes on linux
In my application, I have a process which forks off a child, say child1, and this child process writes a huge binary file on the disk and exits. The parent process then forks off another child process, child2, which reads in this huge file to do further processing.

The file dumping and re-loading is making my application slow and I'm thinking of possible
ways of avoiding disk I/O completely. Possible ways I have identified are ram-disk or tmpfs.
Can I somehow implement ram-disk or tmpfs from within my application? Or is there any other
way by which I can avoid disk I/O completely and send data across processes reliably.

答:
If the two sub-processes do not run at the same time pipes or sockets won't work for you – their buffers would be too small for the 'huge binary file' and the first process will block waiting for anything for reading the data.

In such case you rather need some kind of shared memory. You can use the SysV IPC shared memory API, POSIX shared memory API (which internally uses tmpfs on recent Linux) or use files on a tmpfs (usually mounted on /dev/shm, sometimes on /tmp) file system directly.

ContentLicense: CC BY-SA 3.0

Title: Sharing data across processes on linux


问:
Python aiohttp + asyncio: How to execute code after loop.run_forever()
Code:

#!/usr/bin/env python

import asyncio
import os
import socket
import time
import traceback
from aiohttp import web
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count

CPU_COUNT = cpu_count()
print("CPU Count:", CPU_COUNT)

def mk_socket(host="127.0.0.1", port=9090, reuseport=False):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if reuseport:
        SO_REUSEPORT = 15
        sock.setsockopt(socket.SOL_SOCKET, SO_REUSEPORT, 1)
    sock.bind((host, port))
    return sock

async def index(request):
    icecast_index_path = os.path.abspath("../test/icecast/icecast_index.html")
    print(icecast_index_path)
    try:
        content = open(icecast_index_path, encoding="utf8").read()
        return web.Response(content_type="text/html", text=content)
    except Exception as e:
        return web.Response(content_type="text/html", text="<!doctype html>
Error: "+str(e)+"
")

async def start_server():
    try:
        host = "127.0.0.1"
        port=8080
        reuseport = True
        app = web.Application()
        app.add_routes([web.get('/', index)])
        runner = web.AppRunner(app)
        await runner.setup()
        sock = mk_socket(host, port, reuseport=reuseport)
        srv = web.SockSite(runner, sock)
        await srv.start()
        print('Server started at http://127.0.0.1:8080')
        return srv, app, runner
    except Exception:
        traceback.print_exc()
        raise

async def finalize(srv, app, runner):
    sock = srv.sockets[0]
    app.loop.remove_reader(sock.fileno())
    sock.close()

    #await handler.finish_connections(1.0)
    await runner.cleanup()
    srv.close()
    await srv.wait_closed()
    await app.finish()

def init():
    loop = asyncio.get_event_loop()
    srv, app, runner = loop.run_until_complete(start_server())
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete((finalize(srv, app, runner)))

if __name__ == '__main__':
    with ProcessPoolExecutor() as executor:
        for i in range(0, int(CPU_COUNT/2)):
            executor.submit(init)

    #after the aiohttp start i want to execute more code
    #for example:
    print("Hello world.")
    #in actual programm the ProcessPoolExecutor is called
    #inside a pyqt5 app
    #so i don't want the pyqt5 app to freeze.
```
<p>The problem is that with that code i can't execute code after the <code>ProcessPoolExecutor</code> calls.</p>
<p>How can i fix that?</p>
<p>I tried to remove this part:</p>
<pre class="lang-py prettyprint-override"><code>try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete((finalize(srv, app, runner)))
</code>```

in init() method but after that the aiohttp server is closed instantly.

Edit: If i use a thread instead of ProcessPoolExecutor then there is an aiohttp errors that says:

RuntimeError: set_wakeup_fd only works in main thread

RuntimeError: There is no current event loop in thread

Aiohttp + asyncio related errors.

Maybe i may use a @ signature up to def declarations (i suppose).

答:
Using with with an Executor will cause your process to block until the jobs in the executor are completed; since they’re running infinite event loops, they will never complete and your Executor will never unblock.

Instead, just use the executor to kick off the jobs, and run your stuff afterwards. When you’re finally done, call .shutdown() to wait for processes to exit:

executor = ProcessPoolExecutor()
for i in range(0, int(CPU_COUNT/2)):
    executor.submit(init)
# other code…
executor.shutdown()
```

Body:
Code:

#!/usr/bin/env python

import asyncio
import os
import socket
import time
import traceback
from aiohttp import web
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count

CPU_COUNT = cpu_count()
print("CPU Count:", CPU_COUNT)

def mk_socket(host="127.0.0.1", port=9090, reuseport=False):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if reuseport:
        SO_REUSEPORT = 15
        sock.setsockopt(socket.SOL_SOCKET, SO_REUSEPORT, 1)
    sock.bind((host, port))
    return sock

async def index(request):
    icecast_index_path = os.path.abspath("../test/icecast/icecast_index.html")
    print(icecast_index_path)
    try:
        content = open(icecast_index_path, encoding="utf8").read()
        return web.Response(content_type="text/html", text=content)
    except Exception as e:
        return web.Response(content_type="text/html", text="<!doctype html>
Error: "+str(e)+"
")

async def start_server():
    try:
        host = "127.0.0.1"
        port=8080
        reuseport = True
        app = web.Application()
        app.add_routes([web.get('/', index)])
        runner = web.AppRunner(app)
        await runner.setup()
        sock = mk_socket(host, port, reuseport=reuseport)
        srv = web.SockSite(runner, sock)
        await srv.start()
        print('Server started at http://127.0.0.1:8080')
        return srv, app, runner
    except Exception:
        traceback.print_exc()
        raise

async def finalize(srv, app, runner):
    sock = srv.sockets[0]
    app.loop.remove_reader(sock.fileno())
    sock.close()

    #await handler.finish_connections(1.0)
    await runner.cleanup()
    srv.close()
    await srv.wait_closed()
    await app.finish()

def init():
    loop = asyncio.get_event_loop()
    srv, app, runner = loop.run_until_complete(start_server())
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete((finalize(srv, app, runner)))

if __name__ == '__main__':
    with ProcessPoolExecutor() as executor:
        for i in range(0, int(CPU_COUNT/2)):
            executor.submit(init)

    #after the aiohttp start i want to execute more code
    #for example:
    print("Hello world.")
    #in actual programm the ProcessPoolExecutor is called
    #inside a pyqt5 app
    #so i don't want the pyqt5 app to freeze.

The problem is that with that code i can't execute code after the ProcessPoolExecutor calls.

How can i fix that?

I tried to remove this part:

try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete((finalize(srv, app, runner)))

in init() method but after that the aiohttp server is closed instantly.

Edit: If i use a thread instead of ProcessPoolExecutor then there is an aiohttp errors that says:

RuntimeError: set_wakeup_fd only works in main thread

RuntimeError: There is no current event loop in thread

Aiohttp + asyncio related errors.

Maybe i may use a @ signature up to def declarations (i suppose).


问:
React Native I can not store an array with AsyncStorage
I am newbie in React Native and I am trying to store and get an array with AsyncStorage in ReactNative.

I have two problems.

First, I do not know why but when I storage data, it only works the second time but I am calling first the set of useState.

```<code>const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };
</code>```

Second, how can I call the getData function to get all the data and show it? Are there something like .onInit, .onInitialize... in ReactNative? Here is my full code

```<code>const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);

  const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };

  const completeTask = (index) => {
    var itemsCopy = [...taskItems];
    itemsCopy.splice(index, 1);
    setTaskItems(itemsCopy);
    storeData(taskItems);
  }

  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@tasks', JSON.stringify(value))
      console.log('store', JSON.stringify(taskItems));
    } catch (e) {
      console.log('error');
    }
  }

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@tasks')
      if(value !== null) {
        console.log('get', JSON.parse(value));
      }
    } catch(e) {
      console.log('error get');
    }
  }
</code>```

答:
Updating state in React is not super intuitive. It's not asynchronous, and can't be awaited. However, it's not done immediately, either - it gets put into a queue which React optimizes according to its own spec.

That's why BYIRINGIRO Emmanuel's answer is correct, and is the easiest way to work with state inside functions. If you have a state update you need to pass to more than one place, set it to a variable inside your function, and use that.

If you need to react to state updates inside your component, use the useEffect hook, and add the state variable to its dependency array. The function in your useEffect will then run whenever the state variable changes.

Body:
I am newbie in React Native and I am trying to store and get an array with AsyncStorage in ReactNative.

I have two problems.

First, I do not know why but when I storage data, it only works the second time but I am calling first the set of useState.

const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };

Second, how can I call the getData function to get all the data and show it? Are there something like .onInit, .onInitialize... in ReactNative? Here is my full code

const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);

  const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };

  const completeTask = (index) => {
    var itemsCopy = [...taskItems];
    itemsCopy.splice(index, 1);
    setTaskItems(itemsCopy);
    storeData(taskItems);
  }

  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@tasks', JSON.stringify(value))
      console.log('store', JSON.stringify(taskItems));
    } catch (e) {
      console.log('error');
    }
  }

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@tasks')
      if(value !== null) {
        console.log('get', JSON.parse(value));
      }
    } catch(e) {
      console.log('error get');
    }
  }


问:
Getting "Unhandled Exception: User denied permissions to access the device's location"
After trying hard and spending a lot of time I found the following solution that worked for me:</p>

答:
The following step by step process might help :

pubspec.yaml

Add geolocator: ^8.0.1 under dependencies:

```<code>dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  geolocator: ^8.0.1
</code>```

AndroidManifest.xml

You will see the following :

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.get_weather">
</code>```

Add the following under the above code:

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.hardware.location.gps" />
</code>```

main.dart

```<code>import 'package:flutter/material.dart';
import 'package:get_weather/screens/loading_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}
</code>```

loading_screen.dart

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

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  void getLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    print(position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            //Get the current location
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}
</code>```

The code in loading_screen.dart will help you get the 'User denied permission' resolved.

Body:
The following step by step process might help :

pubspec.yaml

Add geolocator: ^8.0.1 under dependencies:

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  geolocator: ^8.0.1

AndroidManifest.xml

You will see the following :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.get_weather">

Add the following under the above code:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.hardware.location.gps" />

main.dart

import 'package:flutter/material.dart';
import 'package:get_weather/screens/loading_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

loading_screen.dart

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

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  void getLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    print(position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            //Get the current location
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

The code in loading_screen.dart will help you get the 'User denied permission' resolved.


问:
Networkx - problem while working big data
I am trying to triangulate a large amount of massive data using Delaunay to scipy.spatial for triangulation and networkx to get the node adjacency relations. My code works very well on small data sets but when I try to introduce volumes of about 2 miollion points I always get the following error:

raise NetworkXError(f"The node {n} is not in the graph.") from e
NetworkXError: The node 1 is not in the graph.

It seems like my graph store the first node and nothing more. When I did my research I found that networkx is well adapted to massive data

Here is my code :

```<code>import numpy as np
import networkx as nx
import scipy.spatial
points = np.genfromtxt('las1.xyz', delimiter = ';')
xy= points[:,0:2]
z= points[:,2]
delTri = scipy.spatial.Delaunay(xy)
edges = set()
for n in range(delTri.nsimplex):
       edge = sorted([delTri.vertices[n,0], delTri.vertices[n,1]])
       edges.add((edge[0], edge[1]))
       edge = sorted([delTri.vertices[n,0], delTri.vertices[n,2]])
       edges.add((edge[0], edge[1]))
       edge = sorted([delTri.vertices[n,1], delTri.vertices[n,2]])
       edges.add((edge[0], edge[1]))
pts_neigh = {}
graph = nx.Graph(list(edges))
for i in range(len(xy)):
       pts_neigh[i] =  list(graph.neighbors(i))
</code>```

I still get the edges list from my networkx graph but it seems like it fails at the level of constructing the nodes.
I will be so grateful for your help.

答:
Although it's possible to instantiate graph with specific data, the syntax can be a bit complex. An easier option is to explicitly add edges from a list:

graph = nx.Graph()
graph.add_edges_from(list(edges))
```

Body:
I am trying to triangulate a large amount of massive data using Delaunay to scipy.spatial for triangulation and networkx to get the node adjacency relations. My code works very well on small data sets but when I try to introduce volumes of about 2 miollion points I always get the following error:

raise NetworkXError(f"The node {n} is not in the graph.") from e
NetworkXError: The node 1 is not in the graph.

It seems like my graph store the first node and nothing more. When I did my research I found that networkx is well adapted to massive data

Here is my code :

import numpy as np
import networkx as nx
import scipy.spatial
points = np.genfromtxt('las1.xyz', delimiter = ';')
xy= points[:,0:2]
z= points[:,2]
delTri = scipy.spatial.Delaunay(xy)
edges = set()
for n in range(delTri.nsimplex):
       edge = sorted([delTri.vertices[n,0], delTri.vertices[n,1]])
       edges.add((edge[0], edge[1]))
       edge = sorted([delTri.vertices[n,0], delTri.vertices[n,2]])
       edges.add((edge[0], edge[1]))
       edge = sorted([delTri.vertices[n,1], delTri.vertices[n,2]])
       edges.add((edge[0], edge[1]))
pts_neigh = {}
graph = nx.Graph(list(edges))
for i in range(len(xy)):
       pts_neigh[i] =  list(graph.neighbors(i))

I still get the edges list from my networkx graph but it seems like it fails at the level of constructing the nodes.
I will be so grateful for your help.


问:
When should I use semicolons in SQL Server?
While checking some code on the web and scripts generated by SQL Server Management Studio I have noticed that some statements are ended with a semicolon.

So when should I use it?

答:
Personal opinion: Use them only where they are required. (See TheTXI's answer above for the required list.)

Since the compiler doesn't require them, you can put them all over, but why? The compiler won't tell you where you forgot one, so you'll end up with inconsistent use.

[This opinion is specific to SQL Server. Other databases may have more-stringent requirements. If you're writing SQL to run on multiple databases, your requirements may vary.]

tpdi stated above, "in a script, as you're sending more than one statement, you need it." That's actually not correct. You don't need them.

```<code>PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional';
PRINT 'Semicolons are optional';
</code>```

Output:

```<code>Semicolons are optional
Semicolons are optional
Semicolons are optional
Semicolons are optional
</code>```

OwnerDisplayName: apinto

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
Personal opinion: Use them only where they are required. (See TheTXI's answer above for the required list.)

Since the compiler doesn't require them, you can put them all over, but why? The compiler won't tell you where you forgot one, so you'll end up with inconsistent use.

[This opinion is specific to SQL Server. Other databases may have more-stringent requirements. If you're writing SQL to run on multiple databases, your requirements may vary.]

tpdi stated above, "in a script, as you're sending more than one statement, you need it." That's actually not correct. You don't need them.

PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional';
PRINT 'Semicolons are optional';

Output:

Semicolons are optional
Semicolons are optional
Semicolons are optional
Semicolons are optional

OwnerDisplayName: Rob Garrison


问:
Is is legal to have relativePath to parent pom in a repository?
I found this artifact pom in the maven 2 central repository:

http://search.maven.org/remotecontent?filepath=javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom

It includes:

```<code>...
<parent>
  <groupId>org.glassfish.web</groupId>
  <artifactId>jsp</artifactId>
  <version>2.2</version>
  <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<packaging>jar</packaging>
<version>${jsp-api.version}</version>
<name>JavaServer Pages(TM) API v${jsp-api.version}</name>
....
</code>```

I encountered a problem when I tried to resolve with Ivy the dependency:

```<code><dependency org="javax.servlet.jsp" name="jsp-api" rev="2.1.2" />
</code>```

Ivy could not resolve the dependency and printed out this error:

```<code>[ivy:resolve]       nexus: bad revision found in http://XXX/nexus/content/groups/public/javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom: expected='2.1.2 found='${jsp-api.version}'
</code>```

Now wonder if it is ok that a pom file in a repository references relatively to a parent pom?

答:
Yes, it is legal.

http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Project_Inheritance

From the error, it looks like it's not resolving ${jsp-api.version} for you.

Body:
I found this artifact pom in the maven 2 central repository:

http://search.maven.org/remotecontent?filepath=javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom

It includes:

...
<parent>
  <groupId>org.glassfish.web</groupId>
  <artifactId>jsp</artifactId>
  <version>2.2</version>
  <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<packaging>jar</packaging>
<version>${jsp-api.version}</version>
<name>JavaServer Pages(TM) API v${jsp-api.version}</name>
....

I encountered a problem when I tried to resolve with Ivy the dependency:

<dependency org="javax.servlet.jsp" name="jsp-api" rev="2.1.2" />

Ivy could not resolve the dependency and printed out this error:

[ivy:resolve]       nexus: bad revision found in http://XXX/nexus/content/groups/public/javax/servlet/jsp/jsp-api/2.1.2/jsp-api-2.1.2.pom: expected='2.1.2 found='${jsp-api.version}'

Now wonder if it is ok that a pom file in a repository references relatively to a parent pom?


问:
How to Hide Continue and Cancel button on Flutter Stepper
I wanna hide Continue and Cancel Button on Stepper
And change to On Enter Text Filed for continuing the step.
Is it possible?
How to do that?

Thanks

答:
```<code>      class MyHomePage extends StatefulWidget {
     const MyHomePage({Key? key}) : super(key: key);

       @override
        _MyHomePageState createState() => _MyHomePageState();
       }

      class _MyHomePageState extends State<MyHomePage> {
             int _currentstep = 0;

       @override
      Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    centerTitle: true,
    backgroundColor: Colors.green,
    title: const Text('App',style: TextStyle(color:
         Colors.white), ),
            ),

         body: Stepper(
          steps: [
    const Step(  state: _ _currentstep <= 0 ?
      StepState.editing : StepState.complete,
      isActive: _ _currentstep >= 0,
         title: Text('Account'), content: Center(child:
      Text('Account'),)),
     const Step(state: _ _currentstep <= 1 ?
      StepState.editing : StepState.complete,
      isActive: _ _currentstep >= 1,title: Text('Address'),
   content: Center(child:
    Text('Address'),)),
      const Step(state: _ _currentstep <= 2 ?
      StepState.editing : StepState.complete,
      isActive: _ _currentstep >= 2,title: Text('Confirm'), content: Center(child:
      Text('Confirm'),))
           ],
      onStepContinue: () {
        if (_currentstep < (2)) {
          setState(() {
            _currentstep += 1;
          });
        } ),
        controlsBuilder: (context, details) {
        return Row(
          mainAxisAlignment: _currentstep != 0
              ? MainAxisAlignment.spaceBetween
              : MainAxisAlignment.end,
          children: [
            if (_currentstep != 0)
              ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      side: const BorderSide(color: Colors.grey),
                      shape: RoundedRectangleBorder(
                          borderRadius:
       BorderRadius.circular(10)),
                      fixedSize: Size(20.w, 6.h),
                      elevation: 0,
                      primary: Colors.white),
                  onPressed: details.onStepCancel,
                  child: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.grey[300],
                  )),
            ElevatedButton(
                style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    fixedSize: Size(45, 6),
                    primary: buttonColor),
                onPressed: details.onStepContinue,
                child: Text(
                  "Next",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 13,
                      fontWeight: FontWeight.bold),
                ))
          ],
        );
      },
          )
         );
          }
     }
</code>```

by applying condition in controls builder you can hide or show the next or previous. button

Body:
      class MyHomePage extends StatefulWidget {
     const MyHomePage({Key? key}) : super(key: key);

       @override
        _MyHomePageState createState() => _MyHomePageState();
       }

      class _MyHomePageState extends State<MyHomePage> {
             int _currentstep = 0;

       @override
      Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    centerTitle: true,
    backgroundColor: Colors.green,
    title: const Text('App',style: TextStyle(color:
         Colors.white), ),
            ),

         body: Stepper(
          steps: [
    const Step(  state: _ _currentstep <= 0 ?
      StepState.editing : StepState.complete,
      isActive: _ _currentstep >= 0,
         title: Text('Account'), content: Center(child:
      Text('Account'),)),
     const Step(state: _ _currentstep <= 1 ?
      StepState.editing : StepState.complete,
      isActive: _ _currentstep >= 1,title: Text('Address'),
   content: Center(child:
    Text('Address'),)),
      const Step(state: _ _currentstep <= 2 ?
      StepState.editing : StepState.complete,
      isActive: _ _currentstep >= 2,title: Text('Confirm'), content: Center(child:
      Text('Confirm'),))
           ],
      onStepContinue: () {
        if (_currentstep < (2)) {
          setState(() {
            _currentstep += 1;
          });
        } ),
        controlsBuilder: (context, details) {
        return Row(
          mainAxisAlignment: _currentstep != 0
              ? MainAxisAlignment.spaceBetween
              : MainAxisAlignment.end,
          children: [
            if (_currentstep != 0)
              ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      side: const BorderSide(color: Colors.grey),
                      shape: RoundedRectangleBorder(
                          borderRadius:
       BorderRadius.circular(10)),
                      fixedSize: Size(20.w, 6.h),
                      elevation: 0,
                      primary: Colors.white),
                  onPressed: details.onStepCancel,
                  child: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.grey[300],
                  )),
            ElevatedButton(
                style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    fixedSize: Size(45, 6),
                    primary: buttonColor),
                onPressed: details.onStepContinue,
                child: Text(
                  "Next",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 13,
                      fontWeight: FontWeight.bold),
                ))
          ],
        );
      },
          )
         );
          }
     }

by applying condition in controls builder you can hide or show the next or previous. button


问:
Converting anonymous type to another anonymous type
I wrote a library that can serialize LINQ expressions to a byte array. A server can receive and reconstruct the query from the serialized data, plug in the appropriate data sources, and return the result to the client. The library supports projection to anonymous types. When the query is de-serialized, it reconstructs the anonymous RuntimeType by emitting the appropriate IL. When the client receives the result, there's an expectation that the type can be accessed using the anonymous type's properties.

E.g.

var query = Customers
   .Where(c => c.State == "CO")
   .Select(c => new { c.Id, c.FirstName, c.LastName });

var results = query.ToListAsync(cancellationToken);

foreach(var result in results)
{
   Console.WriteLine($"{c.Id} = {c.FirstName} {c.LastName}";
}
```

The underlying query provider can't present the result because the anonymous type created by IL emit is not the same type as what was defined in the query and so List<<>__anonymous1> is not convertible to `List<<>__anonymous2>. Therefore the type needs to be converted. The CastByExample trick here won't work because the type's aren't in the same assembly.

How can this be achieved?

答:
There's two options here:

Out-of-the box, Automapper does this.

The mapping can be performed by leveraging expression trees:

public static Func<object, TResult> CreateAnonymousTypeMapper<TResult>(Type srcType)
{
    /* Produces the following equivalent in delegate form:
     * TResult Convert(object obj)
     * {
     *      var source = (SourceType)obj;
     *      return new TResult(source.Property1, source.Property2, ...);
     * }
     */

    var destType = typeof(TResult);
    var destConstructor = destType.GetConstructors()[0];
    var constructorParams = destConstructor.GetParameters();
    var sourceProperties = srcType.GetProperties().ToDictionary(p => p.Name);
    var sourceParameterExpression = Expression.Parameter(typeof(object), "obj");
    var typedSourceParameterExpression = Expression.Parameter(srcType, "source");
    var convertObjToSourceExpression = Expression.Convert(sourceParameterExpression, srcType);
    var assignToSourceTypeExpression = Expression.Assign(
        typedSourceParameterExpression,
        convertObjToSourceExpression);
    var callConstructorArgumentExpressions = constructorParams
        .Select(param => Expression.Property(
            typedSourceParameterExpression,
            sourceProperties[param.Name!]))
        .Cast<Expression>()
        .ToArray();
    var callConstructorExpression = Expression.New(destConstructor, callConstructorArgumentExpressions);
    var returnTarget = Expression.Label(destType);
    var lambdaBodyExpression = Expression.Block(new[] { typedSourceParameterExpression },
        assignToSourceTypeExpression,
        Expression.Label(returnTarget, callConstructorExpression));
    var lambdaExpression = Expression.Lambda<Func<object, TResult>>(
        lambdaBodyExpression,
        sourceParameterExpression);

    return lambdaExpression.Compile();
}
```

Body:
I wrote a library that can serialize LINQ expressions to a byte array. A server can receive and reconstruct the query from the serialized data, plug in the appropriate data sources, and return the result to the client. The library supports projection to anonymous types. When the query is de-serialized, it reconstructs the anonymous RuntimeType by emitting the appropriate IL. When the client receives the result, there's an expectation that the type can be accessed using the anonymous type's properties.

E.g.

var query = Customers
   .Where(c => c.State == "CO")
   .Select(c => new { c.Id, c.FirstName, c.LastName });

var results = query.ToListAsync(cancellationToken);

foreach(var result in results)
{
   Console.WriteLine($"{c.Id} = {c.FirstName} {c.LastName}";
}

The underlying query provider can't present the result because the anonymous type created by IL emit is not the same type as what was defined in the query and so List<<>__anonymous1> is not convertible to `List<<>__anonymous2>. Therefore the type needs to be converted. The CastByExample trick here won't work because the type's aren't in the same assembly.

How can this be achieved?


问:
How to align elements in three columns, even when resizing
Desired outcome: I have three columns. I need them to be all the same width, as well as text and buttons to be on the same level in all three of them.

Problem: Depending on the number of words, columns become wider and buttons start to jump when text is resizing, and all three texts are resizing on a different points. I need to prevent that. How can I achieve this?

HTML:

```<code><section class="sub-offer">
      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
            rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
            quis!
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>

      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
            perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
            incidunt odio?
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>

      <div class="offer-container">
        <div class="offer-up">
          <h2>Lorem, ipsum.</h2>
          <img src="https://via.placeholder.com/150x150.png/09f/fff" alt="" />
        </div>
        <div class="offer-down">
          <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
            vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
            ullam quod porro atque error?
          </p>
        </div>
        <div class="more-btn">
          <a href="#">Lorem, ipsum.</a>
        </div>
      </div>
    </section>
</code>```

CSS:

```<code>.sub-offer {
  text-align: center;
  display: flex;
  position: relative;

  .offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
  }

  h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
  }

  p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
  }

  a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;

    &:hover {
      background: #e5e5e5;
    }
  }
}
</code>```

How they look now:

答:
I solved my issue. To give all three columns the same width I've used what @tacoshy recommended in the comments: section.sub-offer { display: flex; } .offer-container { width: calc(100% / 3); }

To align all three buttons though leaving all them responsive I've wrapped my button into a div and used the following css:

```<code>.more-btn {
    display: flex;
    align-self: center;
    margin-top: auto;
  }
</code>```

Body:
Desired outcome: I have three columns. I need them to be all the same width, as well as text and buttons to be on the same level in all three of them.

Problem: Depending on the number of words, columns become wider and buttons start to jump when text is resizing, and all three texts are resizing on a different points. I need to prevent that. How can I achieve this?

HTML:

Lorem, ipsum.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus a
            rerum sapiente odit porro obcaecati fugit, maxime modi veritatis
            quis!

          Lorem, ipsum.

Lorem, ipsum.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi
            perspiciatis voluptas qui iste, voluptatem atque ab rerum illum quia
            incidunt odio?

          Lorem, ipsum.

Lorem, ipsum.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae
            vitae aut fugit dicta repellendus dolorem, quam, accusamus hic nemo
            ullam quod porro atque error?

          Lorem, ipsum.

CSS:

.sub-offer {
  text-align: center;
  display: flex;
  position: relative;

  .offer-container {
    background: linear-gradient(to bottom right, #2e2e3b, #0f1519);
  }

  h2 {
    font-family: 'Playfair Display', serif;
    font-size: 15px;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    margin-top: 4.3em;
    width: 33%;
    text-align: center;
  }

  p {
    font-size: 12px;
    margin-top: 2em;
    padding: 0 0.5em 0 0.5em;
    font-family: 'Montserrat', sans-serif;
  }

  a {
    display: inline-block;
    font-family: 'Montserrat', sans-serif;
    font-size: 12px;
    background: white;
    margin: 3em 0 2.5em 0;
    padding: 0.5em;
    text-decoration: none;
    color: black;

    &:hover {
      background: #e5e5e5;
    }
  }
}

How they look now:

Body:
I solved my issue. To give all three columns the same width I've used what @tacoshy recommended in the comments: section.sub-offer { display: flex; } .offer-container { width: calc(100% / 3); }

To align all three buttons though leaving all them responsive I've wrapped my button into a div and used the following css:

.more-btn {
    display: flex;
    align-self: center;
    margin-top: auto;
  }


问:
Axios - Request header content-type was not present in the Access-Control-Allow-Headers list - ElasticSearch
I'm new to a lot of this technology, but I think I've diagnosed my issue and need some help. I've seen numerous posts on SO regarding this issue, but none have worked, though they have helped me diagnose issue.

I believe the issue is when I send the Header Content-Type w/ my pre-flight w/ Axios, it fails. This is possibly due to lower/case upper case? The error has lower case, but I tried both on the server without luck.

Basically, if I don't specify any header and Axios uses json as content-type, it works, but as soon as I specify Content-Type my pre-flight fails (even though I think post would work..).

Here is the elasticsearch.yml

cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.cors.enabled : true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS,HEAD,GET,POST,PUT,DELETE
http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length
#http.cors.allow-credentials: true
```
<p>Here is my JS that I'm testing BTW w/ an Office Add-In solution in Visual Studio 2017 which I think is using IE as a browser.</p>
<p>Main Func:</p>
<pre class="lang-js prettyprint-override"><code>var URL = "https://elasticsearch:9200/users/_search"
const data = {
    "query": {
        "match": {
            "name": "freesoftwareservers"
        }
    }
};
Do_Axios('get', URL, data, null, false)
Do_Axios('post', URL, data, null, false)
</code>```

Do_Axios:

async function Do_Axios(method, URL, data, headers, withCredentials) {
    return axios({
        method: method,
        url: URL,
        withCredentials: withCredentials,
        //contentType: 'application/json', // does nothing
        //data: JSON.stringify(data), //Causes urlformencoded which is wrong
        data: data, //caues type to be json and I get error
        headers: {
            //"Content-Type": "application/json"
        },
    })
        .then(function (response) {
            console.log("Axios " + method + " response:");
            console.log(response)
            return response;
        })
        .catch(function (error) {
            console.log(error);
        });
}
```

Note: I can get/post if I comment out //data but then the post doesn't run my query. If I uncomment data then Axios uses urlformencoded but that doesn't work.

For now, I've been able to search API via urlformencoded queries, but I'd like to fix my ability to POST correctly to resolve future errors. I'm unsure if issue should be pointed to Axios or Elasticsearch if I open a request.

答:
Well, I finally figured it out. I wonder how many of the other posts I read have similar issues... anyway, the issue was w/ my NGinX proxy server. No better way to learn about CORS then to setup an API and make CORS requests via IE! Without the below, I was still able to post w/ POSTMAN to the same URL which hit my nginx server, but the call from Axios/IE/JS Evironment failed.

I found these snippets and this was the magic that needed added to my "regular" configuration:

```<code>proxy_pass_header Access-Control-Allow-Origin;
proxy_pass_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
add_header Access-Control-Allow-Headers 'X-Requested-With, Content-Type';
add_header Access-Control-Allow-Credentials true;
</code>```

https://gist.github.com/sahilsk/b16cb51387847e6c3329

Here is my code as it stands, cleaned up but generic atm:

Note: I pass axios because I can't figure out how to get my Webpack to transform/polyfill my funcs in seperate js files. But I can declare axios in the main func and pass it and then I can move my funcs into separate files as needed for organization. There is likely a better way to do without passing axios and configuring webpack

Main Func:

```<code>var username = "freesoftwareservers"
var ipv4 = "192.168.1.255"
var showhelp = "false"
await Do_AddUserToES(axios,username, ipv4, showhelp)
Get_UserFromES(axios,username)
var index = "users"
var query = {
    query: {
        match: {
          "username": username
        }
    }
};
Get_PostQueryToES(axios,query, index)
</code>```

Funcs:

```<code>function Do_Axios(axios, method, URL, data, headers, withCredentials) {
    return axios({
        method: method,
        url: URL,
        withCredentials: withCredentials,
        data: data,
        headers: headers,
    })
        .then(function (response) {
            console.log("Axios " + method + " response:");
            console.log(response)
            return response;
        })
        .catch(function (error) {
            console.log(error);
        });
}
</code>```

```<code>function Get_ESURL(Bool_Search, Bool_Doc, Bool_Update, Opt_Index, Opt_IndexKey) {
    var ESUrl = "https://elasticsearch:9200"
    var ESSearch = "/_search"
    var ESDoc = "/_doc"
    var ESUpdate = "/_update"
    var ReturnURL = ESUrl
    if (Opt_Index != undefined) { ReturnURL = ReturnURL + "/" + Opt_Index }
    if (Bool_Search == true) { ReturnURL = ReturnURL + ESSearch }
    if (Bool_Doc == true) { ReturnURL = ReturnURL + ESDoc }
    if (Bool_Update == true) { ReturnURL = ReturnURL + ESUpdate }
    if (Opt_IndexKey != undefined) { ReturnURL = ReturnURL + "/" + Opt_IndexKey }
    console.log("ReturnURL:" + ReturnURL)
    return ReturnURL;
}
</code>```

```<code>function Do_AddUserToES(axios, username, ipv4, showhelp) {
    var adduser = {
        "username": username,
        "ipv4": ipv4,
        "showhelp": showhelp
    };
    var URL = Get_ESURL(false, true, false, "users", username)
    return Do_Axios(axios, 'post', URL, adduser, null, false);
}
</code>```

```<code>function Get_UserFromES(axios, username) {
    var URL = Get_ESURL(false, true, false, "users", username)
    return Do_Axios(axios, 'get', URL, null, null, false);
}
</code>```

```<code>function Get_PostQueryToES(axios, query, index) {
    var URL = Get_ESURL(true, false, false, index)
    return Do_Axios(axios, 'post', URL, query, null, false);
}
</code>```

Body:
I'm new to a lot of this technology, but I think I've diagnosed my issue and need some help. I've seen numerous posts on SO regarding this issue, but none have worked, though they have helped me diagnose issue.

I believe the issue is when I send the Header Content-Type w/ my pre-flight w/ Axios, it fails. This is possibly due to lower/case upper case? The error has lower case, but I tried both on the server without luck.

Basically, if I don't specify any header and Axios uses json as content-type, it works, but as soon as I specify Content-Type my pre-flight fails (even though I think post would work..).

Here is the elasticsearch.yml

cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.cors.enabled : true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS,HEAD,GET,POST,PUT,DELETE
http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length
#http.cors.allow-credentials: true

Here is my JS that I'm testing BTW w/ an Office Add-In solution in Visual Studio 2017 which I think is using IE as a browser.

Main Func:

var URL = "https://elasticsearch:9200/users/_search"
const data = {
    "query": {
        "match": {
            "name": "freesoftwareservers"
        }
    }
};
Do_Axios('get', URL, data, null, false)
Do_Axios('post', URL, data, null, false)

Do_Axios:

async function Do_Axios(method, URL, data, headers, withCredentials) {
    return axios({
        method: method,
        url: URL,
        withCredentials: withCredentials,
        //contentType: 'application/json', // does nothing
        //data: JSON.stringify(data), //Causes urlformencoded which is wrong
        data: data, //caues type to be json and I get error
        headers: {
            //"Content-Type": "application/json"
        },
    })
        .then(function (response) {
            console.log("Axios " + method + " response:");
            console.log(response)
            return response;
        })
        .catch(function (error) {
            console.log(error);
        });
}

Note: I can get/post if I comment out //data but then the post doesn't run my query. If I uncomment data then Axios uses urlformencoded but that doesn't work.

For now, I've been able to search API via urlformencoded queries, but I'd like to fix my ability to POST correctly to resolve future errors. I'm unsure if issue should be pointed to Axios or Elasticsearch if I open a request.

Body:
Well, I finally figured it out. I wonder how many of the other posts I read have similar issues... anyway, the issue was w/ my NGinX proxy server. No better way to learn about CORS then to setup an API and make CORS requests via IE! Without the below, I was still able to post w/ POSTMAN to the same URL which hit my nginx server, but the call from Axios/IE/JS Evironment failed.

I found these snippets and this was the magic that needed added to my "regular" configuration:

proxy_pass_header Access-Control-Allow-Origin;
proxy_pass_header Access-Control-Allow-Methods;
proxy_hide_header Access-Control-Allow-Headers;
add_header Access-Control-Allow-Headers 'X-Requested-With, Content-Type';
add_header Access-Control-Allow-Credentials true;

https://gist.github.com/sahilsk/b16cb51387847e6c3329

Here is my code as it stands, cleaned up but generic atm:

Note: I pass axios because I can't figure out how to get my Webpack to transform/polyfill my funcs in seperate js files. But I can declare axios in the main func and pass it and then I can move my funcs into separate files as needed for organization. There is likely a better way to do without passing axios and configuring webpack

Main Func:

var username = "freesoftwareservers"
var ipv4 = "192.168.1.255"
var showhelp = "false"
await Do_AddUserToES(axios,username, ipv4, showhelp)
Get_UserFromES(axios,username)
var index = "users"
var query = {
    query: {
        match: {
          "username": username
        }
    }
};
Get_PostQueryToES(axios,query, index)

Funcs:

function Do_Axios(axios, method, URL, data, headers, withCredentials) {
    return axios({
        method: method,
        url: URL,
        withCredentials: withCredentials,
        data: data,
        headers: headers,
    })
        .then(function (response) {
            console.log("Axios " + method + " response:");
            console.log(response)
            return response;
        })
        .catch(function (error) {
            console.log(error);
        });
}

function Get_ESURL(Bool_Search, Bool_Doc, Bool_Update, Opt_Index, Opt_IndexKey) {
    var ESUrl = "https://elasticsearch:9200"
    var ESSearch = "/_search"
    var ESDoc = "/_doc"
    var ESUpdate = "/_update"
    var ReturnURL = ESUrl
    if (Opt_Index != undefined) { ReturnURL = ReturnURL + "/" + Opt_Index }
    if (Bool_Search == true) { ReturnURL = ReturnURL + ESSearch }
    if (Bool_Doc == true) { ReturnURL = ReturnURL + ESDoc }
    if (Bool_Update == true) { ReturnURL = ReturnURL + ESUpdate }
    if (Opt_IndexKey != undefined) { ReturnURL = ReturnURL + "/" + Opt_IndexKey }
    console.log("ReturnURL:" + ReturnURL)
    return ReturnURL;
}

function Do_AddUserToES(axios, username, ipv4, showhelp) {
    var adduser = {
        "username": username,
        "ipv4": ipv4,
        "showhelp": showhelp
    };
    var URL = Get_ESURL(false, true, false, "users", username)
    return Do_Axios(axios, 'post', URL, adduser, null, false);
}

function Get_UserFromES(axios, username) {
    var URL = Get_ESURL(false, true, false, "users", username)
    return Do_Axios(axios, 'get', URL, null, null, false);
}

function Get_PostQueryToES(axios, query, index) {
    var URL = Get_ESURL(true, false, false, index)
    return Do_Axios(axios, 'post', URL, query, null, false);
}


问:
C# How to make one class instance available to another class method
I have this:

```<code>Crew_Photos photos = new Crew_Photos(); // contains List<t> of photos
Bus_Crew buscrew = new Bus_Crew();      // Calls update.AddUpdate()
Cab_Crew cabcrew = new Cab_Crew();      // Also calls update.AddUpdate()
UpdateCrew update = new UpdateCrew();   // DEFINES method AddUpdate();
</code>```

I'm trying to avoid doing this:

```<code>Crew_Photos photos = new Crew_Photos();

Bus_Crew buscrew = new BusDriver_Crew(photos);
    busscrew.AddUpdate(photos);

Cab_Crew cabcrew = new Cab_Crew(photos);
    cabcrew.AddUpdate(photos);

UpdateCrew update = new UpdateCrew(photos);
</code>```

I do not want to pass photos to Bus_Crew, and Cab_Crew, only so that I can then pass it again to UpdateCrew() which is actually going to use it.

How can I make Crew_Photos photos available to update.AddUpdate() when it is called by buscrew.AddUpdate() and cabcrew.AddUpdate()?

答:
How about a constructor for UpdateCrew that receives the three things?

```<code>UpdateCrew update = new UpdateCrew(new Crew_Photos(), new BusDriver_Crew(), new Cab_Crew());
</code>```

Then the constructor can call AddUpdate() internally?

It's not clear what is happening within the different classes, so answering this question is very difficult.

Body:
I have this:

Crew_Photos photos = new Crew_Photos(); // contains List<t> of photos
Bus_Crew buscrew = new Bus_Crew();      // Calls update.AddUpdate()
Cab_Crew cabcrew = new Cab_Crew();      // Also calls update.AddUpdate()
UpdateCrew update = new UpdateCrew();   // DEFINES method AddUpdate();

I'm trying to avoid doing this:

Crew_Photos photos = new Crew_Photos();

Bus_Crew buscrew = new BusDriver_Crew(photos);
    busscrew.AddUpdate(photos);

Cab_Crew cabcrew = new Cab_Crew(photos);
    cabcrew.AddUpdate(photos);

UpdateCrew update = new UpdateCrew(photos);

I do not want to pass photos to Bus_Crew, and Cab_Crew, only so that I can then pass it again to UpdateCrew() which is actually going to use it.

How can I make Crew_Photos photos available to update.AddUpdate() when it is called by buscrew.AddUpdate() and cabcrew.AddUpdate()?

Body:
How about a constructor for UpdateCrew that receives the three things?

UpdateCrew update = new UpdateCrew(new Crew_Photos(), new BusDriver_Crew(), new Cab_Crew());

Then the constructor can call AddUpdate() internally?

It's not clear what is happening within the different classes, so answering this question is very difficult.


问:
How do I convert SmartyStreets' jQuery.LiveAddress plugin to its JavaScript SDK?
I have a website where the jQuery.LiveAddress plugin is implemented, but it was deprecated and then totally removed by SmartyStreets in 2014.

https://www.smartystreets.com/archive/jquery-plugin/website/configure

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//d79i1fxsrar4t.cloudfront.net/jquery.liveaddress/5.2/jquery.liveaddress.min.js"></script>
<script>var liveaddress = $.LiveAddress({
    key: "YOUR_WEBSITE_KEY_HERE",
    debug: true,
    target: "US|INTERNATIONAL",
    addresses: [{
        address1: '#street-address',
        locality: '#city',
        administrative_area: '#state',
        postal_code: '#zip',
        country: '#country'
    }]
});
</script>
</code>```

There is now a JavaScript SDK: https://www.smartystreets.com/docs/sdk/javascript

```<code>const SmartyStreetsSDK = require("smartystreets-javascript-sdk");
const SmartyStreetsCore = SmartyStreetsSDK.core;
const Lookup = SmartyStreetsSDK.usStreet.Lookup;

// for Server-to-server requests, use this code:
// let authId = process.env.SMARTY_AUTH_ID;
// let authToken = process.env.SMARTY_AUTH_TOKEN;
// const credentials = new SmartyStreetsCore.StaticCredentials(authId, authToken);

// for client-side requests (browser/mobile), use this code:
let key = process.env.SMARTY_WEBSITE_KEY;
const credentials = new SmartyStreetsCore.SharedCredentials(key);
</code>```

It says "for client-side requests (browser/mobile), use this code", but am I correct in assuming that it is not possible to get this code working as browser JavaScript? Wouldn't I need to be running node as a service on my server to be using this code?

答:
I came across this same issue and unfortunately smarty streets decided to make it more difficult for users to implement their product.

Upon my search I came across this fiddle, it doesn't have all of the features the jquery plugin did but it is a good place to start that doesn't require building your own suggestion UI.

```

jsfiddle source

Body:
I have a website where the jQuery.LiveAddress plugin is implemented, but it was deprecated and then totally removed by SmartyStreets in 2014.

https://www.smartystreets.com/archive/jquery-plugin/website/configure

There is now a JavaScript SDK: https://www.smartystreets.com/docs/sdk/javascript

const SmartyStreetsSDK = require("smartystreets-javascript-sdk");
const SmartyStreetsCore = SmartyStreetsSDK.core;
const Lookup = SmartyStreetsSDK.usStreet.Lookup;

// for Server-to-server requests, use this code:
// let authId = process.env.SMARTY_AUTH_ID;
// let authToken = process.env.SMARTY_AUTH_TOKEN;
// const credentials = new SmartyStreetsCore.StaticCredentials(authId, authToken);

// for client-side requests (browser/mobile), use this code:
let key = process.env.SMARTY_WEBSITE_KEY;
const credentials = new SmartyStreetsCore.SharedCredentials(key);

It says "for client-side requests (browser/mobile), use this code", but am I correct in assuming that it is not possible to get this code working as browser JavaScript? Wouldn't I need to be running node as a service on my server to be using this code?

Body:
I came across this same issue and unfortunately smarty streets decided to make it more difficult for users to implement their product.

Upon my search I came across this fiddle, it doesn't have all of the features the jquery plugin did but it is a good place to start that doesn't require building your own suggestion UI.

<script async src="//jsfiddle.net/smartystreets/uptgh7c8/embed/"></script>

jsfiddle source


问:
Passing a result array into pthread_join
I have the below code but I'm not understanding why the results aren't printing out correctly. I'm allocating val to be the size of the number of results I want to acquire. I pass the address of the location in val that I want to save the results to.</p>
```<code>#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

void* roll_dice() {
    int value = (rand() % 6) + 1;
    int* result = malloc(sizeof(int));
    *result = value;
    // printf("%d\n", value);
    printf("Thread result: %p\n", result);
    return (void*) result;
}

int main(int argc, char* argv[]) {
    int NUM_DICE = 4;
    srand(time(NULL));

    pthread_t th[NUM_DICE];

    for (int i  = 0; i < NUM_DICE; i++) {
        if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
            perror("failure");
        }
    }

    int* val = calloc(NUM_DICE, sizeof(int));
    for (int i = 0; i < NUM_DICE; i++) {
        pthread_join(th[i], &val);          // this doesn't work
//      pthread_join(th[i], &(val+i));      // this doesn't work
        printf("%d\n", *val);
    }

    for (int i = 0; i < NUM_DICE; i++) {
        printf("Dice %d rolled %d\n", i+1, *(val+i));
    }

    return 0;
}
</code>```

答:
malloc returns void* if success, you need cast it to int*.

the third parameter of pthread_create is void(*)(void*), not void(*)(),
so the roll_dice() need a void* argument.

we can use an array to store the threads return values.

after all, we need to free the memory we used malloc allocted.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

void* roll_dice(void*) {
    int value = (rand() % 6) + 1;
    int* result = (int*)malloc(sizeof(int));
    *result = value;
    // printf("%d\n", value);
    printf("Thread result: %p\n", result);
    return (void*) result;
}

int main(int argc, char* argv[]) {
    int NUM_DICE = 4;
    srand(time(NULL));

    pthread_t th[NUM_DICE];

    for (int i  = 0; i < NUM_DICE; i++) {
        if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
            perror("failure");
        }
    }

    int* val[NUM_DICE];
    for (int i = 0; i < NUM_DICE; i++) {
        pthread_join(th[i], (void**)&val[i]);          // this doesn't work
//      pthread_join(th[i], &(val+i));      // this doesn't work
        printf("%d\n", *val[i]);
    }

    for (int i = 0; i < NUM_DICE; i++) {
        printf("Dice %d rolled %d\n", i+1, *(val[i]));
    }

    for (int i = 0; i < NUM_DICE; i++) {
        free(val[i]);
    }

    return 0;
}
</code>```

Body:
I have the below code but I'm not understanding why the results aren't printing out correctly. I'm allocating val to be the size of the number of results I want to acquire. I pass the address of the location in val that I want to save the results to.

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

void* roll_dice() {
    int value = (rand() % 6) + 1;
    int* result = malloc(sizeof(int));
    *result = value;
    // printf("%d\n", value);
    printf("Thread result: %p\n", result);
    return (void*) result;
}

int main(int argc, char* argv[]) {
    int NUM_DICE = 4;
    srand(time(NULL));

    pthread_t th[NUM_DICE];

    for (int i  = 0; i < NUM_DICE; i++) {
        if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
            perror("failure");
        }
    }

    int* val = calloc(NUM_DICE, sizeof(int));
    for (int i = 0; i < NUM_DICE; i++) {
        pthread_join(th[i], &val);          // this doesn't work
//      pthread_join(th[i], &(val+i));      // this doesn't work
        printf("%d\n", *val);
    }

    for (int i = 0; i < NUM_DICE; i++) {
        printf("Dice %d rolled %d\n", i+1, *(val+i));
    }

    return 0;
}

Body:
malloc returns void* if success, you need cast it to int*.

the third parameter of pthread_create is void(*)(void*), not void(*)(),
so the roll_dice() need a void* argument.

we can use an array to store the threads return values.

after all, we need to free the memory we used malloc allocted.

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

void* roll_dice(void*) {
    int value = (rand() % 6) + 1;
    int* result = (int*)malloc(sizeof(int));
    *result = value;
    // printf("%d\n", value);
    printf("Thread result: %p\n", result);
    return (void*) result;
}

int main(int argc, char* argv[]) {
    int NUM_DICE = 4;
    srand(time(NULL));

    pthread_t th[NUM_DICE];

    for (int i  = 0; i < NUM_DICE; i++) {
        if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
            perror("failure");
        }
    }

    int* val[NUM_DICE];
    for (int i = 0; i < NUM_DICE; i++) {
        pthread_join(th[i], (void**)&val[i]);          // this doesn't work
//      pthread_join(th[i], &(val+i));      // this doesn't work
        printf("%d\n", *val[i]);
    }

    for (int i = 0; i < NUM_DICE; i++) {
        printf("Dice %d rolled %d\n", i+1, *(val[i]));
    }

    for (int i = 0; i < NUM_DICE; i++) {
        free(val[i]);
    }

    return 0;
}


问:
Vertical viewport was given unbounded height
This is my code:

@override
Widget build(BuildContext context) {
  return new Material(
    color: Colors.deepPurpleAccent,
    child: new Column(
     mainAxisAlignment: MainAxisAlignment.center,
        children:<Widget>[new GridView.count(crossAxisCount: _column,children: new List.generate(_row*_column, (index) {
          return new Center(
              child: new CellWidget()
          );
        }),)]
    )
  );
}
```
<p>Exception as follows:</p>
```I/flutter ( 9925): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 9925): The following assertion was thrown during performResize():
I/flutter ( 9925): Vertical viewport was given unbounded height.
I/flutter ( 9925): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 9925): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 9925): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 9925): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 9925): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 9925): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 9925): the height of the viewport to the sum of the heights of its children.
I/flutter ( 9925):
I/flutter ( 9925): When the exception was thrown, this was the stack:
I/flutter ( 9925): #0      RenderViewport.performResize.<anonymous closure> (package:flutter/src/rendering/viewport.dart:827:15)
I/flutter ( 9925): #1      RenderViewport.performResize (package:flutter/src/rendering/viewport.dart:880:6)
I/flutter ( 9925): #2      RenderObject.layout (package:flutter/src/rendering/object.dart:1555:9)
```

答:
I have made a custom function to solve your problem.
You can directly use this function in your code base:

```<code>Widget horizontalListView(height, width, color, child, margin) {
return Column(
  children: [
    SizedBox(
      height: 200,
      child: ListView.builder(
        itemCount: 10,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context,index) {
          return Container(
            height: height,
            width: width,
            margin: EdgeInsets.all(margin),
            color: color,
            child: child
          );
        }
      ),
    ),
  ],
 );
})
</code>```

P.S. Sorry for bad alignment of code.

Body:
This is my code:

@override
Widget build(BuildContext context) {
  return new Material(
    color: Colors.deepPurpleAccent,
    child: new Column(
     mainAxisAlignment: MainAxisAlignment.center,
        children:<Widget>[new GridView.count(crossAxisCount: _column,children: new List.generate(_row*_column, (index) {
          return new Center(
              child: new CellWidget()
          );
        }),)]
    )
  );
}

Exception as follows:

I/flutter ( 9925): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 9925): The following assertion was thrown during performResize():
I/flutter ( 9925): Vertical viewport was given unbounded height.
I/flutter ( 9925): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 9925): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 9925): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 9925): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 9925): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 9925): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 9925): the height of the viewport to the sum of the heights of its children.
I/flutter ( 9925):
I/flutter ( 9925): When the exception was thrown, this was the stack:
I/flutter ( 9925): #0      RenderViewport.performResize.<anonymous closure> (package:flutter/src/rendering/viewport.dart:827:15)
I/flutter ( 9925): #1      RenderViewport.performResize (package:flutter/src/rendering/viewport.dart:880:6)
I/flutter ( 9925): #2      RenderObject.layout (package:flutter/src/rendering/object.dart:1555:9)

Body:
I have made a custom function to solve your problem.
You can directly use this function in your code base:

Widget horizontalListView(height, width, color, child, margin) {
return Column(
  children: [
    SizedBox(
      height: 200,
      child: ListView.builder(
        itemCount: 10,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context,index) {
          return Container(
            height: height,
            width: width,
            margin: EdgeInsets.all(margin),
            color: color,
            child: child
          );
        }
      ),
    ),
  ],
 );
})

P.S. Sorry for bad alignment of code.


问:
R programming, Ifelse Error: "Error in ifelse(i %in% c(1, 6), rasterImage(ringIMG2, -22, -22, 22, 22, : replacement has length zero: "
I am trying to run different versions of the same command in a for loop based on the value of i.

If i equals 1 or 6 run this:
rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)

If i equals 2, 3 or 5 run this:
rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)

If i equals 4 run this:
rasterImage(ringIMG2, -23.5, -23.5, 23.5, 23.5, interpolate=FALSE, angle =0)

I am using a nested ifelse statement.

```<code>  for (i in 1:6)
  {
    #adjusts size of image within the plot
    ifelse(i %in% c(1,6), rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0),
           ifelse(i %in% c(2,3,5), rasterImage(ringIMG2, -23, -23, 23, 23, interpolate=FALSE, angle =0),
                  rasterImage(ringIMG2, -23.5, -23.5, 23.5, 23.5, interpolate=FALSE, angle =0)
           )
    )
    }
</code>```

I keep getting the following error:

```<code>Error in ifelse(i %in% c(1, 6), rasterImage(ringIMG2, -22, -22, 22, 22,  :
  replacement has length zero
In addition: Warning messages:
1: In readPNG(paste0("R", i, ".png")) :
  libpng warning: iCCP: known incorrect sRGB profile
2: In rep(yes, length.out = length(ans)) :
  'x' is NULL so the result will be NULL
</code>```

The code on its own is running fine:

```<code>rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)
</code>```

Well I'm still getting the first warning but that is not any real concern.

I have tried the simplifying and it seems to work...

```<code>check <- ifelse(i %in% c(1,6), print('Yes'))
[1] "Yes"
</code>```

My syntax looks ok based on the link below:

Nested ifelse syntax

```<code>ifelse(<condition>, <yes>,
              ifelse(<condition>, <yes>, <no>)
                    )
       )
</code>```

Anyone got an idea where I'm going wrong?

Thanks!

答:
You want to use if and else — not to be confused with ifelse().

ifelse() is useful when you want to create a vector of values based on a vector of conditions. It returns a vector the same length as the test condition, and expects all arguments to be the same length. But rasterImage() doesn’t have a return value — passing it as an argument to ifelse() is equivalent to passing NULL. length(i) != length(NULL), so you get an error.

But if and else are standard control flow statements, rather than functions with prescribed inputs and outputs, so will work better for your case:

```<code>for (i in 1:6) {
  if (i %in% c(1,6)) {
    rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)
  } else if (i %in% c(2,3,5)) {
    rasterImage(ringIMG2, -23, -23, 23, 23, interpolate=FALSE, angle =0)
  } else {
    rasterImage(ringIMG2, -23.5, -23.5, 23.5, 23.5, interpolate=FALSE, angle =0)
  }
}
</code>```

You could also accomplish this a bit more concisely without if statements:

```<code>for (i in c(22, 23, 23, 23.5, 23, 22)) {
  rasterImage(ringIMG2, -i, -i, i, i, interpolate=FALSE, angle =0)
}
</code>```

Body:
I am trying to run different versions of the same command in a for loop based on the value of i.

If i equals 1 or 6 run this:
rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)

If i equals 2, 3 or 5 run this:
rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)

If i equals 4 run this:
rasterImage(ringIMG2, -23.5, -23.5, 23.5, 23.5, interpolate=FALSE, angle =0)

I am using a nested ifelse statement.

  for (i in 1:6)
  {
    #adjusts size of image within the plot
    ifelse(i %in% c(1,6), rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0),
           ifelse(i %in% c(2,3,5), rasterImage(ringIMG2, -23, -23, 23, 23, interpolate=FALSE, angle =0),
                  rasterImage(ringIMG2, -23.5, -23.5, 23.5, 23.5, interpolate=FALSE, angle =0)
           )
    )
    }

I keep getting the following error:

Error in ifelse(i %in% c(1, 6), rasterImage(ringIMG2, -22, -22, 22, 22,  :
  replacement has length zero
In addition: Warning messages:
1: In readPNG(paste0("R", i, ".png")) :
  libpng warning: iCCP: known incorrect sRGB profile
2: In rep(yes, length.out = length(ans)) :
  'x' is NULL so the result will be NULL

The code on its own is running fine:

rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)

Well I'm still getting the first warning but that is not any real concern.

I have tried the simplifying and it seems to work...

check <- ifelse(i %in% c(1,6), print('Yes'))
[1] "Yes"

My syntax looks ok based on the link below:

Nested ifelse syntax

ifelse(<condition>, <yes>,
              ifelse(<condition>, <yes>, <no>)
                    )
       )

Anyone got an idea where I'm going wrong?

Thanks!

Body:
You want to use if and else — not to be confused with ifelse().

ifelse() is useful when you want to create a vector of values based on a vector of conditions. It returns a vector the same length as the test condition, and expects all arguments to be the same length. But rasterImage() doesn’t have a return value — passing it as an argument to ifelse() is equivalent to passing NULL. length(i) != length(NULL), so you get an error.

But if and else are standard control flow statements, rather than functions with prescribed inputs and outputs, so will work better for your case:

for (i in 1:6) {
  if (i %in% c(1,6)) {
    rasterImage(ringIMG2, -22, -22, 22, 22, interpolate=FALSE, angle =0)
  } else if (i %in% c(2,3,5)) {
    rasterImage(ringIMG2, -23, -23, 23, 23, interpolate=FALSE, angle =0)
  } else {
    rasterImage(ringIMG2, -23.5, -23.5, 23.5, 23.5, interpolate=FALSE, angle =0)
  }
}

You could also accomplish this a bit more concisely without if statements:

for (i in c(22, 23, 23, 23.5, 23, 22)) {
  rasterImage(ringIMG2, -i, -i, i, i, interpolate=FALSE, angle =0)
}