问:
Remove value from array on click React.js
Im building an image slider that maps out and lists an array of image url's.

I'm trying to save an array of image urls that the user wants to hide from view.

My plan is to store the array value in a dynamoDB table, then retrieve the array of urls that do not want to be shown, and then filter them out from the mapped images in the slider.

I have an EyeOFF icon shown over the image they click, and that toggles the icon hide true and false with the onClick prop of the image and the icon. --- see const handleBottomImageClick().

My issue is that Im unable to remove the value of the image (img url) from the array thats saved in the state variable selectedImage. --- see const handleTopImageClick().

I tried array.pop(), and array.splice(), but I don't know if those methods would work efficiently for what i'm trying to do.

Slider Component

```<code>import React, { useState, useEffect, useRef } from "react";
import { IonModal, IonContent, IonButton, IonIcon, IonGrid, IonRow, IonCol, IonItem, IonLabel } from '@ionic/react';
import { chevronBackOutline, chevronForwardOutline } from 'ionicons/icons';
import { Storage } from "aws-amplify";
import Image from '../components/SliderImages.js';
import FullImage from '../components/LargeSliderImage.js';
import Slider from "react-slick";
import "slick-carousel/slick/slick.scss";
import { chunk } from 'lodash';
import Modal from 'react-modal';
import { eyeOffOutline, createSharp, shareSharp } from 'ionicons/icons';

const SliderComponent = (props) => {

    const { job, hideImages } = props;
    const [selectedImage, setSlectedImage] = useState([]);
    const [images, setImages] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [activeSlide, setActiveSlide] = useState(false);
    const [initialSlide, setInitialSlide] = useState(0)
    const [state, setState] = useState({
        nav1: null,
        nav2: null
    });
    const slider1 = useRef();
    const slider2 = useRef();

       let imagesToHide = [];

    const SlickArrowLeft = ({ ...props }) => (

        <IonIcon  {...props} type="button" size="large" icon={chevronBackOutline} />

    );

    const SlickArrowRight = ({ ...props }) => (
        <IonIcon {...props} type="button" size="large" icon={chevronForwardOutline} />
    );

    const customStyles = {
        content: {
            top: '50%',
            left: '50%',
            right: 'auto',
            bottom: 'auto',
            marginRight: '-50%',
            transform: 'translate(-50%, -50%)'
        }
    };

    useEffect(() => {
        setState({
            nav1: slider1.current,
            nav2: slider2.current
        });
    }, []);

    const {
        nav1,
        nav2
    } = state;

    const settings = {
        infinite: false,
        lazyLoad: "ondemand",
        useCSS: true,
        useTransform: true,
        slidesToShow: 5,
        slidesToScroll: 5,
        speed: 500,
        initialSlide: 0,
        autoHeight: false,
        draggable: true,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 4,
                    slidesToScroll: 4,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,
                }
            },
            {
                breakpoint: 600,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,

                }
            },
            {
                breakpoint: 480,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: true,
                    prevArrow: <SlickArrowLeft class="prevArrowButton" />,
                    nextArrow: <SlickArrowRight class="nextArrowButton" />,
                }
            }
        ]
    };

    const viewSettings = {
        infinite: true,
        lazyLoad: "ondemand",
        slidesToShow: 1,
        slidesToScroll: 1,
        speed: 500,
        autoHeight: false,
        focusOnSelect: false,
        initialSlide: initialSlide,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

    }

    useEffect(() => {
        async function onLoad() {

            try {
                const downloadedImage = await getImage(job);
                setImages(downloadedImage);
            } catch (e) {
                alert(e);
            }
        }

        onLoad();
    }, [job]);

    async function getImage(jobID) {
        const imageURL = await Storage.list(`${jobID}/completed/`);
        let imagesToDownload = imageURL
        let imagesAsArray = [];
        for (let i = 0; i < imagesToDownload.length; i++) {
            const imagesDownloaded = await getURLFromS3(imagesToDownload[i]);
            imagesAsArray.push(imagesDownloaded)
        }
        return imagesAsArray
    }

    async function getURLFromS3(fileToDownload) {
        const result = await Storage.get(fileToDownload.key)
        return result;
    }

    const handleBottomImageClick = function (index, image2) {
        if (hideImages) {
            if (selectedImage[image2]) {
                setSlectedImage({ ...selectedImage, [image2]: false })
            } else {
                setSlectedImage({ ...selectedImage, [image2]: !selectedImage[image2] })
            }

        } else {

            setShowModal(true)
            const i = index + index + 1
            setInitialSlide(i)

        }

    }

    const handleTopImageClick = function (index, image1) {
        if (hideImages) {
            if (selectedImage[image1]) {
                const arr = [selectedImage]
                arr.splice(selectedImage[image1])
                setSlectedImage(arr)
            } else {
                setSlectedImage({ ...selectedImage, [image1]: !selectedImage[image1]})
            }
        } else {
            setShowModal(true)
            const i = index + index
            setInitialSlide(i)
        }
    }

    return (
        <>
            {hideImages ? (

                <div className="ion-padding" style={{ textAlign: "center" }}>
                    <IonLabel position="stacked"> Select the images you want to hide from the customer view. Tap finished when done. </IonLabel>
                    <br /><br />
                    <div style={{ justifyContent: 'center', display: "flex" }}>
                        <IonButton onClick={() => console.log(selectedImage)} size="small">
                            Finished
                    </IonButton>
                    </div>
                    <br />
                </div>

            ) : (
                    null
                )}
            <div style={{ justifyContent: 'center', display: "flex" }}>

                <Slider className="image-slider-frame" asNavFor={nav1} ref={slider => (slider1.current = slider)} {...settings}>
                    {chunk(images, 2).map(([image1, image2], i) =>

                        <ul className="listing-image-slidee" key={i}>

                            <div>
                                <li className="listing-image-pairs">
                                    <img onClick={() => {handleTopImageClick(i, image1);} } height="206px" width="272px" className="img" src={image1} />
                                    <IonIcon onClick={() => handleTopImageClick(i, image1)} className="image-hide" key={image1} size="large" hidden={selectedImage[image1] ? false : true} icon={eyeOffOutline} />
                                </li>
                            </div>

                            <div >
                                {image2 && <li className="listing-image-pairs">
                                    <img onClick={() => handleBottomImageClick(i, image2)} height="206px" width="272px" className="img" src={image2} />
                                    <IonIcon className="image-hide" key={image2} size="large" onClick={() => handleBottomImageClick(i, image2)} hidden={selectedImage[image2] ? false : true} icon={eyeOffOutline} />
                                </li>}
                            </div>

                        </ul>

                    )}
                </Slider>

            </div>
            <div>

                <Modal ariaHideApp={false} className="Modal" isOpen={showModal}>
                    <IonGrid>
                        <IonRow clasName="ion-no-padding" style={{ justifyContent: 'center' }} >
                            <IonCol sizeXs="13" sizeSm="13" sizeMd="9" sizeLg="7" sizeXl="7" >
                                <Slider style={{ maxHeight: "768px" }} asNavFor={nav2} ref={slider => (slider2.current = slider)}  {...viewSettings}>
                                    {(images).map((image, i) =>
                                        <div>
                                            <br />
                                            <img src={image} />
                                        </div>

                                    )}
                                </Slider>
                                <br/>
                                <IonItem lines="none">
                                    <IonButton size="small" color="secondary" slot="end" onClick={() => setShowModal(false)}>close</IonButton>
                                </IonItem>
                            </IonCol>
                        </IonRow>
                    </IonGrid>
                </Modal>

            </div>
        </>
    )
}
export default SliderComponent;
</code>```

答:
First of all you must initialize selectedImage with object and not an array as that is what you expect it to be later

Second, assuming its an object, you won't use splice on it. You would either delete the key or make it false.

In any case you must make sure you are cloning the object before updating in state

```<code>const [selectedImage, setSlectedImage] = useState({}); // Initialize object
...
const handleTopImageClick = function (index, image1) {
    if (hideImages) {
        if (selectedImage[image1]) {
            setSlectedImage({...selectedImage, [image1]: false}); // hide image
        } else {
            setSlectedImage({ ...selectedImage, [image1]: true}); // show
        }
    } else {
        setShowModal(true)
        const i = index + index
        setInitialSlide(i)
    }
}
</code>```

Body:
Im building an image slider that maps out and lists an array of image url's.

I'm trying to save an array of image urls that the user wants to hide from view.

My plan is to store the array value in a dynamoDB table, then retrieve the array of urls that do not want to be shown, and then filter them out from the mapped images in the slider.

I have an EyeOFF icon shown over the image they click, and that toggles the icon hide true and false with the onClick prop of the image and the icon. --- see const handleBottomImageClick().

My issue is that Im unable to remove the value of the image (img url) from the array thats saved in the state variable selectedImage. --- see const handleTopImageClick().

I tried array.pop(), and array.splice(), but I don't know if those methods would work efficiently for what i'm trying to do.

Slider Component

import React, { useState, useEffect, useRef } from "react";
import { IonModal, IonContent, IonButton, IonIcon, IonGrid, IonRow, IonCol, IonItem, IonLabel } from '@ionic/react';
import { chevronBackOutline, chevronForwardOutline } from 'ionicons/icons';
import { Storage } from "aws-amplify";
import Image from '../components/SliderImages.js';
import FullImage from '../components/LargeSliderImage.js';
import Slider from "react-slick";
import "slick-carousel/slick/slick.scss";
import { chunk } from 'lodash';
import Modal from 'react-modal';
import { eyeOffOutline, createSharp, shareSharp } from 'ionicons/icons';

const SliderComponent = (props) => {

    const { job, hideImages } = props;
    const [selectedImage, setSlectedImage] = useState([]);
    const [images, setImages] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [activeSlide, setActiveSlide] = useState(false);
    const [initialSlide, setInitialSlide] = useState(0)
    const [state, setState] = useState({
        nav1: null,
        nav2: null
    });
    const slider1 = useRef();
    const slider2 = useRef();

       let imagesToHide = [];

    const SlickArrowLeft = ({ ...props }) => (

        <IonIcon  {...props} type="button" size="large" icon={chevronBackOutline} />

    );

    const SlickArrowRight = ({ ...props }) => (
        <IonIcon {...props} type="button" size="large" icon={chevronForwardOutline} />
    );

    const customStyles = {
        content: {
            top: '50%',
            left: '50%',
            right: 'auto',
            bottom: 'auto',
            marginRight: '-50%',
            transform: 'translate(-50%, -50%)'
        }
    };

    useEffect(() => {
        setState({
            nav1: slider1.current,
            nav2: slider2.current
        });
    }, []);

    const {
        nav1,
        nav2
    } = state;

    const settings = {
        infinite: false,
        lazyLoad: "ondemand",
        useCSS: true,
        useTransform: true,
        slidesToShow: 5,
        slidesToScroll: 5,
        speed: 500,
        initialSlide: 0,
        autoHeight: false,
        draggable: true,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 4,
                    slidesToScroll: 4,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,
                }
            },
            {
                breakpoint: 600,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,

                }
            },
            {
                breakpoint: 480,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: true,
                    prevArrow: <SlickArrowLeft class="prevArrowButton" />,
                    nextArrow: <SlickArrowRight class="nextArrowButton" />,
                }
            }
        ]
    };

    const viewSettings = {
        infinite: true,
        lazyLoad: "ondemand",
        slidesToShow: 1,
        slidesToScroll: 1,
        speed: 500,
        autoHeight: false,
        focusOnSelect: false,
        initialSlide: initialSlide,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

    }

    useEffect(() => {
        async function onLoad() {

            try {
                const downloadedImage = await getImage(job);
                setImages(downloadedImage);
            } catch (e) {
                alert(e);
            }
        }

        onLoad();
    }, [job]);

    async function getImage(jobID) {
        const imageURL = await Storage.list(`${jobID}/completed/`);
        let imagesToDownload = imageURL
        let imagesAsArray = [];
        for (let i = 0; i < imagesToDownload.length; i++) {
            const imagesDownloaded = await getURLFromS3(imagesToDownload[i]);
            imagesAsArray.push(imagesDownloaded)
        }
        return imagesAsArray
    }

    async function getURLFromS3(fileToDownload) {
        const result = await Storage.get(fileToDownload.key)
        return result;
    }

    const handleBottomImageClick = function (index, image2) {
        if (hideImages) {
            if (selectedImage[image2]) {
                setSlectedImage({ ...selectedImage, [image2]: false })
            } else {
                setSlectedImage({ ...selectedImage, [image2]: !selectedImage[image2] })
            }

        } else {

            setShowModal(true)
            const i = index + index + 1
            setInitialSlide(i)

        }

    }

    const handleTopImageClick = function (index, image1) {
        if (hideImages) {
            if (selectedImage[image1]) {
                const arr = [selectedImage]
                arr.splice(selectedImage[image1])
                setSlectedImage(arr)
            } else {
                setSlectedImage({ ...selectedImage, [image1]: !selectedImage[image1]})
            }
        } else {
            setShowModal(true)
            const i = index + index
            setInitialSlide(i)
        }
    }

    return (
        <>
            {hideImages ? (

                    <IonLabel position="stacked"> Select the images you want to hide from the customer view. Tap finished when done. </IonLabel>

                        <IonButton onClick={() => console.log(selectedImage)} size="small">
                            Finished
                    </IonButton>

            ) : (
                    null
                )}

                <Slider className="image-slider-frame" asNavFor={nav1} ref={slider => (slider1.current = slider)} {...settings}>
                    {chunk(images, 2).map(([image1, image2], i) =>

                                     {handleTopImageClick(i, image1);} } height="206px" width="272px" className="img" src={image1} />
                                    <IonIcon onClick={() => handleTopImageClick(i, image1)} className="image-hide" key={image1} size="large" hidden={selectedImage[image1] ? false : true} icon={eyeOffOutline} />

                                {image2 &&

                                     handleBottomImageClick(i, image2)} height="206px" width="272px" className="img" src={image2} />
                                    <IonIcon className="image-hide" key={image2} size="large" onClick={() => handleBottomImageClick(i, image2)} hidden={selectedImage[image2] ? false : true} icon={eyeOffOutline} />

}

                    )}
                </Slider>

                <Modal ariaHideApp={false} className="Modal" isOpen={showModal}>
                    <IonGrid>
                        <IonRow clasName="ion-no-padding" style={{ justifyContent: 'center' }} >
                            <IonCol sizeXs="13" sizeSm="13" sizeMd="9" sizeLg="7" sizeXl="7" >
                                <Slider style={{ maxHeight: "768px" }} asNavFor={nav2} ref={slider => (slider2.current = slider)}  {...viewSettings}>
                                    {(images).map((image, i) =>

                                    )}
                                </Slider>

                                <IonItem lines="none">
                                    <IonButton size="small" color="secondary" slot="end" onClick={() => setShowModal(false)}>close</IonButton>
                                </IonItem>
                            </IonCol>
                        </IonRow>
                    </IonGrid>
                </Modal>

        </>
    )
}
export default SliderComponent;

Body:
First of all you must initialize selectedImage with object and not an array as that is what you expect it to be later

Second, assuming its an object, you won't use splice on it. You would either delete the key or make it false.

In any case you must make sure you are cloning the object before updating in state

const [selectedImage, setSlectedImage] = useState({}); // Initialize object
...
const handleTopImageClick = function (index, image1) {
    if (hideImages) {
        if (selectedImage[image1]) {
            setSlectedImage({...selectedImage, [image1]: false}); // hide image
        } else {
            setSlectedImage({ ...selectedImage, [image1]: true}); // show
        }
    } else {
        setShowModal(true)
        const i = index + index
        setInitialSlide(i)
    }
}


来源: stackexchange

问:
Scaling Animation iPhone
Can anyone describe a way to create an animated scaling affect on the iPhone?  I would like an image to start small, and then grow while fading. Motion tweening would also be helpful. Is quartz neccessary for this? I'd prefer to use something as simple as possible.

Thanks SO!

答:
You can do this all using UIViews/CALayer.

If the values you wish to expand to are predefined it's very easy.

you can use a CABasicAnimation where you set the new CGSize for the view/layer, and the length of the transition, coupled with another where you adjust the opacity of the view/layer. Add these two animations to the view. Motion tweening can be achieved by adjusting the position/frame of the object inside of a animation block.

This this section from the apple documentation on Core Animation for more information, and some basic examples

ContentLicense: CC BY-SA 3.0

Title: Scaling Animation iPhone


问:
Filtering a list of monads
I am attempting to filter a list of type: IO [Either a b]

Ideally, I would like to compose filtering function with the following type sig:

```<code>(Monad m, Monad m2) => m [m2 a] -> (a -> Bool) -> m [m2 a]
</code>```

I have tried a lot of combinations of filter, filterM, fmap, and =<< in a vain attempt to lift my predicate into the proper context, but I keep missing the mark - I can achieve m [m a]-> (a -> m Bool)-> m [m a], but since Either and IO are not the same monad, this doesn't seem to do me any good.

This seems like a usecase for 'do notation' , but I've been unable to suss out a way to examine the type signatures of things assigned with the <- operator, and so am left shooting at a moving target.

I am not sure how to compose the function in a way that will make it clear that it's traversing a list containing a instances of a different monad (Either) then the monad that contains the list itself (IO).

What am I missing here?

答:
I am handling the lists using their monad instance instead of using filter method. It may be better to use the filter in real world situations. I'm also not trying to make my functions as small as possible

I assumed you want some arbitrary method to handle the Eithers.
If you want to only filter the "right a" or get the left then you probably should use traversable. You also could use bimap to "fmap" left and right of Either simultaneously.

First a solution that works only with either:

```<code>filtermonads :: IO [(Either a b)] -> (a -> Bool) -> IO [(Either a b)]
filtermonads ioListEitherA cond = do
  listEitherA <- ioListEitherA
  return $ do
        eitherA <- listEitherA
        case eitherA of
          Left a -> if cond a then pure (Left a) else []
          Right b -> return (Right b)
</code>```

Should be the same as the following:

```<code>filtermonads' :: IO [(Either a b)] -> (a -> Bool) -> IO [(Either a b)]
filtermonads' ioListEitherA cond = let
  f x = case x of
    Left a -> if cond a then pure (Left a) else []
    Right a -> pure (Right a)
  in
    fmap (join . fmap f) ioListEitherA
</code>```

We have to manually open the Either as we require access to the information encapsulated inside it in order to know how to handle the list.

You could generalize this by instead separately providing a function (m2 a -> Bool) that tells how to extract the information from the monad.

```<code>eitherCond :: Either a b -> Bool
eitherCond eitherA = case eitherA of
          Left a -> False
          Right b -> True

filtermonads'' :: (Monad m) => m [a] -> (a -> Bool) -> m [a]
filtermonads'' m1listm2a cond = do
  listm2a <- m1listm2a
  return $ do
    m2a <- listm2a
    if cond m2a then pure m2a else []
</code>```

You could also generalize the list to MonadPlus or MonadFail as you can think of filtering meaning you need a monad with a zero element. The monad library itself also has fail that is sometimes zero, but you should not use it as it is not a feature all plain monads have and as such the implementations are sometimes very arbitrary.

Plain filter might be better as only few structures implement the MonadPlus class. I should have used mfilter for this. MonadPlus also doesn't have that many structures that implement it. For example Map is not even a monad.

```<code>filtermonads''' :: (Monad m1, MonadPlus mp) => m1 (mp a) -> (a -> Bool) -> m1 (mp a)
filtermonads''' m1listm2a cond = do
  listm2a <- m1listm2a
  return $ do
    m2a <- listm2a
    if cond m2a then pure m2a else mzero
</code>```

```<code>testData :: IO [Either Char Char]
testData = pure [Right 'a', Left 'a', Left 'c']

test1 = filtermonads testData (\x -> x=='a')
test2 = filtermonads' testData (\x -> x=='a')
test3 = filtermonads'' testData eitherCond
test4 = filtermonads''' testData eitherCond

justData ::IO (Maybe Char)
justData = pure (Just 'b')
readData :: Maybe (IO Char)
readData = Just (getChar) -- Notice that io mzero is error!
test5 = filtermonads''' justData (\x -> x=='a')
test6 = filtermonads''' readData (\x -> x=='a')
main = case (test6) of
  Just a -> a >>= putStrLn . pure
  Nothing -> pure ()
</code>```

Title: Filtering a list of monads

Body:
I am attempting to filter a list of type: IO [Either a b]

Ideally, I would like to compose filtering function with the following type sig:

(Monad m, Monad m2) => m [m2 a] -> (a -> Bool) -> m [m2 a]

I have tried a lot of combinations of filter, filterM, fmap, and =<< in a vain attempt to lift my predicate into the proper context, but I keep missing the mark - I can achieve m [m a]-> (a -> m Bool)-> m [m a], but since Either and IO are not the same monad, this doesn't seem to do me any good.

This seems like a usecase for 'do notation' , but I've been unable to suss out a way to examine the type signatures of things assigned with the <- operator, and so am left shooting at a moving target.

I am not sure how to compose the function in a way that will make it clear that it's traversing a list containing a instances of a different monad (Either) then the monad that contains the list itself (IO).

What am I missing here?

Body:
I am handling the lists using their monad instance instead of using filter method. It may be better to use the filter in real world situations. I'm also not trying to make my functions as small as possible

I assumed you want some arbitrary method to handle the Eithers.
If you want to only filter the "right a" or get the left then you probably should use traversable. You also could use bimap to "fmap" left and right of Either simultaneously.

First a solution that works only with either:

filtermonads :: IO [(Either a b)] -> (a -> Bool) -> IO [(Either a b)]
filtermonads ioListEitherA cond = do
  listEitherA <- ioListEitherA
  return $ do
        eitherA <- listEitherA
        case eitherA of
          Left a -> if cond a then pure (Left a) else []
          Right b -> return (Right b)

Should be the same as the following:

filtermonads' :: IO [(Either a b)] -> (a -> Bool) -> IO [(Either a b)]
filtermonads' ioListEitherA cond = let
  f x = case x of
    Left a -> if cond a then pure (Left a) else []
    Right a -> pure (Right a)
  in
    fmap (join . fmap f) ioListEitherA

We have to manually open the Either as we require access to the information encapsulated inside it in order to know how to handle the list.

You could generalize this by instead separately providing a function (m2 a -> Bool) that tells how to extract the information from the monad.

eitherCond :: Either a b -> Bool
eitherCond eitherA = case eitherA of
          Left a -> False
          Right b -> True

filtermonads'' :: (Monad m) => m [a] -> (a -> Bool) -> m [a]
filtermonads'' m1listm2a cond = do
  listm2a <- m1listm2a
  return $ do
    m2a <- listm2a
    if cond m2a then pure m2a else []

You could also generalize the list to MonadPlus or MonadFail as you can think of filtering meaning you need a monad with a zero element. The monad library itself also has fail that is sometimes zero, but you should not use it as it is not a feature all plain monads have and as such the implementations are sometimes very arbitrary.

Plain filter might be better as only few structures implement the MonadPlus class. I should have used mfilter for this. MonadPlus also doesn't have that many structures that implement it. For example Map is not even a monad.

filtermonads''' :: (Monad m1, MonadPlus mp) => m1 (mp a) -> (a -> Bool) -> m1 (mp a)
filtermonads''' m1listm2a cond = do
  listm2a <- m1listm2a
  return $ do
    m2a <- listm2a
    if cond m2a then pure m2a else mzero

testData :: IO [Either Char Char]
testData = pure [Right 'a', Left 'a', Left 'c']

test1 = filtermonads testData (\x -> x=='a')
test2 = filtermonads' testData (\x -> x=='a')
test3 = filtermonads'' testData eitherCond
test4 = filtermonads''' testData eitherCond

justData ::IO (Maybe Char)
justData = pure (Just 'b')
readData :: Maybe (IO Char)
readData = Just (getChar) -- Notice that io mzero is error!
test5 = filtermonads''' justData (\x -> x=='a')
test6 = filtermonads''' readData (\x -> x=='a')
main = case (test6) of
  Just a -> a >>= putStrLn . pure
  Nothing -> pure ()

ContentLicense: CC BY-SA 4.0


问:
Cannot access memory error for character array in struct - C
I am attempting to create a queue using a linked list in C. I am using two structs to represent the queue and each node which are as follows.

```<code>#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;
</code>```

I then use these the following functions to initialize the queue and the nodes.

```<code>int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}
</code>```

Upon running my enqueue function I get a seg fault due to a strcpy function and when debugging gdb says it cannot access the memory of the node I am attempting to add. The enqueue code is as follows:

```<code>int enqueue_ch(Queue_ch* q, char* data)
{
    if(strlen(data) > (DATA_MAX + 1))
        return 1;
    QueueNode_ch* tmp;
    initQueueNode_ch(tmp);
    strncpy(tmp->data, data, DATA_MAX);
    if(isEmpty_queue_ch(q))
        q->rear = q->front = tmp;
    else
    {
        q->rear->next = tmp;
        q->rear = tmp;
    }
    q->count++;
    return 0;
}
</code>```

I will also include my main function as additional information.

```<code>#include <stdio.h>
#include "Queue.h"

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}
</code>```

As far as I can tell there should be plenty of space to copy the given string to the node. Would anyone have any idea what is failing and possible fixes?

答:
```<code>int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}
</code>```

This function is unusable. It ignores the value of q passed into it and does not return a pointer to the queue it initialized. C is strictly pass by value.

```<code>int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}
</code>```

This code never gives queue any value and passes a garbage value to initQueue_ch (which it ignores) and then a garbage value to enqueue_ch.

Body:
I am attempting to create a queue using a linked list in C. I am using two structs to represent the queue and each node which are as follows.

#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;

I then use these the following functions to initialize the queue and the nodes.

int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}

Upon running my enqueue function I get a seg fault due to a strcpy function and when debugging gdb says it cannot access the memory of the node I am attempting to add. The enqueue code is as follows:

int enqueue_ch(Queue_ch* q, char* data)
{
    if(strlen(data) > (DATA_MAX + 1))
        return 1;
    QueueNode_ch* tmp;
    initQueueNode_ch(tmp);
    strncpy(tmp->data, data, DATA_MAX);
    if(isEmpty_queue_ch(q))
        q->rear = q->front = tmp;
    else
    {
        q->rear->next = tmp;
        q->rear = tmp;
    }
    q->count++;
    return 0;
}

I will also include my main function as additional information.

#include <stdio.h>
#include "Queue.h"

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}

As far as I can tell there should be plenty of space to copy the given string to the node. Would anyone have any idea what is failing and possible fixes?

Body:
int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

This function is unusable. It ignores the value of q passed into it and does not return a pointer to the queue it initialized. C is strictly pass by value.

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}

This code never gives queue any value and passes a garbage value to initQueue_ch (which it ignores) and then a garbage value to enqueue_ch.


问:
Unable to add all content to parent div inside a loop
The array gets console logged fine, but only the last person of the array is inserted in the HTML
.

Why or what is the failure?

document.getElementById("team").addEventListener("click", show)
function show(){
    document.getElementById("fritz").style.display = "block";
    document.getElementById("bill").style.display = "block";
    document.getElementById("fran").style.display = "block";

    for (i = 0; i < people.length; i++) {

        var persoxn = people[i].printinfos()

        document.getElementById('insert_text').innerHTML = persoxn

        console.log(persoxn)
     }
}
```

(https://imgur.com/IJbxvbR)
console

答:
You are overriding (replacing) the
 content in each iteration, therefore all of the elements except the last one get overwritten.

Maybe you meant to use .insertAdjacentHTML():

    for (let i = 0; i < people.length; i++) {
        var person = people[i].printinfos();
        document.getElementById('insert_text').insertAdjacentHTML(person, "beforeend");
        console.log(person);
     }
```

Also don't forget to declare i inside the loop.

Body:
The array gets console logged fine, but only the last person of the array is inserted in the HTML
.

Why or what is the failure?

document.getElementById("team").addEventListener("click", show)
function show(){
    document.getElementById("fritz").style.display = "block";
    document.getElementById("bill").style.display = "block";
    document.getElementById("fran").style.display = "block";

    for (i = 0; i < people.length; i++) {

        var persoxn = people[i].printinfos()

        document.getElementById('insert_text').innerHTML = persoxn

        console.log(persoxn)
     }
}

(https://imgur.com/IJbxvbR)
console

Body:
You are overriding (replacing) the <div> content in each iteration, therefore all of the elements except the last one get overwritten.

Maybe you meant to use .insertAdjacentHTML():

    for (let i = 0; i < people.length; i++) {
        var person = people[i].printinfos();
        document.getElementById('insert_text').insertAdjacentHTML(person, "beforeend");
        console.log(person);
     }

Also don't forget to declare i inside the loop.


问:
CSV remove duplicates in 2nd column without deleting first row
I have a csv with 17 columns and many 1000s of rows.  In column 2, I am attempting to delete duplicates, but keep the first.

File example:

```<code>1001,Henry
1002,Dave
1003,Dave
1004,Tom
</code>```

when I run:

```<code>sort -t, -k2,2 -u file.csv -o newfile.csv
</code>```

the newfile.csv contains (wrong)

```<code>1001,Henry
1004,Tom
</code>```

desired output:

```<code>1001,Henry
1002,Dave
1004,Tom
</code>```

I've tried several things with awk as well, no luck.  Thanks in advance!

答:
Try this,

```<code>awk -F ',' '!seen[$2]++' file.csv > newfile.csv
</code>```

This command is telling awk which lines to print. The variable $2 holds the entire contents of column 2 and square brackets are array access. So, for each second column of line in filename, the node of the array named seen is incremented and the line printed if the content of that node(column2) was not (!) previously set.

Body:
I have a csv with 17 columns and many 1000s of rows.  In column 2, I am attempting to delete duplicates, but keep the first.

File example:

1001,Henry
1002,Dave
1003,Dave
1004,Tom

when I run:

sort -t, -k2,2 -u file.csv -o newfile.csv

the newfile.csv contains (wrong)

1001,Henry
1004,Tom

desired output:

1001,Henry
1002,Dave
1004,Tom

I've tried several things with awk as well, no luck.  Thanks in advance!

Body:
Try this,

awk -F ',' '!seen[$2]++' file.csv > newfile.csv

This command is telling awk which lines to print. The variable $2 holds the entire contents of column 2 and square brackets are array access. So, for each second column of line in filename, the node of the array named seen is incremented and the line printed if the content of that node(column2) was not (!) previously set.


问:
Function in getting the less than equal in the list and removing the duplicates
I need to count how many less than or equal numbers in the list and disregarding the duplicates.

```<code>def getVal(prices = [5,5,10], money = 5):
        count = 0
        for i in prices:
            if money >= i and money == i:
                count += 1
        return count
</code>```

the output of this code is:
2

How can I get the output of 1.

答:
One liner?

```<code>def getVal(prices, money):
    return sum(i <= money for i in set(prices))

print(getVal([5, 5, 10], 5))
</code>```

Whenever you come across avoiding duplicates, the answer is always a set.

Body:
I need to count how many less than or equal numbers in the list and disregarding the duplicates.

def getVal(prices = [5,5,10], money = 5):
        count = 0
        for i in prices:
            if money >= i and money == i:
                count += 1
        return count

the output of this code is:
2

How can I get the output of 1.

Body:
One liner?

def getVal(prices, money):
    return sum(i <= money for i in set(prices))

print(getVal([5, 5, 10], 5))

Whenever you come across avoiding duplicates, the answer is always a set.


问:
Use query string in URL or use multiple URL?
If I want to display many posts in my web application but every post have its own type and I want to display each type in single page so, What's the best method to do that? Is put all all posts in one url and use query string to filter the posts upon the type and display it in the page?

For example : axios.get('/posts?type =sport')

Or I have to put every single type in separate Url

For example: axios.get('/posts/sport')

Also one more question please?
use one reducer to manage every posts or create one reducer for each post type?

答:
welcome to Stackoverflow!

I can imagine you have a web API of some sort serving a URL /posts. You want to consume that endpoint from your web application, and you are using axios to do that. I can assume you are using JSON to return that data. Correct me if I'm wrong.

Now that the basic information is "clear", what data you serve from the endpoint, and how it is requested from the client is up to you. Do you want to ask the server what types are there first, and then do one AJAX request per type? Ok. Do you want to serve all posts independent of their type? Ok. Do you want to accept POST data in your controller so you can filter the results before returning a response? Ok.

If you are looking for a more specific answer, you must give more details, or specify more. But I hope I could be of help.

Edit: complete answer.

If you want to filter the results, you have to send some additional data in your POST request, in this case, your post type. In axios, this could be done like this:

```<code>axios.post('https://example.com/posts', {
    type: 'sports'
}).then((data) => {
    console.log(data);
});
</code>```

You can obviously get the "type" value from a select input, other variable, even the current router page. I don't know your exact setup, but you can always come back and ask ;)

THEN, in your API controller you have to get that POST parameter type, and use it to filter the results. Again, I don't know your exact setup, but for MySQL if would be a WHERE statement in your query, or similar.

Body:
welcome to Stackoverflow!

I can imagine you have a web API of some sort serving a URL /posts. You want to consume that endpoint from your web application, and you are using axios to do that. I can assume you are using JSON to return that data. Correct me if I'm wrong.

Now that the basic information is "clear", what data you serve from the endpoint, and how it is requested from the client is up to you. Do you want to ask the server what types are there first, and then do one AJAX request per type? Ok. Do you want to serve all posts independent of their type? Ok. Do you want to accept POST data in your controller so you can filter the results before returning a response? Ok.

If you are looking for a more specific answer, you must give more details, or specify more. But I hope I could be of help.

Edit: complete answer.

If you want to filter the results, you have to send some additional data in your POST request, in this case, your post type. In axios, this could be done like this:

axios.post('https://example.com/posts', {
    type: 'sports'
}).then((data) => {
    console.log(data);
});

You can obviously get the "type" value from a select input, other variable, even the current router page. I don't know your exact setup, but you can always come back and ask ;)

THEN, in your API controller you have to get that POST parameter type, and use it to filter the results. Again, I don't know your exact setup, but for MySQL if would be a WHERE statement in your query, or similar.


问:
Get windows, move and resize on Windows
I'm on Windows and I need to get one window by title name then move and resize it. The code below is for unix only because fcntl doesn't exist on Windows.

```<code>import Xlib
import Xlib.display

display = Xlib.display.Display()
screen = display.screen()
root = screen.root
tree = root.query_tree()
wins = tree.children

for win in wins:
    print (win.get_wm_name())
    win.configure(x=123, y=345, width=678, height=910)
    win.change_attributes(win_gravity=X.NorthWestGravity, bit_gravity=X.StaticGravity)
</code>```

ModuleNotFoundError: No module named 'fcntl'

Do you have an alternative to this please ? Then how to get the windows which has the title "Hello there" ?

答:
I have found this and it is working :</p>

```<code>import win32gui, win32con

win2find = 'Skype'
whnd = win32gui.FindWindowEx(None, None, None, win2find)
if not (whnd == 0):
    print('Skype')
    win32gui.SetWindowPos(whnd, win32con.HWND_NOTOPMOST, 0, 0, 500, 600, 0)
</code>```

Title: Get windows, move and resize on Windows

Body:
I'm on Windows and I need to get one window by title name then move and resize it. The code below is for unix only because fcntl doesn't exist on Windows.

import Xlib
import Xlib.display

display = Xlib.display.Display()
screen = display.screen()
root = screen.root
tree = root.query_tree()
wins = tree.children

for win in wins:
    print (win.get_wm_name())
    win.configure(x=123, y=345, width=678, height=910)
    win.change_attributes(win_gravity=X.NorthWestGravity, bit_gravity=X.StaticGravity)

ModuleNotFoundError: No module named 'fcntl'

Do you have an alternative to this please ? Then how to get the windows which has the title "Hello there" ?

Body:
I have found this and it is working :

import win32gui, win32con

win2find = 'Skype'
whnd = win32gui.FindWindowEx(None, None, None, win2find)
if not (whnd == 0):
    print('Skype')
    win32gui.SetWindowPos(whnd, win32con.HWND_NOTOPMOST, 0, 0, 500, 600, 0)


问:
Firebase Cloud Functions: "status":"INVALID_ARGUMENT"
I am locally testing a Firebase Cloud Function. When I call this function using the local URL http://localhost:5001/projectName/us-central1/functionName as described here:

exports.createSession = functions.https.onRequest((_req, res) => {
  res.status(200).send('TESTING');
});
```

<p>the function works and it returns the string.</p>

<p>However, when I call this function:</p>

<pre class="lang-js prettyprint-override"><code>exports.createSession = functions.https.onCall((data, context) => {
  return 'TESTING';
});
</code>```

It throws the error: {"error":{"message":"Bad Request","status":"INVALID_ARGUMENT"}}

I'd like to use the latter function because I want to access the context.auth object to check for user Firebase authentication.

I'm using Firebase CLI v8.4 and Node v10.20.

What am I missing from the second function to get it working? I am not calling it with any arguments as I do not need to.

答:
You're comparing a callable function using onCall to an HTTP function using onRequest.  Callable functions are implemented very differently than HTTP functions.  I suggest reading over the documentation I linked in order to better understand the difference.  The main point is that callable functions follow a specific protocol, and that any client access must follow that protocol, or possibly receive the error that you show here.  The best implementation of that protocol is the client SDK provided by Firebase - you should use that to invoke the function.

If you want a normal HTTP function to be invoked using the usual HTTP libraries, then don't use a callable at all.  You can pass authentication information to an HTTP function manually using an ID token then verify it using the Firebase Admin SDK.  The documentation link has examples.

Body:
I am locally testing a Firebase Cloud Function. When I call this function using the local URL http://localhost:5001/projectName/us-central1/functionName as described here:

exports.createSession = functions.https.onRequest((_req, res) => {
  res.status(200).send('TESTING');
});

the function works and it returns the string.

However, when I call this function:

exports.createSession = functions.https.onCall((data, context) => {
  return 'TESTING';
});

It throws the error: {"error":{"message":"Bad Request","status":"INVALID_ARGUMENT"}}

I'd like to use the latter function because I want to access the context.auth object to check for user Firebase authentication.

I'm using Firebase CLI v8.4 and Node v10.20.

What am I missing from the second function to get it working? I am not calling it with any arguments as I do not need to.


问:
Swift parameters are not visible inside of Objective C Function?
Some background: I'm building an app in react native that uses an Objective C library written about 6 or 7 years ago, maybe older. I'm writing swift code that has been set up to send callbacks to the react native application in JS. I have this function that I'm trying to use:

```<code>token = service.getUserToken(server,
                port:  P2PFunctions.tls_port,
                appId: P2PFunctions.appID,
                appSecret: P2PFunctions.appSecret,
                phone: P2PFunctions.phone,
                token: nil, errcode: errCode, errmsg: nil);
        callback(["\(token!)"]);
</code>```

And this is its definition:

```<code>- (NSInteger)getUserToken:(NSString*)ip_In port:(NSInteger)port_In appId:
(NSString*)appId_In appSecret:(NSString*)appSecret_In phone:
(NSString*)phoneNum_In token:(NSString**)accessTok_Out errcode:
(NSString**)strErrCode_Out errmsg:(NSString**)errMsg_Out;
</code>```

These are the types I'm using (EDIT: I changed them from private to public, and they still are not being recognized):

The problem is, I'm getting nil back from the function. I believe I'm getting an HTTP response that is empty, and I notice that inside the debugger when I step to the Objective C function, I see nil for all my parameters inside of the Objective C function. I think... it is that I'm not passing the correct type. Or my Swift parameters are not visible in Objective C's memory space. If it is expecting an (NSString *), should I be passing a String?

How do I pass the correct types from Swift to Objective C? What would I change in my function call? Are my parameter types okay? I cannot edit the original Objective C library. They share a common memory space for all variables in the entire program, right?

Thank you so much!

答:
I just ran this successfully:

```<code>// the objc part
@interface Test : NSObject

- (NSInteger)getUserToken:(NSString*)ip_In
                     port:(NSInteger)port_In
                    appId:(NSString*)appId_In
                appSecret:(NSString*)appSecret_In
                    phone:(NSString*)phoneNum_In
                    token:(NSString* _Nonnull * _Nonnull)accessTok_Out
                  errcode:(NSString* _Nonnull * _Nonnull)strErrCode_Out
                   errmsg:(NSString* _Nonnull * _Nonnull)errMsg_Out;

@end

@implementation Test

- (NSInteger)getUserToken:(NSString*)ip_In
                     port:(NSInteger)port_In
                    appId:(NSString*)appId_In
                appSecret:(NSString*)appSecret_In
                    phone:(NSString*)phoneNum_In
                    token:(NSString**)accessTok_Out
                  errcode:(NSString**)strErrCode_Out
                   errmsg:(NSString**)errMsg_Out {

    *accessTok_Out = @"Token";
    *strErrCode_Out = @"OK";
    *errMsg_Out = @"msg";

    return 42;
}

@end

// and the swift part
let t = Test()
var token: NSString = "t"
var errcode: NSString = "c"
var errmsg: NSString = "m"
let result = t.getUserToken("ip", port: 1,
   appId: "2", appSecret: "3", phone: "4",
   token: &token, errcode: &errcode, errmsg: &errmsg)
print(result)
</code>```

and it works as expected.

Maybe this gives you a hint as to what's different in your situation.

Body:
Some background: I'm building an app in react native that uses an Objective C library written about 6 or 7 years ago, maybe older. I'm writing swift code that has been set up to send callbacks to the react native application in JS. I have this function that I'm trying to use:

token = service.getUserToken(server,
                port:  P2PFunctions.tls_port,
                appId: P2PFunctions.appID,
                appSecret: P2PFunctions.appSecret,
                phone: P2PFunctions.phone,
                token: nil, errcode: errCode, errmsg: nil);
        callback(["\(token!)"]);

And this is its definition:

- (NSInteger)getUserToken:(NSString*)ip_In port:(NSInteger)port_In appId:
(NSString*)appId_In appSecret:(NSString*)appSecret_In phone:
(NSString*)phoneNum_In token:(NSString**)accessTok_Out errcode:
(NSString**)strErrCode_Out errmsg:(NSString**)errMsg_Out;

These are the types I'm using (EDIT: I changed them from private to public, and they still are not being recognized):

The problem is, I'm getting nil back from the function. I believe I'm getting an HTTP response that is empty, and I notice that inside the debugger when I step to the Objective C function, I see nil for all my parameters inside of the Objective C function. I think... it is that I'm not passing the correct type. Or my Swift parameters are not visible in Objective C's memory space. If it is expecting an (NSString *), should I be passing a String?

How do I pass the correct types from Swift to Objective C? What would I change in my function call? Are my parameter types okay? I cannot edit the original Objective C library. They share a common memory space for all variables in the entire program, right?

Thank you so much!

Body:
I just ran this successfully:

// the objc part
@interface Test : NSObject

- (NSInteger)getUserToken:(NSString*)ip_In
                     port:(NSInteger)port_In
                    appId:(NSString*)appId_In
                appSecret:(NSString*)appSecret_In
                    phone:(NSString*)phoneNum_In
                    token:(NSString* _Nonnull * _Nonnull)accessTok_Out
                  errcode:(NSString* _Nonnull * _Nonnull)strErrCode_Out
                   errmsg:(NSString* _Nonnull * _Nonnull)errMsg_Out;

@end

@implementation Test

- (NSInteger)getUserToken:(NSString*)ip_In
                     port:(NSInteger)port_In
                    appId:(NSString*)appId_In
                appSecret:(NSString*)appSecret_In
                    phone:(NSString*)phoneNum_In
                    token:(NSString**)accessTok_Out
                  errcode:(NSString**)strErrCode_Out
                   errmsg:(NSString**)errMsg_Out {

    *accessTok_Out = @"Token";
    *strErrCode_Out = @"OK";
    *errMsg_Out = @"msg";

    return 42;
}

@end

// and the swift part
let t = Test()
var token: NSString = "t"
var errcode: NSString = "c"
var errmsg: NSString = "m"
let result = t.getUserToken("ip", port: 1,
   appId: "2", appSecret: "3", phone: "4",
   token: &token, errcode: &errcode, errmsg: &errmsg)
print(result)

and it works as expected.

Maybe this gives you a hint as to what's different in your situation.


问:
Unable to decode base64 while read the data from console C#
I'm facing the issue while converting the encode/decode the data with C#. I have hard-coded the certain base64(encoded) data and its successfully decoded the string. As like below,

```<code>string encodedText = "eyJDb25uX0dyb3VwX0lEIjozMywiVXNlckVtYWlsIjoiVGVzdHNlcnZpc2VA\nZ21haWwuY29tIiwiVXNlclBhc3N3b3JkIjoib1ZkTEREWUVfX3FuSnZFSE1W\ncnR5WU5ZZzJSTnNzUnpaWG5KaFJMcCIsIkJhc2VVUkwiOiJodHRwOi8vbG9j\nYWxob3N0OjMwMDAifQ==\n";
byte[] data = Convert.FromBase64String(encodedText);
string decodedString = Encoding.UTF8.GetString(data);
</code>```

But, while reading the same value from the console, its failed to decode the data. For example,

```<code>string readLine = Console.ReadLine();
Console.WriteLine("Received Data :: " + readLine); // Exactly same data received here
byte[] encodedByte = Convert.FromBase64String(readLine); //Failed here?
string configData = System.Text.Encoding.UTF8.GetString(encodedByte);
</code>```

The second code failed with the below error message

```<code>Unhandled exception. System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
   at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
   at System.Convert.FromBase64String(String s)
</code>```

Note:

I have noticed that and removed all the \n from the given string. Now, its working fine. But, I'm not sure how to remove that \n programatically. I tried with the below codes, but it's does not working,

```<code>readLine = Regex.Replace(readLine, @"\t|\n|\r", String.Empty);
</code>```

And also tried with,

```<code>readLine = readLine.Replace("\n", String.Empty);
</code>```

It would be much appreciated if anyone help on this.

答:
Here is the original re-written to illustrate extra characters:

```<code>string encodedText =
    "eyJDb25uX0dyb3VwX0lEIjozMywiVXNlckVtYWlsIjoiVGVzdHNlcnZpc2VA"
+ "\nZ21haWwuY29tIiwiVXNlclBhc3N3b3JkIjoib1ZkTEREWUVfX3FuSnZFSE1W"
+ "\ncnR5WU5ZZzJSTnNzUnpaWG5KaFJMcCIsIkJhc2VVUkwiOiJodHRwOi8vbG9j"
+ "\nYWxob3N0OjMwMDAifQ=="
+ "\n";
</code>```

The data that should be entered in the console is then:

eyJDb25uX0dyb3VwX0lEIjozMywiVXNlckVtYWlsIjoiVGVzdHNlcnZpc2VAZ21haWwuY29tIiwiVXNlclBhc3N3b3JkIjoib1ZkTEREWUVfX3FuSnZFSE1WcnR5WU5ZZzJSTnNzUnpaWG5KaFJMcCIsIkJhc2VVUkwiOiJodHRwOi8vbG9jYWxob3N0OjMwMDAifQ==

There is no encoding issue present with this data "when cleaned up", and it will be read correctly with Console.ReadLine if correctly entered. Try to pipe it in from a file if unable to paste such correctly.

The code from the literal works because of relaxed rules in that newline characters are ignored by Convert.FromBase64String. However, the translation (of "\n" to a literal newline) that occurs in a string literal does NOT occur when entered/read via the console.

Performing a translation of errant \n sequences that appear - read as two characters when typed in the console - would require code such as:

```<code>readLine = readLine.Replace("\\n", "");
// "\n".ToCharArray()  -> { 0x10 }
// "\\n".ToCharArray() -> { '\\', 'n' }
</code>```

Body:
I'm facing the issue while converting the encode/decode the data with C#. I have hard-coded the certain base64(encoded) data and its successfully decoded the string. As like below,

string encodedText = "eyJDb25uX0dyb3VwX0lEIjozMywiVXNlckVtYWlsIjoiVGVzdHNlcnZpc2VA\nZ21haWwuY29tIiwiVXNlclBhc3N3b3JkIjoib1ZkTEREWUVfX3FuSnZFSE1W\ncnR5WU5ZZzJSTnNzUnpaWG5KaFJMcCIsIkJhc2VVUkwiOiJodHRwOi8vbG9j\nYWxob3N0OjMwMDAifQ==\n";
byte[] data = Convert.FromBase64String(encodedText);
string decodedString = Encoding.UTF8.GetString(data);

But, while reading the same value from the console, its failed to decode the data. For example,

string readLine = Console.ReadLine();
Console.WriteLine("Received Data :: " + readLine); // Exactly same data received here
byte[] encodedByte = Convert.FromBase64String(readLine); //Failed here?
string configData = System.Text.Encoding.UTF8.GetString(encodedByte);

The second code failed with the below error message

Unhandled exception. System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
   at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
   at System.Convert.FromBase64String(String s)

Note:

I have noticed that and removed all the \n from the given string. Now, its working fine. But, I'm not sure how to remove that \n programatically. I tried with the below codes, but it's does not working,

readLine = Regex.Replace(readLine, @"\t|\n|\r", String.Empty);

And also tried with,

readLine = readLine.Replace("\n", String.Empty);

It would be much appreciated if anyone help on this.

Body:
Here is the original re-written to illustrate extra characters:

string encodedText =
    "eyJDb25uX0dyb3VwX0lEIjozMywiVXNlckVtYWlsIjoiVGVzdHNlcnZpc2VA"
+ "\nZ21haWwuY29tIiwiVXNlclBhc3N3b3JkIjoib1ZkTEREWUVfX3FuSnZFSE1W"
+ "\ncnR5WU5ZZzJSTnNzUnpaWG5KaFJMcCIsIkJhc2VVUkwiOiJodHRwOi8vbG9j"
+ "\nYWxob3N0OjMwMDAifQ=="
+ "\n";

The data that should be entered in the console is then:

eyJDb25uX0dyb3VwX0lEIjozMywiVXNlckVtYWlsIjoiVGVzdHNlcnZpc2VAZ21haWwuY29tIiwiVXNlclBhc3N3b3JkIjoib1ZkTEREWUVfX3FuSnZFSE1WcnR5WU5ZZzJSTnNzUnpaWG5KaFJMcCIsIkJhc2VVUkwiOiJodHRwOi8vbG9jYWxob3N0OjMwMDAifQ==

There is no encoding issue present with this data "when cleaned up", and it will be read correctly with Console.ReadLine if correctly entered. Try to pipe it in from a file if unable to paste such correctly.

The code from the literal works because of relaxed rules in that newline characters are ignored by Convert.FromBase64String. However, the translation (of "\n" to a literal newline) that occurs in a string literal does NOT occur when entered/read via the console.

Performing a translation of errant \n sequences that appear - read as two characters when typed in the console - would require code such as:

readLine = readLine.Replace("\\n", "");
// "\n".ToCharArray()  -> { 0x10 }
// "\\n".ToCharArray() -> { '\\', 'n' }


问:
Why do I repeatedly get EADDRINUSE errors
I may know the answer to this question but I am looking for confirmation in case I am missing something.

I am in a development mode on a full stack Node/React project. My server is running on port 5000. My client is running on port 3000. I am proxying my frontend routes to node for the actual IO. All of that seems to be running just fine.

I am working from my home office so when I quit work each evening I simply walk away from my work. Sometime later that night my machine logs me out. That is probably NOT a best practice.

The next working day I sit down to work, I login, I execute npm run dev (I'm running concurrently). Typically the front end comes up No Problem. However (even though the app executes properly) my console displays ERRADDRINUSE :::5000.

It looks like everything is going ok but I suppose something may be lying in wait for me. And, it also indicates that it isn't completely benign.

Here is my thought. I do get automatically logged out each evening but apparently that is not necessarily closing the ports down (at least not port 5000). I am thinking that I should probably be performing and actual shut down or restart every evening.

Am I right? And, when you confirm, would you mind including the "why"? I am still learning as I go. Thanks.

答:
TLDR:

Running ps aux | grep node will allow you to determine the PID of the process that is listening on listening on port 5000 and you can kill it with kill -9 PID.
(where PID is the process id of the hanging process)

Little more explanation:

Your two servers are each running as independent processes within your system. If you run a command-line program like top, you will be able a list of the running processes, including the process identifier or PID.

When the state of your system changes (logging out, shutting down, loses network connection). The operating system issues a signal (sometimes referred to as a software interrupt). The process is then responsible for deciding how to proceed after receiving the signal. (There is separate code for this known as signal handlers). Most modern web frameworks already have signal handlers built in to respond to the common signals.

Usually, a process is terminated when the SIGTERM signal is issued or is forced to stop when the SIGKILL signal is issued.

However, it is not uncommon to have a process that hangs every now and then. (I have seen this before with nodejs servers). To stop them, the easiest thing to do would be to issue a SIGTERM (gracefully stop the process) or SIGKILL signal (force stop the process) manually to the process yourself.

The kill -9 PID command can be used to issue a SIGKILL signal to the process.

For more on this see the Linux man-pages on processes and/or signals.


问:
create a new array from array of arrays
I have this array of arrays:

```<code>let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]
</code>```

And I want to return this single array from it:

```<code>b = ["i was sent = i do", "i was sent = i sent", "to protect you = to find you"]
</code>```

How can I do that?

I have tried to use a map like let b = a.map(s => s + ' = '); but it won't do the job?

答:
Assuming your inner arrays always have two elements:

let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]

let b = a.map(el => `${el[0]} = ${el[1]}`);

console.log(b);```

Title: create a new array from array of arrays

Body:
I have this array of arrays:

let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]

And I want to return this single array from it:

b = ["i was sent = i do", "i was sent = i sent", "to protect you = to find you"]

How can I do that?

I have tried to use a map like let b = a.map(s => s + ' = '); but it won't do the job?


问:
Facebook notification of Wordpress post
Is there a way of sending notification about new wordpress-based blog to facebook account?
Or maybe a plugin for wordpress?

Restriction is that user shouldn't be logged into facebook, just specify facebook credentials to the plugin.

答: Check out the Wordpress.com Facebook application: http://en.blog.wordpress.com/2007/07/18/facebook/</p>

OwnerDisplayName: Roman

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5

Title: Facebook notification of Wordpress post

OwnerDisplayName: Can Berk Güder


答:
You can use

```<code>[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];

myImageView.alpha = 0.0;
myImageView.size = CGSizeMake(myImageView.size.width*2,myImageView.size.height*2);

[UIView commitAnimations];
</code>```

This does require the CoreAnimations framework to be added to your project.

Title: Scaling Animation iPhone

Body:
Can anyone describe a way to create an animated scaling affect on the iPhone?  I would like an image to start small, and then grow while fading. Motion tweening would also be helpful. Is quartz neccessary for this? I'd prefer to use something as simple as possible.

Thanks SO!

Body:
You can use

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];

myImageView.alpha = 0.0;
myImageView.size = CGSizeMake(myImageView.size.width*2,myImageView.size.height*2);

[UIView commitAnimations];

This does require the CoreAnimations framework to be added to your project.


问:
how to get the values of one array of objects key based on values of another array of objects?
```<code>   data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}
</code>```

the output expected is

```<code>const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}
</code>```

I tried mapping the uids to get and array of values like

```<code>uids = [12, 23]
</code>```

then

```<code>        names = uids.map(key => object[key].name);
</code>```

so that I could use them to map the keys and the names in the other object but couldn't figure it out
I know it is basic javascript but I am new to this

答:
```<code>var data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
};

var object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}};

var uids = [12, 23];

    mappedValues = uids.map(key => object[key]);

 var result = mappedValues.map((item, i) => Object.assign({}, item, data[i]));
console.log(result);
</code>```

Body:
   data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}

the output expected is

const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}

I tried mapping the uids to get and array of values like

uids = [12, 23]

then

        names = uids.map(key => object[key].name);

so that I could use them to map the keys and the names in the other object but couldn't figure it out
I know it is basic javascript but I am new to this


问:
My speech.listen(source) in python is taking stalling
I am currently using the SpeechRecognition library, and when I do audio = speech.listen(source), it seems like it stalls. There is no execution of code after it. I remove ambient sound, but it still seems to stall and have no effect on what my mic is picking up. Microphone works when I look at my computer's settings and it is unmuted.

I create an pyttsx3 instance called engine, and a sr.Recognizer() instance called speech. I then call getVoiceCommand() to get some audio from the user(me) which goes to print("Listening...") and then it stalls.

The code after audio = speech.listen(source) does not execute, and when the timeout of 10 seconds is done, it gives me the WaitTimoutError, which hints out to me that it never picked up a sound? I tried changing the energy_threshold for values between 50 and 4000 and still didn't pick up any noise.

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

def speak(text):
    engine.say(text)
    engine.runAndWait()

def getVoiceCommand():
    voice_text = ''
    try:
        with sr.Microphone() as source:
            speech.adjust_for_ambient_noise(source)
            print("Listening...")
            #speech.energy_threshold = 4000
            print(speech.energy_threshold)
            audio = speech.listen(source, timeout=10)

        print("Stopped")
        voice_text = speech.recognize_google(audio, language='en-US')
    except sr.UnknownValueError:
        print("Unknown value error")
    except sr.RequestError as e:
        print('Network error.')
    except sr.WaitTimeoutError:
        print(audio)
        print("Wait timeout error")

    print(voice_text)

engine = pyttsx3.init()
engine.setProperty('voice', voice_id) # voice_id is chosen voice

rate = 220
engine.setProperty('rate', rate)

speech = sr.Recognizer()
getVoiceCommand()

</code>```

答:
I have used this program with the exact same libraries. This is assuming you have a microphone of some sort. If this doesn't work, its most likely background noise it is trying to detect as an input which in that case, you would need to add r.adjust_for_ambient_noise(source, duration=1) Tell me if this code below works...

```<code>engine = pyttsx3.init('sapi5')   #Only use sapi 5 if it is Windows 10
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #This bit goes below the imports

def speak(audio):
    engine.say(audio)     #This bit right here goes below the above
    engine.runAndWait()

def takeCommand():
    r = sr.Recognizer()

    with sr.Microphone() as source:

        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-us')
        print("User said: {query}\n")

    except Exception as e:
        print(e)
        print("Google was unable to hear")
        return "None"

    return query
</code>```

I hope this works for you.

Body:
I am currently using the SpeechRecognition library, and when I do audio = speech.listen(source), it seems like it stalls. There is no execution of code after it. I remove ambient sound, but it still seems to stall and have no effect on what my mic is picking up. Microphone works when I look at my computer's settings and it is unmuted.

I create an pyttsx3 instance called engine, and a sr.Recognizer() instance called speech. I then call getVoiceCommand() to get some audio from the user(me) which goes to print("Listening...") and then it stalls.

The code after audio = speech.listen(source) does not execute, and when the timeout of 10 seconds is done, it gives me the WaitTimoutError, which hints out to me that it never picked up a sound? I tried changing the energy_threshold for values between 50 and 4000 and still didn't pick up any noise.

import speech_recognition as sr
import pyttsx3
import pyaudio

def speak(text):
    engine.say(text)
    engine.runAndWait()

def getVoiceCommand():
    voice_text = ''
    try:
        with sr.Microphone() as source:
            speech.adjust_for_ambient_noise(source)
            print("Listening...")
            #speech.energy_threshold = 4000
            print(speech.energy_threshold)
            audio = speech.listen(source, timeout=10)

        print("Stopped")
        voice_text = speech.recognize_google(audio, language='en-US')
    except sr.UnknownValueError:
        print("Unknown value error")
    except sr.RequestError as e:
        print('Network error.')
    except sr.WaitTimeoutError:
        print(audio)
        print("Wait timeout error")

    print(voice_text)

engine = pyttsx3.init()
engine.setProperty('voice', voice_id) # voice_id is chosen voice

rate = 220
engine.setProperty('rate', rate)

speech = sr.Recognizer()
getVoiceCommand()

Body:
I have used this program with the exact same libraries. This is assuming you have a microphone of some sort. If this doesn't work, its most likely background noise it is trying to detect as an input which in that case, you would need to add r.adjust_for_ambient_noise(source, duration=1) Tell me if this code below works...

engine = pyttsx3.init('sapi5')   #Only use sapi 5 if it is Windows 10
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #This bit goes below the imports

def speak(audio):
    engine.say(audio)     #This bit right here goes below the above
    engine.runAndWait()

def takeCommand():
    r = sr.Recognizer()

    with sr.Microphone() as source:

        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-us')
        print("User said: {query}\n")

    except Exception as e:
        print(e)
        print("Google was unable to hear")
        return "None"

    return query

I hope this works for you.


问:
How can I effectively bind my @KafkaListener to ConcurrentKafkaListenerContainerFactory?
I hit this scenario which appears strange to me:

So basically I have defined two @KafkaListener in one class:

@KafkaListener(id = "listener1", idIsGroup = false, topics = "data1", containerFactory = "kafkaListenerContainerFactory")
    public void receive(){}

@KafkaListener(id = "listener2", idIsGroup = false, topics = "data2", containerFactory = "kafkaListenerContainerFactory2")
    public void receive(){}
```

<p>Their <code>id</code>, <code>topics</code>, <code>containerFactory</code> are different, and each of them relies on a different <code>ConcurrentKafkaListenerContainerFactory</code> as defined in another class:</p>

<pre class="lang-java prettyprint-override"><code>@Bean
public ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory("group1", "earliest"));
    factory.setAutoStartup(false);
    return factory;
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> kafkaListenerContainerFactory2() {
    ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory("group2", "latest"));
    factory.setAutoStartup(true);
    return factory;
}

@Bean
public ConsumerFactory<String, ConsumerRecord> consumerFactory(String groupId, String offset) {
    Map<String, Object> config = new HashMap<>();
    // dt is current timestamp in millisecond (epoch)
    config.put(ConsumerConfig.GROUP_ID_CONFIG, groupId + "-" + dt);
    config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, offset);
    // other config omitted
    return new DefaultKafkaConsumerFactory<>(config);
}
</code>```

So what I expect to see (and what I want to achieve) are:

Only listener2 will auto-start because
factory.setAutoStartup(true)

Listener2 will start with group.id "group2" and auto.offset.reset "latest"

Later when listener1 starts via some event listener, it will start
with group.id "group1" and auto.offset.reset "earlist"

However, only the 1st is actually guaranteed. Listener2 can start with either {group2 + latest} or {group1 + earliest}. And later when listener1 starts to consume data, it will just reuse the config of listener2 (I can see the same group id which contains a timestamp is printed twice in my log)

My question is, why the group ID and offset config for listener2 are randomly picked while autoStartup is not? And why listener1 will reuse the config of listener2?

答:
It's because consumerFactory is a singleton @Bean and the arguments are ignored on the second call.

Add @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) to the factory get a new bean each time.

However, you don't need any of this, you can simply set the groupId property on the annotations and avoid all this extra definition.

You can also control autoStartup on the annotation (since 2.2).

EDIT

To answer the question in the comment below...

```<code>groupId = "#{'${group.id}' + T(java.time.Instant).now().toEpochMilli()}"
</code>```

however, if you want a unique group id; this is more reliable...

```<code>groupId = "#{'${group.id}' + T(java.util.UUID).randomUUID()}"
</code>```

Body:
I hit this scenario which appears strange to me:

So basically I have defined two @KafkaListener in one class:

@KafkaListener(id = "listener1", idIsGroup = false, topics = "data1", containerFactory = "kafkaListenerContainerFactory")
    public void receive(){}

@KafkaListener(id = "listener2", idIsGroup = false, topics = "data2", containerFactory = "kafkaListenerContainerFactory2")
    public void receive(){}

Their id, topics, containerFactory are different, and each of them relies on a different ConcurrentKafkaListenerContainerFactory as defined in another class:

@Bean
public ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory("group1", "earliest"));
    factory.setAutoStartup(false);
    return factory;
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> kafkaListenerContainerFactory2() {
    ConcurrentKafkaListenerContainerFactory<String, ConsumerRecord> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory("group2", "latest"));
    factory.setAutoStartup(true);
    return factory;
}

@Bean
public ConsumerFactory<String, ConsumerRecord> consumerFactory(String groupId, String offset) {
    Map<String, Object> config = new HashMap<>();
    // dt is current timestamp in millisecond (epoch)
    config.put(ConsumerConfig.GROUP_ID_CONFIG, groupId + "-" + dt);
    config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, offset);
    // other config omitted
    return new DefaultKafkaConsumerFactory<>(config);
}

So what I expect to see (and what I want to achieve) are:

Only listener2 will auto-start because
factory.setAutoStartup(true)

Listener2 will start with group.id "group2" and auto.offset.reset "latest"

Later when listener1 starts via some event listener, it will start
with group.id "group1" and auto.offset.reset "earlist"

However, only the 1st is actually guaranteed. Listener2 can start with either {group2 + latest} or {group1 + earliest}. And later when listener1 starts to consume data, it will just reuse the config of listener2 (I can see the same group id which contains a timestamp is printed twice in my log)

My question is, why the group ID and offset config for listener2 are randomly picked while autoStartup is not? And why listener1 will reuse the config of listener2?

Body:
It's because consumerFactory is a singleton @Bean and the arguments are ignored on the second call.

Add @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) to the factory get a new bean each time.

However, you don't need any of this, you can simply set the groupId property on the annotations and avoid all this extra definition.

You can also control autoStartup on the annotation (since 2.2).

EDIT

To answer the question in the comment below...

groupId = "#{'${group.id}' + T(java.time.Instant).now().toEpochMilli()}"

however, if you want a unique group id; this is more reliable...

groupId = "#{'${group.id}' + T(java.util.UUID).randomUUID()}"


问:
Python: select specific entries of a list
Say

a = [1,2,3,4,5,6,7]

If I want to select the elements 0 to 4 of that I can do so by

a[0:3]

Now what I would like to do is to select, say, the first, third and fourth element with a similar command. So I would like to build the list [2,4,5] by a command such as

a[???]

What would I have to fill in for the ????

(I do not want to do [a[1],a[3],a[4]], since in my case a is the return of the function, and only want to call it once.)

Thanks for suggestions!

答:
You could use mapping like the follwoing:

```<code>a = [1,2,3,4,5,6,7]

res = list(map(a.__getitem__, [1,3,5]))
print(res)
# [2, 4, 6]
</code>```

Other option is to use operator.itemgetter:

```<code>import operator
b= [1,3,5]
res = operator.itemgetter(*b)(a)
print(list(res)
# [2, 4, 6]
</code>```

Body:
You could use mapping like the follwoing:

a = [1,2,3,4,5,6,7]

res = list(map(a.__getitem__, [1,3,5]))
print(res)
# [2, 4, 6]

Other option is to use operator.itemgetter:

import operator
b= [1,3,5]
res = operator.itemgetter(*b)(a)
print(list(res)
# [2, 4, 6]


问:
error: result of comparison against a string literal is unspecified for C
So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

```<code>#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}
</code>```

答:
You cannot compare two strings in c using a comparison operator.
Try using

```<code>strcmp(const char* one, const char* two)
</code>```

That is, in your case
use

```<code>#include<stdio.h>
#include<cs50.h>
int main(void){
    char[] a = get_string("ENTER YOUR NAME FOR READING\n");
    char[] b = "david";
    if (!strcmp(a,"david"))
    {
        printf("...");
    }
}
</code>```

Also, Strings in c are not declared as strings. They are declared as char arrays

Body:
So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}

Body:
You cannot compare two strings in c using a comparison operator.
Try using

strcmp(const char* one, const char* two)

That is, in your case
use

#include<stdio.h>
#include<cs50.h>
int main(void){
    char[] a = get_string("ENTER YOUR NAME FOR READING\n");
    char[] b = "david";
    if (!strcmp(a,"david"))
    {
        printf("...");
    }
}

Also, Strings in c are not declared as strings. They are declared as char arrays


问:
Solution has projects that are located outside the solution folder
I tried to add my solution to the local repository by selecting File|Add to Source Control, but I got the following message.

Source Control - Git

  The current solution has projects that are located outside the solution folder.These projects will not be source controlled in Git repository.To add all the projects to a single Git repository please consolidate all projects under a single folder.

However, all of my projects are within my solution folder. The only thing I'm uncertain about is that I added a NuGet package to one of my projects and I don't see that anywhere. It appears as the following in the project's csproj file.

```<code><ItemGroup>
  <PackageReference Include="Microsoft.Win32.Registry" Version="4.5.0" />
</ItemGroup>
</code>```

Does anyone know if that could cause this error? I was able to click OK and it created the local repository, but I want to put it on GitHub and so I'd like to figure out what the issue is.

As an additional question, when adding a solution like this to GitHub, would I normally include any packages like this? I expected a packages folder but I didn't get one.

Here's a screenshot of the solution:

And here's my solution file:

```<code>Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28922.388
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Toxic", "Toxic\Toxic.csproj", "{DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Toxic.Desktop", "Toxic.Desktop\Toxic.Desktop.csproj", "{A4EAA8D5-C085-4960-A871-74F68F6F9BC7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Toxic.Web",    "Toxic.Web\Toxic.Web.csproj", "{49E8312B-506E-4AC1-8524-37BB601EC889}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ToxicTests", "ToxicTests\ToxicTests.csproj", "{131B2077-A4C2-48EA-A1E1-8CA1A38097BD}"
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Release|Any CPU.Build.0 = Release|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Release|Any CPU.Build.0 = Release|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Release|Any CPU.Build.0 = Release|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Release|Any CPU.Build.0 = Release|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(ExtensibilityGlobals) = postSolution
        SolutionGuid = {2076F481-A5C7-4132-874E-47767C93475D}
    EndGlobalSection
EndGlobal
</code>```

UPDATE:

It seems I now get this message every time I add a new project to Source Control. There seems to be something fundamentally going on here as I do not think I am referencing any external files, and I think my solution files show that. Note that even though I get this message, it still adds the solution to source control and everything seems to be working okay.

I do not have a command-line GIT program and would really prefer not to install anything else if there's any way to see what's going on without it.

答:
For anyone who experienced this right after adding a xUnit .Net Core test project, the solution/workaround is in a comment from tintow on the excellent answer from dmcquiggin:

I was facing the same problem and found a fairly simple workaround. As dmcquiggen pointed out, this is related to MS Test. I found that by simply unloading the MS Test project before checking in resolved this problem and the test project is still checked into source control. Then just reload the MS Test project and it appears to work as normal. Maybe the underlying test package is not included but thats not a problem for me. – Tintow Oct 11 '19 at 11:59

Body:
I tried to add my solution to the local repository by selecting File|Add to Source Control, but I got the following message.

Source Control - Git

  The current solution has projects that are located outside the solution folder.These projects will not be source controlled in Git repository.To add all the projects to a single Git repository please consolidate all projects under a single folder.

However, all of my projects are within my solution folder. The only thing I'm uncertain about is that I added a NuGet package to one of my projects and I don't see that anywhere. It appears as the following in the project's csproj file.

<ItemGroup>
  <PackageReference Include="Microsoft.Win32.Registry" Version="4.5.0" />
</ItemGroup>

Does anyone know if that could cause this error? I was able to click OK and it created the local repository, but I want to put it on GitHub and so I'd like to figure out what the issue is.

As an additional question, when adding a solution like this to GitHub, would I normally include any packages like this? I expected a packages folder but I didn't get one.

Here's a screenshot of the solution:

And here's my solution file:

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28922.388
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Toxic", "Toxic\Toxic.csproj", "{DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Toxic.Desktop", "Toxic.Desktop\Toxic.Desktop.csproj", "{A4EAA8D5-C085-4960-A871-74F68F6F9BC7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Toxic.Web",    "Toxic.Web\Toxic.Web.csproj", "{49E8312B-506E-4AC1-8524-37BB601EC889}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ToxicTests", "ToxicTests\ToxicTests.csproj", "{131B2077-A4C2-48EA-A1E1-8CA1A38097BD}"
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {DEAAC3F5-B48F-4601-ADC7-ECFE1519A841}.Release|Any CPU.Build.0 = Release|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {A4EAA8D5-C085-4960-A871-74F68F6F9BC7}.Release|Any CPU.Build.0 = Release|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {49E8312B-506E-4AC1-8524-37BB601EC889}.Release|Any CPU.Build.0 = Release|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {131B2077-A4C2-48EA-A1E1-8CA1A38097BD}.Release|Any CPU.Build.0 = Release|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(ExtensibilityGlobals) = postSolution
        SolutionGuid = {2076F481-A5C7-4132-874E-47767C93475D}
    EndGlobalSection
EndGlobal

UPDATE:

It seems I now get this message every time I add a new project to Source Control. There seems to be something fundamentally going on here as I do not think I am referencing any external files, and I think my solution files show that. Note that even though I get this message, it still adds the solution to source control and everything seems to be working okay.

I do not have a command-line GIT program and would really prefer not to install anything else if there's any way to see what's going on without it.


问:
Lifespan of C# Assembly object instantiated by interface with Activator.CreateInstance
I'm experimenting with a plugin architecture using C# and dotnet. What I've discovered is that any instance created this way doesn't get collected until the application closes.

My original thought was to load each object and call a registration method, then allow it to die.  The registration method would pass back the information needed to know when it should be loaded in the future and create a new instance at that time.  This would prevent me from keeping 50 or so objects alive when not in use.

Putting a simple System.Diagnostics.Debug.Writeline in the constructor and finalizer of the classes this first loop through does not destroy any objects.  Only when I close the application do any finalizer calls happen. If I do an experiment where I have an internal IProduct instance and load several instances to that I get 5 constructor calls and once I close 5 finalizer calls.

For the below I created 2 different DLL's with 1 class each implementing the interface.  So I get a Class1 Constructor call and a Class2 Constructor call. But only get destructor calls when closing.

My initial expectations where that the finalizer would be called once the IProduct myDLL fell out of scope (iterating through/leaving the for loop) Or worst case the function itself.  This is pared down to have no data pass from the loaded dll to the main program to ensure I'm not keeping anything alive through hanging onto a reference, but I'm still seeing the same results.

```<code>    void LoadProductPlugins()
    {
        string[] sFiles = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\dll", "*.dll", SearchOption.TopDirectoryOnly);

        foreach (string strDll in sFiles)
        {
            Assembly assy = Assembly.LoadFile(strDll);

            Type[] types = (from t in assy.GetExportedTypes()
                                 where !t.IsInterface && !t.IsAbstract
                                 where typeof(IProduct).IsAssignableFrom(t)
                                 select t).ToArray();
            for (int i = 0; i < types.Length; i++)
            {
                IProduct myDLL = (IProduct) Activator.CreateInstance(types[i]);
            }
        }
    }
</code>```

答:
There is no difference in lifespan management of an object whether it is  created via regular new, CreateInstance or any other method one can come up with. An object will be collected when GC is needed and the particular object is no longer reachable.

Notes:

Finalizers are called only as part of full GC pass (Gen 2). This leads to behavior you see when finalizers are called at shutdown only because there is not enough memory usage to need GC earlier.

Assemblies themselves are not unloaded till they AppDomain is unloaded. Unless you are creating separate AppDomain for your plugins it means assembly will not be unloaded. You may want to read on assembly loading/versioning - Reading all posts around https://learn.microsoft.com/en-us/archive/blogs/suzcook/assembly-identity would save you a lot of time.

Body:
I'm experimenting with a plugin architecture using C# and dotnet. What I've discovered is that any instance created this way doesn't get collected until the application closes.

My original thought was to load each object and call a registration method, then allow it to die.  The registration method would pass back the information needed to know when it should be loaded in the future and create a new instance at that time.  This would prevent me from keeping 50 or so objects alive when not in use.

Putting a simple System.Diagnostics.Debug.Writeline in the constructor and finalizer of the classes this first loop through does not destroy any objects.  Only when I close the application do any finalizer calls happen. If I do an experiment where I have an internal IProduct instance and load several instances to that I get 5 constructor calls and once I close 5 finalizer calls.

For the below I created 2 different DLL's with 1 class each implementing the interface.  So I get a Class1 Constructor call and a Class2 Constructor call. But only get destructor calls when closing.

My initial expectations where that the finalizer would be called once the IProduct myDLL fell out of scope (iterating through/leaving the for loop) Or worst case the function itself.  This is pared down to have no data pass from the loaded dll to the main program to ensure I'm not keeping anything alive through hanging onto a reference, but I'm still seeing the same results.

    void LoadProductPlugins()
    {
        string[] sFiles = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\dll", "*.dll", SearchOption.TopDirectoryOnly);

        foreach (string strDll in sFiles)
        {
            Assembly assy = Assembly.LoadFile(strDll);

            Type[] types = (from t in assy.GetExportedTypes()
                                 where !t.IsInterface && !t.IsAbstract
                                 where typeof(IProduct).IsAssignableFrom(t)
                                 select t).ToArray();
            for (int i = 0; i < types.Length; i++)
            {
                IProduct myDLL = (IProduct) Activator.CreateInstance(types[i]);
            }
        }
    }


答:
let a = [
  ["i was sent", "i do"],
  ["i was sent", "i sent"],
  ["to protect you", "to find you"]
]

let result = a.map(x => x.join(" = "))
console.log(result)```

Title: create a new array from array of arrays