问:
Passport authenticate middleware with encrypted username using bcrypt
I am needing some assistance with how to use passport.authenticate() when the username has been encrypted using the NPM bcryptjs library.

For example, when I create a user I encrypt the username before using passport.js to create and save the user to MongoDB. Then in my route to log in, I pass in passport.authenticate("local") as the middleware which does all checking against the username and password.

In this scenario the username is actually the encrypted string, is there a way to use the passport.authenticate to check against the passed in username and an encrypted string?

Pieces of my code that make up the registration and login route.

```<code>userParam.username = bcrypt.hashSync(userParam.username);

        userModel.create(new userModel(userParam), userParam.password , (error) => {
            if (error) {
                response.Error = error;
                return Promise.resolve(response);
            }
        });

        //Save user
        passport.authenticate('local')(req, res, function () {
            req.session.save((error) => {
                if (error) {
                    response.Error = error;
                    return Promise.resolve(error);
                }
            });
        });
</code>```

Login route.

```<code>app.get('/api/user/login', passport.authenticate('local'), function (req, res) {
    req.session.save((err) => {
        if (err) {
            return res.json({ message: "Failed to sign in", err });
        }

        res.json({ status: "Signed In", authenticated: req.isAuthenticated(), user: req.user, session: req.session });
    });
});
</code>```

答:
Update:
I was able to dig deeper on the documentation for passport.js and I found that the passport.authenticate() was handled by the instance of passport.use(new LocalStrategy(...)). In that method, I was able to add my own custom logic to handle checking against an encrypted username.

Before I was just using

```<code>passport.use(new LocalStrategy(User.authenticate()));
</code>```

And I was able to update for my use case performing the following....

```<code>passport.use(new LocalStrategy(
            async function(username, password, done) {
              let allUsers = await User.find({});

              if(username.length == 7) {

                  for(var i = 0; i < allUsers.length; i++) {
                    if (bcrypt.compareSync(username, allUsers[i].username)) {
                        username = allUsers[i].username ;
                        break;
                    }
                  }
              }

              User.findOne({ username }, function (err, user) {
                if (err) {
                     return done(err);
                }
                if (!user) {
                  return done(null, false, { message: 'Incorrect username.' });
                }
                if (!password) {
                  return done(null, false, { message: 'Incorrect password.' });
                }
                return done(null, user);
              });
            }
          ));
    ```
```

Body:
I am needing some assistance with how to use passport.authenticate() when the username has been encrypted using the NPM bcryptjs library.

For example, when I create a user I encrypt the username before using passport.js to create and save the user to MongoDB. Then in my route to log in, I pass in passport.authenticate("local") as the middleware which does all checking against the username and password.

In this scenario the username is actually the encrypted string, is there a way to use the passport.authenticate to check against the passed in username and an encrypted string?

Pieces of my code that make up the registration and login route.

userParam.username = bcrypt.hashSync(userParam.username);

        userModel.create(new userModel(userParam), userParam.password , (error) => {
            if (error) {
                response.Error = error;
                return Promise.resolve(response);
            }
        });

        //Save user
        passport.authenticate('local')(req, res, function () {
            req.session.save((error) => {
                if (error) {
                    response.Error = error;
                    return Promise.resolve(error);
                }
            });
        });

Login route.

app.get('/api/user/login', passport.authenticate('local'), function (req, res) {
    req.session.save((err) => {
        if (err) {
            return res.json({ message: "Failed to sign in", err });
        }

        res.json({ status: "Signed In", authenticated: req.isAuthenticated(), user: req.user, session: req.session });
    });
});

Body:
Update:
I was able to dig deeper on the documentation for passport.js and I found that the passport.authenticate() was handled by the instance of passport.use(new LocalStrategy(...)). In that method, I was able to add my own custom logic to handle checking against an encrypted username.

Before I was just using

passport.use(new LocalStrategy(User.authenticate()));

And I was able to update for my use case performing the following....

passport.use(new LocalStrategy(
            async function(username, password, done) {
              let allUsers = await User.find({});

              if(username.length == 7) {

                  for(var i = 0; i < allUsers.length; i++) {
                    if (bcrypt.compareSync(username, allUsers[i].username)) {
                        username = allUsers[i].username ;
                        break;
                    }
                  }
              }

              User.findOne({ username }, function (err, user) {
                if (err) {
                     return done(err);
                }
                if (!user) {
                  return done(null, false, { message: 'Incorrect username.' });
                }
                if (!password) {
                  return done(null, false, { message: 'Incorrect password.' });
                }
                return done(null, user);
              });
            }
          ));
    ```


来源: stackexchange

问:
Duplicate arrays object value create as multi-dimensional array
I wanted to create filter from object, which passed from from, but there can be multiple values from filter form.
I want to pass an array to my filter and if theres multiple values, it can be multi-dimensional array.

For example, from form with serializeArray it's pass

```<code>0: {name: "holiday", value: "newyear"}
1: {name: "holiday", value: "christmas"}
2: {name: "startDate", value: ""}
3: {name: "genre", value: ""}
4: {name: "city", value: ""}
</code>```

But I wanted to create

```<code>0: {name: "holiday", value: {"christmas", "newyear"}}
1: {name: "startDate", value: ""}
2: {name: "genre", value: ""}
3: {name: "city", value: ""}
</code>```

And then pass it to filter() by my own rules and keys

I wanted to ask, how to validate, that there is multiple values with duplicate name property, and create new object.

答:
You can use reduce to group values in object and then get an array with Object.values.

const data = [{name: "holiday", value: "newyear"}, {name: "holiday", value: "christmas"}, {name: "startDate", value: ""}, {name: "genre", value: ""}, {name: "city", value: ""}]

const obj = data.reduce((r, e) => {
  if(!r[e.name]) r[e.name] = {...e}
  else r[e.name].value = [].concat(r[e.name].value, e.value)
  return r
}, {})

const result = Object.values(obj)
console.log(result)```

ContentLicense: CC BY-SA 4.0

Body:
I wanted to create filter from object, which passed from from, but there can be multiple values from filter form.
I want to pass an array to my filter and if theres multiple values, it can be multi-dimensional array.

For example, from form with serializeArray it's pass

0: {name: "holiday", value: "newyear"}
1: {name: "holiday", value: "christmas"}
2: {name: "startDate", value: ""}
3: {name: "genre", value: ""}
4: {name: "city", value: ""}

But I wanted to create

0: {name: "holiday", value: {"christmas", "newyear"}}
1: {name: "startDate", value: ""}
2: {name: "genre", value: ""}
3: {name: "city", value: ""}

And then pass it to filter() by my own rules and keys

I wanted to ask, how to validate, that there is multiple values with duplicate name property, and create new object.


问:
Jest Unit Tests on Teamcity
We have a Vue.js app that uses jest and jest teamcity reporter, the problem is when I run on teamcity I am getting below errors

```<code>  Trace: The node type SpreadProperty has been renamed to SpreadElement
      at Object.isSpreadProperty (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\types\lib\validators\generated\index.js:4304:11)
      at hasSpread (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\babel-plugin-transform-object-rest-spread\lib\index.js:38:13)
      at PluginPass.ObjectExpression (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\babel-plugin-transform-object-rest-spread\lib\index.js:234:14)
      at newFn (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\visitors.js:193:21)
      at NodePath._call (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:53:20)
      at NodePath.call (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:40:17)
      at NodePath.visit (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:88:12)
      at TraversalContext.visitQueue (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\context.js:118:16)
      at TraversalContext.visitMultiple (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\context.js:85:17)
      at TraversalContext.visit (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\context.js:144:19)
</code>```

My teamcity steps looks like below

Also If I run from cmd from the build agent directly, I can see tests running though,

Can anyone point what could be the issue ?

答:
This needs to be added in package.json file in order to identify and run unit tests under teamcity.</p>

```<code>"jest": {
    "testResultsProcessor": "jest-teamcity-reporter"
}
</code>```

Title: Jest Unit Tests on Teamcity

Body:
We have a Vue.js app that uses jest and jest teamcity reporter, the problem is when I run on teamcity I am getting below errors

  Trace: The node type SpreadProperty has been renamed to SpreadElement
      at Object.isSpreadProperty (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\types\lib\validators\generated\index.js:4304:11)
      at hasSpread (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\babel-plugin-transform-object-rest-spread\lib\index.js:38:13)
      at PluginPass.ObjectExpression (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\babel-plugin-transform-object-rest-spread\lib\index.js:234:14)
      at newFn (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\visitors.js:193:21)
      at NodePath._call (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:53:20)
      at NodePath.call (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:40:17)
      at NodePath.visit (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\path\context.js:88:12)
      at TraversalContext.visitQueue (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\context.js:118:16)
      at TraversalContext.visitMultiple (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\context.js:85:17)
      at TraversalContext.visit (D:\BuildAgent\work\87cb20bee7187581\SMA Web\SMA.Web\node_modules\@babel\core\node_modules\@babel\traverse\lib\context.js:144:19)

My teamcity steps looks like below

Also If I run from cmd from the build agent directly, I can see tests running though,

Can anyone point what could be the issue ?

Body:
This needs to be added in package.json file in order to identify and run unit tests under teamcity.

"jest": {
    "testResultsProcessor": "jest-teamcity-reporter"
}


问:
How extract Object with "{ }" from an string
I try to extract Object from bellow array :

```<code>var array = [];
array =
a,b,c,{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},c,b

</code>```

imagine extract this :

```<code>result = [
{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"}
         ]
</code>```

I use my code but didn't give me the right answer :

```<code>for (var i =0 ; i < array.length ; i++) {
   console.log((array[i].split(','));
}
</code>```

In this code I just get each variable in each line
I need more thing because in each time maybe I have different
array that has for example 2 Object in this example I just have
 3 Object.I try to define If I has any Object I can find them and push them in one array.

Body:
I try to extract Object from bellow array :

var array = [];
array =
a,b,c,{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},c,b

imagine extract this :

result = [
{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"}
         ]

I use my code but didn't give me the right answer :

for (var i =0 ; i < array.length ; i++) {
   console.log((array[i].split(','));
}

In this code I just get each variable in each line
I need more thing because in each time maybe I have different
array that has for example 2 Object in this example I just have
 3 Object.I try to define If I has any Object I can find them and push them in one array.

Body:
You can use Array.filter

var array = [];
array = [
'a','b','c',{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},'c','b'
        ];

 let result = array.filter(e => typeof e === 'object');
 console.log(result)


答:
You can use array reduce function. Inside reduce callback check if the type of the element is object then in accumulator array push the element

var array = [];
array = [
  'a', 'b', 'c', {
    "A": "0",
    "f": "1",
    "g": "2"
  }, {
    "B": "5",
    "v": "8",
    "x": "4"
  }, {
    "C": "0",
    "f": "1",
    "g": "2"
  },
  'c', 'b'
];

let newArr = array.reduce((acc, curr) => {

  if (typeof(curr) === 'object') {
    acc.push(curr)
  }
  return acc;
}, []);

console.log(newArr)```

Title: How extract Object with "{ }" from an string


问:
Which is the best way to check if a post meta value exists?
Up until recently, I've always used the following method to check if a post meta exists:

```<code>if(get_post_meta($post_id, 'example-key', true)) {
    echo get_post_meta($post_id, 'example-key', true);
}
</code>```

This of course provides a fallback if the key doesn't exist, but it also calls the same function twice. Is there any benefit of using this instead?

```<code>if(metadata_exists('post', '$post_id', 'example-key')) {
    echo get_post_meta($post_id, 'example-key', true);
}
</code>```

It seems that get_post_meta() will return the value of the key, and metadata_exists() will return a boolean. In terms of PHP performance, is one faster or more efficient than the other?

Should I stop using the first example, and use the second from now on?

答:
Generally to check the MetaData exists or not there is a ideal function given by wordpress. i.e :

```<code>metadata_exists( string $meta_type, int $object_id, string $meta_key )
</code>```

The same you are using is correct one i.e :

```<code>if(metadata_exists('post', '$post_id', 'example-key')) {
    echo get_post_meta($post_id, 'example-key', true);
}
</code>```

It determines, if a meta key is set for a given object.

Note : "metadata_exists" function returns directly the bool i.e true or false where as "get_post_meta" function returns the value may be an array id $single is set to "false" or Will return the value if $single is set to "true".
So, If as per my understanding the the "metadata_exists" time complexity is less than the other one.

Support Documents for the same :
Yes, you can check the following developer docs by wordpress.org (official), you will get the complete understanding of the same. .

```<code>1) get_post_meta   : https://developer.wordpress.org/reference/functions/get_post_meta/
2) metadata_exists : https://developer.wordpress.org/reference/functions/metadata_exists/
</code>```

Hope it helps..

Body:
Up until recently, I've always used the following method to check if a post meta exists:

if(get_post_meta($post_id, 'example-key', true)) {
    echo get_post_meta($post_id, 'example-key', true);
}

This of course provides a fallback if the key doesn't exist, but it also calls the same function twice. Is there any benefit of using this instead?

if(metadata_exists('post', '$post_id', 'example-key')) {
    echo get_post_meta($post_id, 'example-key', true);
}

It seems that get_post_meta() will return the value of the key, and metadata_exists() will return a boolean. In terms of PHP performance, is one faster or more efficient than the other?

Should I stop using the first example, and use the second from now on?

Body:
Generally to check the MetaData exists or not there is a ideal function given by wordpress. i.e :

metadata_exists( string $meta_type, int $object_id, string $meta_key )

The same you are using is correct one i.e :

if(metadata_exists('post', '$post_id', 'example-key')) {
    echo get_post_meta($post_id, 'example-key', true);
}

It determines, if a meta key is set for a given object.

Note : "metadata_exists" function returns directly the bool i.e true or false where as "get_post_meta" function returns the value may be an array id $single is set to "false" or Will return the value if $single is set to "true".
So, If as per my understanding the the "metadata_exists" time complexity is less than the other one.

Support Documents for the same :
Yes, you can check the following developer docs by wordpress.org (official), you will get the complete understanding of the same. .

1) get_post_meta   : https://developer.wordpress.org/reference/functions/get_post_meta/
2) metadata_exists : https://developer.wordpress.org/reference/functions/metadata_exists/

Hope it helps..


问:
Images Not Stacking - HTML & CSS
I have an html page that contains "links" to many sections of the page. I'm using a single page layout where if a link is clicked, you are not actually taken to a new page. Instead you are taken to the section of the page that you clicked on in the nav bar. I have a section for 6 images, each with a caption. I need the images to be in 2 rows with 3 images per row without using a table.(each image with its caption underneath) But I also need them to be responsive, so if the size of the browser is minimized then the images stack up on each other (caption still there). I tried using padding and margins but I wasn't able to get it to work so I don't have any CSS to post but I do have my HTML code. Can someone please help me out? Here is my code:</p>

```<code>         <div class="allimagesgallery">

                <a href="images/image1.jpg">
                    <img id="galleryimages" src="images/image1.jpg">
                </a>
                <div class="caption">CAPTION.</div>

                <a  href="images/image2.jpeg">
                    <img id="galleryimages" src="images/image2.jpeg">
                </a>
                <div class="caption"> CAPTION </div>

                <a  href="images/image3.jpg">
                    <img id="galleryimages" src="images/image3.jpg">
                </a>
                <div class="caption"> CAPTION </div>

                <a href="images/image4.jpg">
                    <img id="galleryimages" src="images/image4.jpg">
                </a>
                <div class="caption">CAPTION</div>

                <a href="images/image5.jpeg">
                    <img id="galleryimages" src="images/image5.jpeg">
                </a>
                <div class="caption"> CAPTION </div>

                <a href="images/image6.jpeg">
                    <img id="galleryimages" src="images/image6.jpeg">
                </a>
                <div class="caption"> CAPTION </div>

    </div>

    </div>
</code>```

答:
it would help us if we knew what your css in "allimagesgallery" looked like.

A little reformatting like the code below might help:

```<code>/*-----css---------*/
.imagesgalleryrow img{
display: inline-block;
}

<!-- /// HTML  \\\  -->
<div class="allimagesgallery">

    <div class="imagesgalleryrow">

        <a href="images/image1.jpg">
            <img id="galleryimages" src="images/image1.jpg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image2.jpeg">
            <img id="galleryimages" src="images/image2.jpeg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image3.jpg">
            <img id="galleryimages" src="images/image3.jpg">
        </a>
        <div class="caption"> CAPTION </div>

    </div>

    <div class="imagesgalleryrow">

        <a href="images/image1.jpg">
            <img id="galleryimages" src="images/image1.jpg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image2.jpeg">
            <img id="galleryimages" src="images/image2.jpeg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image3.jpg">
            <img id="galleryimages" src="images/image3.jpg">
        </a>
        <div class="caption"> CAPTION </div>

    </div>

    <div class="imagesgalleryrow">

        <a href="images/image1.jpg">
            <img id="galleryimages" src="images/image1.jpg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image2.jpeg">
            <img id="galleryimages" src="images/image2.jpeg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image3.jpg">
            <img id="galleryimages" src="images/image3.jpg">
        </a>
        <div class="caption"> CAPTION </div>

    </div>
</div>
</code>```

Title: Images Not Stacking - HTML & CSS

Body:
I have an html page that contains "links" to many sections of the page. I'm using a single page layout where if a link is clicked, you are not actually taken to a new page. Instead you are taken to the section of the page that you clicked on in the nav bar. I have a section for 6 images, each with a caption. I need the images to be in 2 rows with 3 images per row without using a table.(each image with its caption underneath) But I also need them to be responsive, so if the size of the browser is minimized then the images stack up on each other (caption still there). I tried using padding and margins but I wasn't able to get it to work so I don't have any CSS to post but I do have my HTML code. Can someone please help me out? Here is my code:

CAPTION.

 CAPTION

 CAPTION

CAPTION

 CAPTION

 CAPTION

Body:
it would help us if we knew what your css in "allimagesgallery" looked like.

A little reformatting like the code below might help:

/*-----css---------*/
.imagesgalleryrow img{
display: inline-block;
}

<!-- /// HTML  \\\  -->
<div class="allimagesgallery">

    <div class="imagesgalleryrow">

        <a href="images/image1.jpg">
            <img id="galleryimages" src="images/image1.jpg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image2.jpeg">
            <img id="galleryimages" src="images/image2.jpeg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image3.jpg">
            <img id="galleryimages" src="images/image3.jpg">
        </a>
        <div class="caption"> CAPTION </div>

    </div>

    <div class="imagesgalleryrow">

        <a href="images/image1.jpg">
            <img id="galleryimages" src="images/image1.jpg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image2.jpeg">
            <img id="galleryimages" src="images/image2.jpeg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image3.jpg">
            <img id="galleryimages" src="images/image3.jpg">
        </a>
        <div class="caption"> CAPTION </div>

    </div>

    <div class="imagesgalleryrow">

        <a href="images/image1.jpg">
            <img id="galleryimages" src="images/image1.jpg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image2.jpeg">
            <img id="galleryimages" src="images/image2.jpeg">
        </a>
        <div class="caption"> CAPTION </div>

        <a  href="images/image3.jpg">
            <img id="galleryimages" src="images/image3.jpg">
        </a>
        <div class="caption"> CAPTION </div>

    </div>
</div>


问:
Minimum android tablet size information needed
I want to develop application with single binary for Android device and for Android tablets with target android 2.1 version.

My orientation also depends upon whether app is running on device or on tablet.

So i just want to know, is there any specification like tablet should be minimum of "X" inches.

答:
My orientation also depends upon whether app is running on device or on tablet.

Your application should depend on whether the screen is small, normal, large, or xlarge. There is no concept of "device or on tablet" in Android.

is there any specification like tablet should be minimum of "X" inches.

There is no concept of "tablet" in Android. What a user will think of as a "tablet" will tend to be large or xlarge screen size.

ContentLicense: CC BY-SA 3.0


问:
How to simply load images with src attribute with webpack 4?
Im stuck and can't get to work my webpack configuration for loading images with src attribute from HTML. I cloned a repo with full setup of webpack, but I know there is a way to simply customize and load images directly from HTML.

Webpack.config.js file:

```<code>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
entry: {
main: "./src/index.js"
},
output: {
path: path.join(__dirname, "../build"),
filename: "[name].bundle.js"
},
mode: "development",
devServer: {
contentBase: path.join(__dirname, "../build"),
compress: true,
port: 3000,
overlay: true
},
devtool: "cheap-module-eval-source-map",
module: {
 rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
      loader: "babel-loader" // transpiling our JavaScript files using Babel and webpack
    }
  },
  {
    test: /\.(sa|sc|c)ss$/,
    use: [
      "style-loader", // creates style nodes from JS strings
      "css-loader", // translates CSS into CommonJS
      "postcss-loader", // Loader for webpack to process CSS with PostCSS
      "sass-loader" // compiles Sass to CSS, using Node Sass by default
    ]
  },
  {
    test: /\.(png|svg|jpe?g|gif)$/,
    use: [
      {
        loader: "file-loader", // This will resolves import/require() on a file into a url
and emits the file into the output directory.
        options: {
          name: "[name].[ext]",
          outputPath: "assets",
        }
      },
    ]
  },
  {
    test: /\.html$/,
    use: {
      loader: "html-loader",
      options: {
        attrs: ["img:src", ":data-src"],
        minimize: true
      }
    }
  }
]
},

plugins: [
  // CleanWebpackPlugin will do some clean up/remove folder before build
  // In this case, this plugin will remove 'dist' and 'build' folder before re-build again
  new CleanWebpackPlugin(),
  // The plugin will generate an HTML5 file for you that includes all your webpack bundles
in
the body using script tags
new HtmlWebpackPlugin({
  template: "./src/index.html",
  filename: "index.html"
}),
</code>```

Before this project I was able to make that images would simply load from HTML but now ironicly im stuck and can't get this working.

Any help will be very appriciated.

When loading a image directly form HTML, I get the following error:

```<code> Error: Child compilation failed:
 Module not found: Error: Can't resolve '
 ./src/assets/images/portret.jpg' in '/home/viktoras/www/sites/painter-new/src':
</code>```

答:
You can do this:</p>

```<code><img src="<%=require('./src/assets/logo.png')%>">

    Plugin Conf
    $new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html'
      }),
</code>```

Body:
Im stuck and can't get to work my webpack configuration for loading images with src attribute from HTML. I cloned a repo with full setup of webpack, but I know there is a way to simply customize and load images directly from HTML.

Webpack.config.js file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
entry: {
main: "./src/index.js"
},
output: {
path: path.join(__dirname, "../build"),
filename: "[name].bundle.js"
},
mode: "development",
devServer: {
contentBase: path.join(__dirname, "../build"),
compress: true,
port: 3000,
overlay: true
},
devtool: "cheap-module-eval-source-map",
module: {
 rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
      loader: "babel-loader" // transpiling our JavaScript files using Babel and webpack
    }
  },
  {
    test: /\.(sa|sc|c)ss$/,
    use: [
      "style-loader", // creates style nodes from JS strings
      "css-loader", // translates CSS into CommonJS
      "postcss-loader", // Loader for webpack to process CSS with PostCSS
      "sass-loader" // compiles Sass to CSS, using Node Sass by default
    ]
  },
  {
    test: /\.(png|svg|jpe?g|gif)$/,
    use: [
      {
        loader: "file-loader", // This will resolves import/require() on a file into a url
and emits the file into the output directory.
        options: {
          name: "[name].[ext]",
          outputPath: "assets",
        }
      },
    ]
  },
  {
    test: /\.html$/,
    use: {
      loader: "html-loader",
      options: {
        attrs: ["img:src", ":data-src"],
        minimize: true
      }
    }
  }
]
},

plugins: [
  // CleanWebpackPlugin will do some clean up/remove folder before build
  // In this case, this plugin will remove 'dist' and 'build' folder before re-build again
  new CleanWebpackPlugin(),
  // The plugin will generate an HTML5 file for you that includes all your webpack bundles
in
the body using script tags
new HtmlWebpackPlugin({
  template: "./src/index.html",
  filename: "index.html"
}),

Before this project I was able to make that images would simply load from HTML but now ironicly im stuck and can't get this working.

Any help will be very appriciated.

When loading a image directly form HTML, I get the following error:

 Error: Child compilation failed:
 Module not found: Error: Can't resolve '
 ./src/assets/images/portret.jpg' in '/home/viktoras/www/sites/painter-new/src':

Body:
You can do this:

<img src="<%=require('./src/assets/logo.png')%>">

    Plugin Conf
    $new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html'
      }),


问:
Get current working directory in terraform
I am running Terraform using Terragrunt so I am not actually certain about the path that the terraform is invoked from.

So I am trying to get the current working directory as follows:

```<code>resource null_resource "pwd" {
  triggers {
    always_run = "${uuid()}"
  }
  provisioner "local-exec" {
    command = "echo $pwd >> somefile.txt"
  }
}
</code>```

However the resulting file is empty.

Any suggestions?

答:
Try
command = "echo $(pwd) > somefile.txt"

Body:
I am running Terraform using Terragrunt so I am not actually certain about the path that the terraform is invoked from.

So I am trying to get the current working directory as follows:

resource null_resource "pwd" {
  triggers {
    always_run = "${uuid()}"
  }
  provisioner "local-exec" {
    command = "echo $pwd >> somefile.txt"
  }
}

However the resulting file is empty.

Any suggestions?


问:
How to make Google Sheets auto update my macros after adding row?
Problem:
After adding a row in my Google Sheet my existing macros stop working because the cells they refer to are now shifted one row.

Question:
Is there a way to make Google Sheets auto update my macros just like it updates all the functions in the sheet?

答:
Use PropertiesService and onChange trigger

PropertiesService allows you to store a variable (like  the row of interest) between script runs

The installable trigger onChange fires automatically when a change (such as row insertion) has taken place

You can set-up the latter to modify the row of interest if another row has been inserted above

Sample:

```<code>var sheetToWatch = "Sheet1";

function setUp(){
  PropertiesService.getScriptProperties().setProperty("row", 4);
}

function onChange(e) {
  var row = parseInt(PropertiesService.getScriptProperties().getProperty("row"));
  var sheet = SpreadsheetApp.getActive().getActiveSheet();
  Logger.log(e.changeType);
  Logger.log(sheet.getName());
  Logger.log(sheetToWatch);
  Logger.log(sheet.getActiveRange().getRow());
  if (e.changeType == "INSERT_ROW"  &&  sheet.getName() == sheetToWatch && sheet.getActiveRange().getRow()<=row){
    row++;
  }
}

function withRow(){
  var row = parseInt(PropertiesService.getScriptProperties().getProperty("row"));
  // do something with my row
}
</code>```

Instructions:

Run fucntion setUp() once to set the initial row

If rows above this row will be inserted, onChange() will change the var row automatically (do not forget to bind an installable trigger to onChange() )

Run your own function (called here withRow()) and retrieve the actual row from ScripProperties

Body:
Use PropertiesService and onChange trigger

PropertiesService allows you to store a variable (like  the row of interest) between script runs

The installable trigger onChange fires automatically when a change (such as row insertion) has taken place

You can set-up the latter to modify the row of interest if another row has been inserted above

Sample:

var sheetToWatch = "Sheet1";

function setUp(){
  PropertiesService.getScriptProperties().setProperty("row", 4);
}

function onChange(e) {
  var row = parseInt(PropertiesService.getScriptProperties().getProperty("row"));
  var sheet = SpreadsheetApp.getActive().getActiveSheet();
  Logger.log(e.changeType);
  Logger.log(sheet.getName());
  Logger.log(sheetToWatch);
  Logger.log(sheet.getActiveRange().getRow());
  if (e.changeType == "INSERT_ROW"  &&  sheet.getName() == sheetToWatch && sheet.getActiveRange().getRow()<=row){
    row++;
  }
}

function withRow(){
  var row = parseInt(PropertiesService.getScriptProperties().getProperty("row"));
  // do something with my row
}

Instructions:

Run fucntion setUp() once to set the initial row

If rows above this row will be inserted, onChange() will change the var row automatically (do not forget to bind an installable trigger to onChange() )

Run your own function (called here withRow()) and retrieve the actual row from ScripProperties


问:
Add props from parent component in map() function from child component
I have 2 components. Parent and child.
This is my child component:

import React, {useState, useEffect} from 'react';

const Users = (props) => {
    const [users, setUsers] = useState([]);
    let [respo, setA] = useState('name');
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://api.github.com/users/hadley/repos`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        setUsers(data)
        // console.log(res)
    };
    fetchData();
    function mapping() {
        return (
            users.map((i, k) =>
{i.props.details}
)
        )
    }

    return (

                {mapping()}

    );
};

export default Users;```
</div>
</div>
</p>

<p>In my parent component i send a prop to  child:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> <Tabs type="card">
 <TabPane tab="Tab Title 1" key="1">
 <Users details="name"/>
 </TabPane>
<TabPane tab="Tab Title 2" key="2">
 <Users details="id"/>
 </TabPane>
 <TabPane tab="Tab Title 3" key="3">
</Tabs></code>```

I tried to access the props like here: users.map((i, k) =>
{i.props.details}
) Why i cant access  the props from parent in map() function?

答:
You're using props incorrectly, use it like :

```<code>{props.details}
</code>```

users is array you got from the api call and its items don't have props in them, if you want to access props in mapping function you should access it directly as I did above as it is available to mapping function through closure

Body:
I have 2 components. Parent and child.
This is my child component:

import React, {useState, useEffect} from 'react';

const Users = (props) => {
    const [users, setUsers] = useState([]);
    let [respo, setA] = useState('name');
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://api.github.com/users/hadley/repos`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        setUsers(data)
        // console.log(res)
    };
    fetchData();
    function mapping() {
        return (
            users.map((i, k) =>
{i.props.details}
)
        )
    }

    return (

                {mapping()}

    );
};

export default Users;

In my parent component i send a prop to  child:

 <Tabs type="card">
 <TabPane tab="Tab Title 1" key="1">
 <Users details="name"/>
 </TabPane>
<TabPane tab="Tab Title 2" key="2">
 <Users details="id"/>
 </TabPane>
 <TabPane tab="Tab Title 3" key="3">
</Tabs>

I tried to access the props like here: users.map((i, k) =>
{i.props.details}
) Why i cant access  the props from parent in map() function?

Body:
You're using props incorrectly, use it like :

{props.details}

users is array you got from the api call and its items don't have props in them, if you want to access props in mapping function you should access it directly as I did above as it is available to mapping function through closure


问:
Executing DB2 commands '' db2start: command not found ''
I have one virtual server running on centos7. I configure it for the Nagios monitoring tool. I created the config file etc. I have 9 DB instances. When I migrated the DB config file with Nagios(adding to the Nagios )

I saw this error code on http://mysiteipaddr/nagios

CRITICAL - cannot connect to db.ipaddress.com. install_driver(DB2) failed: Can't locate DBD/DB2.pm in @INC (@INC contains: /usr/local/nagios/libexec /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 10) line 3.

After this error, I realize the DB2 is not installed on my machine. I've installed the DB2 drivers and when I execute this command I'm facing this output.

```<code> db2ls
-------------------------------------------------------------------------------------------------------------------
/opt/ibm/db2/V9.7                11.1.1.1        1                            Fri Jan 31 11:33:28 2020 +03             0
[root@backup ~]#
</code>```

But when I want to execute DB2 command like db2start, db2stop, db2status, it won't execute and I got this error code.

```<code>bash: db2stop: command not found
bash: db2start:command not found
</code>```

答:
Install below package in all of the instances:

yum -y install perl-CPAN

hope so this will be helpful for you....!!!!

Body:
I have one virtual server running on centos7. I configure it for the Nagios monitoring tool. I created the config file etc. I have 9 DB instances. When I migrated the DB config file with Nagios(adding to the Nagios )

I saw this error code on http://mysiteipaddr/nagios

CRITICAL - cannot connect to db.ipaddress.com. install_driver(DB2) failed: Can't locate DBD/DB2.pm in @INC (@INC contains: /usr/local/nagios/libexec /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 10) line 3.

After this error, I realize the DB2 is not installed on my machine. I've installed the DB2 drivers and when I execute this command I'm facing this output.

 db2ls
-------------------------------------------------------------------------------------------------------------------
/opt/ibm/db2/V9.7                11.1.1.1        1                            Fri Jan 31 11:33:28 2020 +03             0
[root@backup ~]#

But when I want to execute DB2 command like db2start, db2stop, db2status, it won't execute and I got this error code.

bash: db2stop: command not found
bash: db2start:command not found


问:
How not to keep the state of a checkbox through the history?
I'm using a checkbox to create a mobile menu. Simplified, it looks like that:

input, ul {
  display: none;
}
label {
  cursor: pointer;
}
input:checked ~ ul {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="toggle-menu" />
<label for="toggle-menu">Menu</label>
<ul>
  <li>Link</li>
</ul></code>```

It works well, except for a thing: when the user navigates in another page using the menu, and then go back is the history, the checkbox state is kept, and thus the menu is displayed.

Is it possible to prevent this, preferably without Javascript? To say it in another words, I'd like the menu to never be displayed when a page is accessed to, even through the navigation in the history. The user must click on the label to see the menu.

答:
Try autocomplete off. https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion</p>

```<code><input type="checkbox" id="toggle-menu" autocomplete="off"/>
</code>```

Body:
I'm using a checkbox to create a mobile menu. Simplified, it looks like that:

input, ul {
  display: none;
}
label {
  cursor: pointer;
}
input:checked ~ ul {
  display: block;
}

<input type="checkbox" id="toggle-menu" />
Menu

Link

It works well, except for a thing: when the user navigates in another page using the menu, and then go back is the history, the checkbox state is kept, and thus the menu is displayed.

Is it possible to prevent this, preferably without Javascript? To say it in another words, I'd like the menu to never be displayed when a page is accessed to, even through the navigation in the history. The user must click on the label to see the menu.

Body:
Try autocomplete off. https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion

<input type="checkbox" id="toggle-menu" autocomplete="off"/>


问:
Chocolatey Install Package Failing
For those who are familiar with creating Chocolatey packages, can someone offer help to why this one isn't working? It packs, but when I test (install only package), it won't work.
Here is the chocolateyinstall.ps1 file:

```<code>$ErrorActionPreference = 'Stop'; # stop on all errors
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$fileLocation = Join-Path $toolsDir 'armcc.exe'
$packagename = 'ARM_RVCT'

$packageArgs = @{
  packageName   = $packageName
  unzipLocation = $toolsDir
  fileType      = 'EXE' #only one of these: exe, msi, msu
  #url           = $url
  #url64bit      = $url64
  file         = $fileLocation

  softwareName  = 'ARM_RVCT*' #part or all of the Display Name as you see it in Programs and Features. It should be enough to be unique

  silentArgs    = '/S' # ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0
  validExitCodes= @(0)
}

Install-ChocolateyInstallPackage @packageArgs # https://chocolatey.org/docs/helpers-install-chocolatey-install-package
</code>```

When I do choco pack and then run choco install arm_rvct, I get this output:

```<code>Installing the following packages:
arm_rvct
By installing you accept licenses for the packages.

arm_rvct v3.1
arm_rvct package files install completed. Performing other installation steps.
Installing ARM_RVCT...
Microsoft.PowerShell.Commands.WriteErrorException
Error: C3079E: armcc command with no effect
Error: C3065E: type of input file '/S' unknown
Microsoft.PowerShell.Commands.WriteErrorException
ERROR: Running ["C:\ProgramData\chocolatey\lib\arm_rvct\tools\armcc.exe" /S ] was not successful. Exit code was '1'. See log for possible error messages.
The install of arm_rvct was NOT successful.
Error while running 'C:\ProgramData\chocolatey\lib\arm_rvct\tools\chocolateyinstall.ps1'.
 See log for details.

Chocolatey installed 0/1 packages. 1 packages failed.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Failures
 - arm_rvct (exited 1) - Error while running 'C:\ProgramData\chocolatey\lib\arm_rvct\tools\chocolateyinstall.ps1'.
 See log for details.
</code>```

答:
It tells you exactly what the problem is in the error message:

```<code>Error: C3079E: armcc command with no effect
Error: C3065E: type of input file '/S' unknown
</code>```

First, it looks like you might be commenting out, or at the very least, not providing required parameters for armcc.exe. Second, it looks like /S in the context of armcc.exe isn't for a silent install - it wants an input file which you are not currently providing as part of your silent args.

armcc.exe isn't an installer btw - if you don't have a proper installer for your toolchain, consider putting the toolchain in a zip archive, embedding that zip in your package, and then install with Install-ChocolateyZipPackage instead of Install-ChocolateyInstallPackage (the latter is for installing exe or msi installers).

This should automatically generate some shims for your executables and place them on the path. Note that since this looks like it's for the arm_rvct compiler, if that normally accepts pipeline input, Chocolatey shims actually do not support pipeline input, so keep that limitation with generated shims in mind.

It does look like there is an official installer for the ARM toolchain. However, the installation instructions in the release notes don't provide any silent install instructions. That said, this is a common problem with undocumented installers - but it doesn't mean that you can't perform a silent install either, with some effort on your side.

You can either try running setup.exe /S or the referenced ARM Compiler 6.13.msi with msiexec /i "ARM Compiler 6.13.msi" /qn. If neither of these work, you have the options of reaching out to the vendor to ask how silent installs work, or you can go the route of taking the installed files and packaging them into a zip. Note that installers, especially for devkits and toolchains, may register assemblies in Windows and this can get complicated to reverse engineer if a simple file install doesn't work.

In this case though, the vendor would be the best resource to understand how you are able to deploy this package throughout your organization.

Title: Chocolatey Install Package Failing

Body:
For those who are familiar with creating Chocolatey packages, can someone offer help to why this one isn't working? It packs, but when I test (install only package), it won't work.
Here is the chocolateyinstall.ps1 file:

$ErrorActionPreference = 'Stop'; # stop on all errors
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$fileLocation = Join-Path $toolsDir 'armcc.exe'
$packagename = 'ARM_RVCT'

$packageArgs = @{
  packageName   = $packageName
  unzipLocation = $toolsDir
  fileType      = 'EXE' #only one of these: exe, msi, msu
  #url           = $url
  #url64bit      = $url64
  file         = $fileLocation

  softwareName  = 'ARM_RVCT*' #part or all of the Display Name as you see it in Programs and Features. It should be enough to be unique

  silentArgs    = '/S' # ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0
  validExitCodes= @(0)
}

Install-ChocolateyInstallPackage @packageArgs # https://chocolatey.org/docs/helpers-install-chocolatey-install-package

When I do choco pack and then run choco install arm_rvct, I get this output:

Installing the following packages:
arm_rvct
By installing you accept licenses for the packages.

arm_rvct v3.1
arm_rvct package files install completed. Performing other installation steps.
Installing ARM_RVCT...
Microsoft.PowerShell.Commands.WriteErrorException
Error: C3079E: armcc command with no effect
Error: C3065E: type of input file '/S' unknown
Microsoft.PowerShell.Commands.WriteErrorException
ERROR: Running ["C:\ProgramData\chocolatey\lib\arm_rvct\tools\armcc.exe" /S ] was not successful. Exit code was '1'. See log for possible error messages.
The install of arm_rvct was NOT successful.
Error while running 'C:\ProgramData\chocolatey\lib\arm_rvct\tools\chocolateyinstall.ps1'.
 See log for details.

Chocolatey installed 0/1 packages. 1 packages failed.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Failures
 - arm_rvct (exited 1) - Error while running 'C:\ProgramData\chocolatey\lib\arm_rvct\tools\chocolateyinstall.ps1'.
 See log for details.

Body:
It tells you exactly what the problem is in the error message:

Error: C3079E: armcc command with no effect
Error: C3065E: type of input file '/S' unknown

First, it looks like you might be commenting out, or at the very least, not providing required parameters for armcc.exe. Second, it looks like /S in the context of armcc.exe isn't for a silent install - it wants an input file which you are not currently providing as part of your silent args.

armcc.exe isn't an installer btw - if you don't have a proper installer for your toolchain, consider putting the toolchain in a zip archive, embedding that zip in your package, and then install with Install-ChocolateyZipPackage instead of Install-ChocolateyInstallPackage (the latter is for installing exe or msi installers).

This should automatically generate some shims for your executables and place them on the path. Note that since this looks like it's for the arm_rvct compiler, if that normally accepts pipeline input, Chocolatey shims actually do not support pipeline input, so keep that limitation with generated shims in mind.

It does look like there is an official installer for the ARM toolchain. However, the installation instructions in the release notes don't provide any silent install instructions. That said, this is a common problem with undocumented installers - but it doesn't mean that you can't perform a silent install either, with some effort on your side.

You can either try running setup.exe /S or the referenced ARM Compiler 6.13.msi with msiexec /i "ARM Compiler 6.13.msi" /qn. If neither of these work, you have the options of reaching out to the vendor to ask how silent installs work, or you can go the route of taking the installed files and packaging them into a zip. Note that installers, especially for devkits and toolchains, may register assemblies in Windows and this can get complicated to reverse engineer if a simple file install doesn't work.

In this case though, the vendor would be the best resource to understand how you are able to deploy this package throughout your organization.


答:
Group by name and then extract the grouped values.

let arr =[{name: "holiday", value: "newyear"},{name: "holiday", value: "christmas"},{name: "startDate", value: ""},{name: "genre", value: ""},{name: "city", value: ""}],
    result = Object.values(arr.reduce((a, {name, value: v}) => {
      (a[name] || (a[name] = {name, value: []})).value.push(v);
      return a;
    }, {}));

console.log(result);```

Title: Duplicate arrays object value create as multi-dimensional array

Body:
I wanted to create filter from object, which passed from from, but there can be multiple values from filter form.
I want to pass an array to my filter and if theres multiple values, it can be multi-dimensional array.

For example, from form with serializeArray it's pass

0: {name: "holiday", value: "newyear"}
1: {name: "holiday", value: "christmas"}
2: {name: "startDate", value: ""}
3: {name: "genre", value: ""}
4: {name: "city", value: ""}

But I wanted to create

0: {name: "holiday", value: {"christmas", "newyear"}}
1: {name: "startDate", value: ""}
2: {name: "genre", value: ""}
3: {name: "city", value: ""}

And then pass it to filter() by my own rules and keys

I wanted to ask, how to validate, that there is multiple values with duplicate name property, and create new object.


问:
Passenger apache default page error
I asked this a couple of days ago on Server Fault but am getting no responses and little interest. Since it is related to setting up a dev environment I thought the SO community might be able to help me out...

I just installed Passenger and the Passenger Pref Pane on OSX. However, when I try to browse to one of my Rails applications I just get the default Apache "it works!" page.

I've checked the vhost definitions and they seem ok so I can't seem to figure out whats wrong... I've tried reinstalling passenger and the pref pane and restarting apache but to no avail.

Anyone know how to fix this?

My vhost definition looks like this:

```<code><VirtualHost *:80>
  ServerName boilinghot.local
  DocumentRoot "/Users/ganesh/Code/boilinghot/public"
  RailsEnv development
  <Directory "/Users/ganesh/Code/boilinghot/public">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>
</code>```

答:
I had a similar issue. It was solved after I have disabled default page:</p>

```<code>sudo a2dissite 000-default
sudo /etc/init.d/apache2 reload
</code>```

ContentLicense: CC BY-SA 2.5

Title: Passenger apache default page error

Body:
I asked this a couple of days ago on Server Fault but am getting no responses and little interest. Since it is related to setting up a dev environment I thought the SO community might be able to help me out...

I just installed Passenger and the Passenger Pref Pane on OSX. However, when I try to browse to one of my Rails applications I just get the default Apache "it works!" page.

I've checked the vhost definitions and they seem ok so I can't seem to figure out whats wrong... I've tried reinstalling passenger and the pref pane and restarting apache but to no avail.

Anyone know how to fix this?

My vhost definition looks like this:

<VirtualHost *:80>
  ServerName boilinghot.local
  DocumentRoot "/Users/ganesh/Code/boilinghot/public"
  RailsEnv development
  <Directory "/Users/ganesh/Code/boilinghot/public">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Body:
I had a similar issue. It was solved after I have disabled default page:

sudo a2dissite 000-default
sudo /etc/init.d/apache2 reload


问:
Convert git full clone into a shallow clone
How can a deep clone of a repository be turned into a shallow copy IN PLACE?

I am managing separate installations of our software using git to track any changes to the code in the installation made runtime (untracked & dirty files), but the repository is pretty large (800MB), so having about a few hundreds of copies laying around is not the best idea.

So it would be great if these repositories could be turned into a shallow copy containing only the currently deployed commit, rather than the full tree.
During an upgrade the repo would be converted back to a deep clone, the specific commit checked out, and then made into a shallow clone of the new commit.

git fetch --depth=1 --update-shallow does not shrink the .git directory size, I guess it would fetch any new commits, but it doesn't delete the old data. Adding --shallow-exclude=HEAD^2 makes git throw an error, not entirely sure how that should work though, I would hazard a guess it's getting conflicting requirements removing HEAD^2, but wanting to check out HEAD, which would depend on HEAD^2 in a deep clone.

```<code>error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
</code>```

答:
Ok, so this was the solution in the end:</p>

```<code>ORIGIN_URL=$(git remote get-url origin)
COMMIT=$(git rev-parse HEAD)

rm -rf .git
git init .
git remote add origin $ORIGIN_URL
git fetch origin $COMMIT --depth 1
git reset --mixed $COMMIT
</code>```

Body:
How can a deep clone of a repository be turned into a shallow copy IN PLACE?

I am managing separate installations of our software using git to track any changes to the code in the installation made runtime (untracked & dirty files), but the repository is pretty large (800MB), so having about a few hundreds of copies laying around is not the best idea.

So it would be great if these repositories could be turned into a shallow copy containing only the currently deployed commit, rather than the full tree.
During an upgrade the repo would be converted back to a deep clone, the specific commit checked out, and then made into a shallow clone of the new commit.

git fetch --depth=1 --update-shallow does not shrink the .git directory size, I guess it would fetch any new commits, but it doesn't delete the old data. Adding --shallow-exclude=HEAD^2 makes git throw an error, not entirely sure how that should work though, I would hazard a guess it's getting conflicting requirements removing HEAD^2, but wanting to check out HEAD, which would depend on HEAD^2 in a deep clone.

error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly

Body:
Ok, so this was the solution in the end:

ORIGIN_URL=$(git remote get-url origin)
COMMIT=$(git rev-parse HEAD)

rm -rf .git
git init .
git remote add origin $ORIGIN_URL
git fetch origin $COMMIT --depth 1
git reset --mixed $COMMIT


问:
fav icon in index.html file not work in vuejs
fav icon does not display in file in index.html in vue.js project despite of the correct path ?</p>

```<code> <meta charset="utf-8">
    <link rel="icon" href="./src/assets/images/logo.png" type="image/png" sizes="96x96">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <title>demo</title>
  </head>
</code>```

答: Assuming your index.html is located in your public directory, your favicon logo image should also be located inside the public directory since everything on src/ is not actually being served but compiled by webpack and therefore not accessible to the index.html file.</p>

Body:
fav icon does not display in file in index.html in vue.js project despite of the correct path ?

 <meta charset="utf-8">
    <link rel="icon" href="./src/assets/images/logo.png" type="image/png" sizes="96x96">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <title>demo</title>


问:
Configuring codecov token in GitHub Actions .yaml for an R package
I'm trying to set up codecov monitoring for a public R package, where GitHub Actions will run covr::codecov.  I'm looking at this .yaml example (Source):

```<code>  - name: Test coverage
    if: matrix.r == '3.6'
    run: |
      Rscript -e 'remotes::install_github("r-lib/covr@gh-actions")'
      Rscript -e 'covr::codecov(token = "${{secrets.CODECOV_TOKEN}}")'
</code>```

Is it safe for me to put my codecov token in the .yaml file in place of where the above example has CODECOV_TOKEN?

答:
No, don't put the token in the .yaml file.  For use with GitHub Actions, you add the token to the Secrets section of your GitHub repository, then leave the .yaml code above as it is.

Add the secret at the URL (modify with your names): https://github.com/USERNAME/REPONAME/settings/secrets and call it CODECOV_TOKEN.  Then this .yaml code will find it.

(You get the repo's codecov token from https://codecov.io/gh/USERNAME/REPONAME)

Body:
I'm trying to set up codecov monitoring for a public R package, where GitHub Actions will run covr::codecov.  I'm looking at this .yaml example (Source):

  - name: Test coverage
    if: matrix.r == '3.6'
    run: |
      Rscript -e 'remotes::install_github("r-lib/covr@gh-actions")'
      Rscript -e 'covr::codecov(token = "${{secrets.CODECOV_TOKEN}}")'

Is it safe for me to put my codecov token in the .yaml file in place of where the above example has CODECOV_TOKEN?


问:
Use copy() to populate an immutable field
I have a data class with 3 fields on val type.

```<code>data class Person(
    val id: UUID? = null,
    val name: String,
    val address: String?
)
</code>```

I have a Family class which contains :

```<code>    val familyId: UUID? = null,
    val pList: List<Person>
</code>```

In one of the other classes I have to iterate over the pList BUT I need to change the address field for the person while fetching it from another map, based on the id.

I know I can use copy() method to populate an immutable field but I am not sure how to do it exactly. I was trying something like this but I doesn’t seem to work.

```<code>family.pList.forEach {
    it.copy(address = ‘I am getting this value from a map’ )
}
</code>```

I thought address would get populated with the new value but it’s not.

Note also the address field in the pList is not populated.

答:
The copy function returns a new instance of the object with the fields populated as provided when calling copy. So you need to save the new objects somewhere. Your method, as written, is creating a copied object and essentially discarding it immediately.

Here's what I would do:

```<code>val withAddresses = family.pList.map {
    it.copy(address = "I am getting this value from a map")
}
</code>```

The new variable, withAddresses, references the list of Person objects with the address field populated.

Body:
I have a data class with 3 fields on val type.

data class Person(
    val id: UUID? = null,
    val name: String,
    val address: String?
)

I have a Family class which contains :

    val familyId: UUID? = null,
    val pList: List<Person>

In one of the other classes I have to iterate over the pList BUT I need to change the address field for the person while fetching it from another map, based on the id.

I know I can use copy() method to populate an immutable field but I am not sure how to do it exactly. I was trying something like this but I doesn’t seem to work.

family.pList.forEach {
    it.copy(address = ‘I am getting this value from a map’ )
}

I thought address would get populated with the new value but it’s not.

Note also the address field in the pList is not populated.

Body:
The copy function returns a new instance of the object with the fields populated as provided when calling copy. So you need to save the new objects somewhere. Your method, as written, is creating a copied object and essentially discarding it immediately.

Here's what I would do:

val withAddresses = family.pList.map {
    it.copy(address = "I am getting this value from a map")
}

The new variable, withAddresses, references the list of Person objects with the address field populated.


问:
installing virtual environment in windows 10
I was trying to install a virtual environment in windows and I am getting the following error message. I tried googling it but wasn't much of any help.

答:
I hope I understand the problem correctly.
You can try

```<code>python -m pip install virtualenv
</code>```

If that fails, all you need to do is either start cmd as admin, which probably some people will advise against, or use the --user flag, to install the pip package.

Body:
I hope I understand the problem correctly.
You can try

python -m pip install virtualenv

If that fails, all you need to do is either start cmd as admin, which probably some people will advise against, or use the --user flag, to install the pip package.


问:
Runtime button creation in Android studio?
This isn't so much a question about my specific code as it is a question on what I need to use to accomplish my task.

I'm making a workout logging app for my class. The user needs to be able to create a workout routine, filled with various exercises of their choice.

On the home page, there is an "Add Workout" button. Clicking this should bring them to a screen where they name the workout and fill it in with said exercises. When they click save, I need to be able to create a new button on the home page with simply the name of their new workout. This new button when clicked will bring them to that workout, where they can start the workout and put in their reps, sets, weight, etc.

What do I need to be looking at to achieve this? Do I need to be saving the workouts to a database and using a function to go through the database and populate the home screen with respective buttons each time I enter the app / add a new workout? Or is there a different way to do this? I'm not sure that I'm even asking the right question or framing this problem the correct way.

Thanks!

答:
you should put the button on the home page from the beginning but make it invisible at first.

yes you should put the workout information in a database and if there is a workout saved, make the button visible in the home page.

use android:visibility="gone" in XML and birthday.visibility = View.VISIBLE in the activity to modify the visibility


问:
How to convert raw JSON with nested array field in Postman body into form-data?
Yesterday I've asked about this question but got no response maybe because it was too specific related to Django REST Framework. I feel like it's simply the key-value pair problem in form-data I use to post. So I'm going to re-ask the question with simplified content.

What is the form-data format's equivalent for this raw JSON:

```<code>"markets": [
        {
            "market": 1,
            "name": "White Stone",
            "slabs": [
                1,
                2
            ],
            "thicknesses": [
                1,
                2,
                3
            ],
            "finish_types": [
                1
            ]
        },
        {
            "market": 2,
            "name": "White Marble",
            "slabs": [
                1
            ],
            "thicknesses": [
                1
            ],
            "finish_types": [
                1,
                3,
                6
            ]
        }
]
</code>```

I want to create a new Product instance with markets field. markets is an array and has its own attributes. Some of them are also arrays. I can't send more than 1 slabs, thicknesses, and finish_types each within a single markets. slabs, thicknesses, and finish_types are foreign keys.

When I tried to do the key-value pairs like the image above, the only saved elements are the last one inputed.

Here's the created markets:

```<code>"markets": [
            {
                "id": 65,
                "market": 1,
                "name": "White Stone",
                "slabs": [
                    2
                ],
                "thicknesses": [
                    3
                ],
                "finish_types": [
                    1
                ]
            }
]
</code>```

And when I tried another key format like this no slabs and thicknesses will be saved:

```<code>"markets": [
            {
                "id": 66,
                "market": 1,
                "name": "White Stone",
                "slabs": [],
                "thicknesses": [],
                "finish_types": [
                    1
                ]
            }
]
</code>```

答:
According to this answer.

How about you try this format:

```<code>Key                       Value

markets[0][market]         1
markets[0][name]           white stone
markets[0][slabs][]        2
markets[0][thicknesses][]  3
markets[0][finish_types][] 1
</code>```

And maybe this Django thread might help you.

Body:
Yesterday I've asked about this question but got no response maybe because it was too specific related to Django REST Framework. I feel like it's simply the key-value pair problem in form-data I use to post. So I'm going to re-ask the question with simplified content.

What is the form-data format's equivalent for this raw JSON:

"markets": [
        {
            "market": 1,
            "name": "White Stone",
            "slabs": [
                1,
                2
            ],
            "thicknesses": [
                1,
                2,
                3
            ],
            "finish_types": [
                1
            ]
        },
        {
            "market": 2,
            "name": "White Marble",
            "slabs": [
                1
            ],
            "thicknesses": [
                1
            ],
            "finish_types": [
                1,
                3,
                6
            ]
        }
]

I want to create a new Product instance with markets field. markets is an array and has its own attributes. Some of them are also arrays. I can't send more than 1 slabs, thicknesses, and finish_types each within a single markets. slabs, thicknesses, and finish_types are foreign keys.

When I tried to do the key-value pairs like the image above, the only saved elements are the last one inputed.

Here's the created markets:

"markets": [
            {
                "id": 65,
                "market": 1,
                "name": "White Stone",
                "slabs": [
                    2
                ],
                "thicknesses": [
                    3
                ],
                "finish_types": [
                    1
                ]
            }
]

And when I tried another key format like this no slabs and thicknesses will be saved:

"markets": [
            {
                "id": 66,
                "market": 1,
                "name": "White Stone",
                "slabs": [],
                "thicknesses": [],
                "finish_types": [
                    1
                ]
            }
]

Body:
According to this answer.

How about you try this format:

Key                       Value

markets[0][market]         1
markets[0][name]           white stone
markets[0][slabs][]        2
markets[0][thicknesses][]  3
markets[0][finish_types][] 1

And maybe this Django thread might help you.


问:
Swift Core Data optional attribute with Scalar Type gets evaluated to 0 not NIL
I need to have an entity with an Optional Float attribute (with no default value). E.g:

```<code><attribute name="price" optional="YES" attributeType="Float" usesScalarValueType="YES"/>
</code>```

After I store a record in the DB  with this price being NULL, I want to retrieve it and map it to one of my DTOs, but surprise, it's evaluated to 0 (I was expecting NIL)

After looking into the core data auto-generated entity, I find that it was generated as non optional:

```<code>@NSManaged public var price: Float
</code>```

Now, I understand why NULL becomes 0, but the question is more on how to make this model Optional.

Any thoughts?

答:
You can add some extension based on value(forKey:), something like the following

```<code>extension YourClass {
    var isPricePresent: Bool {
        self.value(forKey: "price") != nil
    }
}
</code>```

Note: I assume it is due to legacy & backward compatibility - internal containers just cannot store nil and optional is not Objective-c compatible type.

Body:
I need to have an entity with an Optional Float attribute (with no default value). E.g:

<attribute name="price" optional="YES" attributeType="Float" usesScalarValueType="YES"/>

After I store a record in the DB  with this price being NULL, I want to retrieve it and map it to one of my DTOs, but surprise, it's evaluated to 0 (I was expecting NIL)

After looking into the core data auto-generated entity, I find that it was generated as non optional:

@NSManaged public var price: Float

Now, I understand why NULL becomes 0, but the question is more on how to make this model Optional.

Any thoughts?

Body:
You can add some extension based on value(forKey:), something like the following

extension YourClass {
    var isPricePresent: Bool {
        self.value(forKey: "price") != nil
    }
}

Note: I assume it is due to legacy & backward compatibility - internal containers just cannot store nil and optional is not Objective-c compatible type.


问:
css margin:auto not centering div in webkit browsers (Chrome and Safari) when maximised/full screen
I have been unable to determine the cause of this problem, so I can not display a test case,
instead I have narrowed down my code to a page that still contains the fault without too much extra.

Here is the link:

http://www.richard-walsh.limewebs.com/Disk-Edits/index.html

The problem is that the content div (id=content), is not centering in Chrome and Safari.

It is positioned to the right.

The content div is surrounded by a div called bottom, whose width:100%; and height:auto;.

```<code>#bottom{
    width:100%;
    height:auto;
    padding:0px;
    margin:0px;
}

#content{
    width:862.4px;
    height:402px;
    margin:auto;
    padding-left:10px;
    padding-right:10px;
    padding-top:5px;
    padding-bottom:5px;
    background-color:#030303;
    background-image:url(images/main.png);
    -moz-border-radius:15px;
    border-radius:15px;
    border-style:solid;
    border-color:#181818;
    border-width:4px;
    margin-top:60px;
    -moz-box-shadow: 1px 1px 20px 4px black;
    -webkit-box-shadow: 1px 1px 20px 4px black;
    box-shadow: 1px 1px 20px 4px black;
    overflow:hidden;
}
</code>```

I have found that if I remove overflow:hidden from the content css then it centers correctly.
But I need this (for parts not shown in the link)

I have also found that it works if I remove the menu entirely.
So I think that there must be something in the menu css that has caused this.
It works fine in Firefox(4).

I'm running Chrome 11.0.696.68
and Safari 5.0.5

Oh! I have just noticed that this only happens when Chrome is maximised, when it is in 'window mode' (for lack of a better name) it centers perfectly, even if the window is stretched to the full size of the screen.

I have also noticed that if you remove #copyright, then #content is rendered on the left, and if both #copyright and #choice is removed then the content div renders in the centre, and if you only remove #choice it still renders on the right.

If you remove #menu_all then it centers correctly.

Any help would be much appreciated,

Thanks

答: Add display: block, see if that works.</p>

Body:
I have been unable to determine the cause of this problem, so I can not display a test case,
instead I have narrowed down my code to a page that still contains the fault without too much extra.

Here is the link:

http://www.richard-walsh.limewebs.com/Disk-Edits/index.html

The problem is that the content div (id=content), is not centering in Chrome and Safari.

It is positioned to the right.

The content div is surrounded by a div called bottom, whose width:100%; and height:auto;.

#bottom{
    width:100%;
    height:auto;
    padding:0px;
    margin:0px;
}

#content{
    width:862.4px;
    height:402px;
    margin:auto;
    padding-left:10px;
    padding-right:10px;
    padding-top:5px;
    padding-bottom:5px;
    background-color:#030303;
    background-image:url(images/main.png);
    -moz-border-radius:15px;
    border-radius:15px;
    border-style:solid;
    border-color:#181818;
    border-width:4px;
    margin-top:60px;
    -moz-box-shadow: 1px 1px 20px 4px black;
    -webkit-box-shadow: 1px 1px 20px 4px black;
    box-shadow: 1px 1px 20px 4px black;
    overflow:hidden;
}

I have found that if I remove overflow:hidden from the content css then it centers correctly.
But I need this (for parts not shown in the link)

I have also found that it works if I remove the menu entirely.
So I think that there must be something in the menu css that has caused this.
It works fine in Firefox(4).

I'm running Chrome 11.0.696.68
and Safari 5.0.5

Oh! I have just noticed that this only happens when Chrome is maximised, when it is in 'window mode' (for lack of a better name) it centers perfectly, even if the window is stretched to the full size of the screen.

I have also noticed that if you remove #copyright, then #content is rendered on the left, and if both #copyright and #choice is removed then the content div renders in the centre, and if you only remove #choice it still renders on the right.

If you remove #menu_all then it centers correctly.

Any help would be much appreciated,

Thanks

Body: Add display: block, see if that works.


问:
Setting attribute in Cypress
Can't figure out from Cypress docs how to change attribute of a specific element in my integration test.

Basically, would like to achieve the below:

```<code>document.getElementById('my-id').setAttribute('data-test', 'new-value')
</code>```

Do you think it's possible?

thanks

答:
I believe this topic has the answer you are looking for:
Cypress: set attribute value

As mentionned in that topic, you can either:

use invoke

get the jQuery element by using .then(($el) => { $el.doSomeJqueryThings() }

Title: Setting attribute in Cypress

Body:
Can't figure out from Cypress docs how to change attribute of a specific element in my integration test.

Basically, would like to achieve the below:

document.getElementById('my-id').setAttribute('data-test', 'new-value')

Do you think it's possible?

thanks


答:
Adding autocomplete="off" stops browser from remembering the checkbox state.</p>

```<code><input type="checkbox" id="toggle-menu" autocomplete="off" />
</code>```

Title: How not to keep the state of a checkbox through the history?

Body:
I'm using a checkbox to create a mobile menu. Simplified, it looks like that:

input, ul {
  display: none;
}
label {
  cursor: pointer;
}
input:checked ~ ul {
  display: block;
}

<input type="checkbox" id="toggle-menu" />
Menu

Link

It works well, except for a thing: when the user navigates in another page using the menu, and then go back is the history, the checkbox state is kept, and thus the menu is displayed.

Is it possible to prevent this, preferably without Javascript? To say it in another words, I'd like the menu to never be displayed when a page is accessed to, even through the navigation in the history. The user must click on the label to see the menu.

Body:
Adding autocomplete="off" stops browser from remembering the checkbox state.

<input type="checkbox" id="toggle-menu" autocomplete="off" />


问:
SignalR Webform - signalr/hubs Negociate issue
I have a legacy webform project in which is necessary to integrate signalr Technology
I understood that the signalr/hubs is generated dinamically, however in my specific project i couldn make it work.

I tried to load all urls paths such as:

<%----%>

To turn around this i generate the signalR in another project which is working fine and i copied to my scripts folder /Scripts/SignalR/Hub.js and i referenced it in client side.

It worked fine because my client could establish connection with my chatHub(serverside) initializing my chat variable as below:

However after that i got i error in the negociate process between server to client as the image below:

I think is because when the server trys to comunicate with the client it generates the url as [signalr/hub], but as i mentioned before, I'm using the
/Scripts/SignalR/Hub.js  file to instance de connection to the hub.

How can i fix this negociate issue between server to the client?

Here is my structure files

startup.cs

```<code>using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.SignalR;
using SistemaJaspion.AppCode;
using System.Web.Routing;

[assembly: OwinStartup(typeof(SistemaJaspion.AppCode.Startup))]

namespace SistemaJaspion.AppCode
{
    /// <summary>
    /// The server needs to know which URL to intercept and direct to SignalR. To do that we add an OWIN startup class.
    /// </summary>
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            //app.MapSignalR("/signalr", new HubConfiguration());
            //app.MapSignalR();

            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;
            hubConfiguration.EnableJavaScriptProxies = true;

            app.MapSignalR("/signalr", hubConfiguration);
        }

    }
}

</code>```

ChatHub.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;

namespace SistemaJaspion.AppCode
{
    /// <summary>
    /// The Hub class is used to define methods the clients can call on the server
    /// </summary>
    ///

    [HubName("chatHub")]

    //[Microsoft.AspNet.SignalR.Authorize]
    public class ChatHub : Hub
    {

        static List<UsuariosSignalR> ConnectedUsers = new List<UsuariosSignalR>();

        // Number of connected clients
        private static int connectionCount = 0;

        public void Send(string name, string message)
        {
            // Append the current date
            name = DateTime.Now.ToString() + " " + name;
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }

        public override Task OnConnected()
        {

            // Increase the number of connections
            Interlocked.Increment(ref connectionCount);

            // Update the number of the connected users
            Clients.All.reportConnections(connectionCount);
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            // Decrease the number of connections
            Interlocked.Decrement(ref connectionCount);

            // Update the number of the connected users
            Clients.All.reportConnections(connectionCount);
            return base.OnDisconnected(stopCalled);
        }
    }
}
</code>```

MasterPage.aspx

```<code>
    <script src="../Scripts/jquery-1.6.4.min.js"></script>
    <script src="../Scripts/jquery.signalR-2.4.1.js"></script>
    <script src="../Scripts/SignalR/Hubs.js"></script>

    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">

         $(function () {
                    /* Peer-to-peer broadcast code */
                    // Declare a proxy to reference the ChatHub.

             debugger;

                   var chat = $.connection.chatHub;

                    chat.client.reportConnections = function (count) {
                        $("#usersCount").text(count);
                    }

                    $.connection.hub.logging = true;
                    $.connection.hub.start();
                });

    </script>
</code>```

答:
You can check if endpoint is added in the configure function in startup.cs

```<code>app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();

                endpoints.MapHub<ChartHub>("/charthub");
            });
</code>```

This is what I used in my project.

Body:
I have a legacy webform project in which is necessary to integrate signalr Technology
I understood that the signalr/hubs is generated dinamically, however in my specific project i couldn make it work.

I tried to load all urls paths such as:

<%----%>

To turn around this i generate the signalR in another project which is working fine and i copied to my scripts folder /Scripts/SignalR/Hub.js and i referenced it in client side.

It worked fine because my client could establish connection with my chatHub(serverside) initializing my chat variable as below:

However after that i got i error in the negociate process between server to client as the image below:

I think is because when the server trys to comunicate with the client it generates the url as [signalr/hub], but as i mentioned before, I'm using the
/Scripts/SignalR/Hub.js  file to instance de connection to the hub.

How can i fix this negociate issue between server to the client?

Here is my structure files

startup.cs

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.SignalR;
using SistemaJaspion.AppCode;
using System.Web.Routing;

[assembly: OwinStartup(typeof(SistemaJaspion.AppCode.Startup))]

namespace SistemaJaspion.AppCode
{
    ///
    /// The server needs to know which URL to intercept and direct to SignalR. To do that we add an OWIN startup class.
    ///
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            //app.MapSignalR("/signalr", new HubConfiguration());
            //app.MapSignalR();

            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;
            hubConfiguration.EnableJavaScriptProxies = true;

            app.MapSignalR("/signalr", hubConfiguration);
        }

    }
}

ChatHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;

namespace SistemaJaspion.AppCode
{
    ///
    /// The Hub class is used to define methods the clients can call on the server
    ///
    ///

    [HubName("chatHub")]

    //[Microsoft.AspNet.SignalR.Authorize]
    public class ChatHub : Hub
    {

        static List<UsuariosSignalR> ConnectedUsers = new List<UsuariosSignalR>();

        // Number of connected clients
        private static int connectionCount = 0;

        public void Send(string name, string message)
        {
            // Append the current date
            name = DateTime.Now.ToString() + " " + name;
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }

        public override Task OnConnected()
        {

            // Increase the number of connections
            Interlocked.Increment(ref connectionCount);

            // Update the number of the connected users
            Clients.All.reportConnections(connectionCount);
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            // Decrease the number of connections
            Interlocked.Decrement(ref connectionCount);

            // Update the number of the connected users
            Clients.All.reportConnections(connectionCount);
            return base.OnDisconnected(stopCalled);
        }
    }
}

MasterPage.aspx

Body:
You can check if endpoint is added in the configure function in startup.cs

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();

                endpoints.MapHub<ChartHub>("/charthub");
            });

This is what I used in my project.


问:
Mysql workbench timestamp change format
I have a table with a column in which are inserted timestamps.

exactTime : ' 2017-12-17 05:00:12 ' and i want to change this format into '2017-12-17 05:00'

i would need some help with this .

答:
You can truncate to the nearest minute using:

```<code>select str_to_date('2017-12-17 05:00:12', '%Y-%m-%d %H:%i')
</code>```

To actually output without seconds, you need to convert back to a string.  Or just use string operations:

```<code>select left('2017-12-17 05:00:12', 16)
</code>```

Title: Mysql workbench timestamp change format

Body:
You can truncate to the nearest minute using:

select str_to_date('2017-12-17 05:00:12', '%Y-%m-%d %H:%i')

To actually output without seconds, you need to convert back to a string.  Or just use string operations:

select left('2017-12-17 05:00:12', 16)


问:
Fitting a log-norm distribution for two given percentile values
Assuming that X is log-normal distributed, is it possible to identify its 0th percentile and 100th percentile (or 99.999 approximation) if the 5th percentile and 95th percentile value is given?

How can I program this in scipy to get the low and high value?
I thought conceptually the steps should be
1.) Fit a log normal curve (identify mean and variance) from the 5th percentile = 10 & 95th percentile = 100
2.) Identify the value at low and high (e.g. 99.999%)

答:
Lognormal means the natural log of your distribution is normal. So, moving between the two you may achieve your goal:</p>

```<code>import numpy as np
normal_at_5th_percentile = np.log(10)
normal_at_95th_percentile = np.log(100)

# params of related normal distribution
μ = (normal_at_5th_percentile + normal_at_95th_percentile)/2
σ = (normal_at_95th_percentile - μ) / 2

from scipy import stats
# 0.00001 and 0.99999 percentiles of lognormal distribution derived from normal
np.exp(stats.norm.ppf(.00001, loc=μ, scale=σ)), np.exp(stats.norm.ppf(.99999, loc=μ, scale=σ))
(2.715046684206284, 368.31779203565526)
</code>```

Body:
Lognormal means the natural log of your distribution is normal. So, moving between the two you may achieve your goal:

import numpy as np
normal_at_5th_percentile = np.log(10)
normal_at_95th_percentile = np.log(100)

# params of related normal distribution
μ = (normal_at_5th_percentile + normal_at_95th_percentile)/2
σ = (normal_at_95th_percentile - μ) / 2

from scipy import stats
# 0.00001 and 0.99999 percentiles of lognormal distribution derived from normal
np.exp(stats.norm.ppf(.00001, loc=μ, scale=σ)), np.exp(stats.norm.ppf(.99999, loc=μ, scale=σ))
(2.715046684206284, 368.31779203565526)


问:
Relationships are always nil when doing dynamoattribute.UnmarshalMap
I have two structs. Sample and Test. 'Sample' has a relationship of type 'Test'. When I try to do 'dynamoattribute.UnmarshalMap', the relationship is always nil. Could you advise how to populate relationships ('Test' in this case) please?

```<code>package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

type Sample struct {
    SampleId string `jsonapi:"attr,sampleId,omitempty" dynamodbav:"sample_id"`
    Test     *Test  `jsonapi:"relation,test"`
}

type Test struct {
    TestId string `jsonapi:"attr,testId,omitempty" dynamodbav:"test_id"`
}

func main() {
    var m map[string]*dynamodb.AttributeValue
    m = make(map[string]*dynamodb.AttributeValue)

    m["sample_id"] = &dynamodb.AttributeValue{
        S: aws.String("sample1"),
    }

    m["test_id"] = &dynamodb.AttributeValue{
        S: aws.String("test"),
    }

    sam := Sample{}

    err := dynamodbattribute.UnmarshalMap(m, &sam)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(sam)
}
</code>```

答:
```<code>package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

type Sample struct {
    SampleId string `jsonapi:"attr,sampleId,omitempty" dynamodbav:"sample_id"`
    Test     *Test  `jsonapi:"relation,test"`
}

type Test struct {
    TestId string `jsonapi:"primary,testId" dynamodbav:"test_id"`
}

func main() {
    var m map[string]*dynamodb.AttributeValue
    m = make(map[string]*dynamodb.AttributeValue)

    m["sample_id"] = &dynamodb.AttributeValue{
        S: aws.String("sample1"),
    }

    var mTest map[string]*dynamodb.AttributeValue
    mTest = make(map[string]*dynamodb.AttributeValue)

    mTest["test_id"] = &dynamodb.AttributeValue{
        S: aws.String("test1"),
    }

    m["test"] = &dynamodb.AttributeValue{
        M: mTest,
    }

    sam := Sample{}

    err := dynamodbattribute.UnmarshalMap(m, &sam)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(sam)
}
</code>```

Body:
I have two structs. Sample and Test. 'Sample' has a relationship of type 'Test'. When I try to do 'dynamoattribute.UnmarshalMap', the relationship is always nil. Could you advise how to populate relationships ('Test' in this case) please?

package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

type Sample struct {
    SampleId string `jsonapi:"attr,sampleId,omitempty" dynamodbav:"sample_id"`
    Test     *Test  `jsonapi:"relation,test"`
}

type Test struct {
    TestId string `jsonapi:"attr,testId,omitempty" dynamodbav:"test_id"`
}

func main() {
    var m map[string]*dynamodb.AttributeValue
    m = make(map[string]*dynamodb.AttributeValue)

    m["sample_id"] = &dynamodb.AttributeValue{
        S: aws.String("sample1"),
    }

    m["test_id"] = &dynamodb.AttributeValue{
        S: aws.String("test"),
    }

    sam := Sample{}

    err := dynamodbattribute.UnmarshalMap(m, &sam)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(sam)
}


问:
PLS-00382: expression is of wrong type executing package function from anonymous block
Here is my function func in my package A:

```<code>create or replace PACKAGE A AS

    type MY_TYPE IS TABLE OF MYTABLE%ROWTYPE;

    FUNCTION func RETURN MY_TYPE;

END A;

create or replace PACKAGE BODY A AS

    FUNCTION func RETURN MY_TYPE IS
        CURSOR myCursor IS
           SELECT * FROM MYTABLE;
           var_cursor MYTABLE%ROWTYPE;
           myParam MY_TYPE;
           i NUMBER := 1;

        BEGIN
           FOR var_cursor IN myCursor
           LOOP
             myParam.EXTEND;
             myParam(i) := var_cursor;
             i := i + 1;
           END LOOP;

           RETURN myParam;
        END func;
END A;
</code>```

I want to call this function.

```<code>DECLARE
 type my_type IS TABLE OF MYTABLE%ROWTYPE;
 variable my_type;

BEGIN
   variable := A.func();
END;
</code>```

This gives error

PLS-00382: expression is of wrong type

The types are the same, so what am I doing wrong and how can I fix it?

答:
Your function will not compile. If you use "end " to finish a a function/procedure the so in this case "end func;" Also, you are doing way too much code. No need to LOOP at all, instead use bulk collect.

```<code>create or replace package body a as

    function func return my_type is
        begin
           select *
             from mytable;
             bulk collect into myparam;
           return myparam;
        end func;
end a
</code>```

Body:
Here is my function func in my package A:

create or replace PACKAGE A AS

    type MY_TYPE IS TABLE OF MYTABLE%ROWTYPE;

    FUNCTION func RETURN MY_TYPE;

END A;

create or replace PACKAGE BODY A AS

    FUNCTION func RETURN MY_TYPE IS
        CURSOR myCursor IS
           SELECT * FROM MYTABLE;
           var_cursor MYTABLE%ROWTYPE;
           myParam MY_TYPE;
           i NUMBER := 1;

        BEGIN
           FOR var_cursor IN myCursor
           LOOP
             myParam.EXTEND;
             myParam(i) := var_cursor;
             i := i + 1;
           END LOOP;

           RETURN myParam;
        END func;
END A;

I want to call this function.

DECLARE
 type my_type IS TABLE OF MYTABLE%ROWTYPE;
 variable my_type;

BEGIN
   variable := A.func();
END;

This gives error

PLS-00382: expression is of wrong type

The types are the same, so what am I doing wrong and how can I fix it?

Body:
Your function will not compile. If you use "end " to finish a a function/procedure the so in this case "end func;" Also, you are doing way too much code. No need to LOOP at all, instead use bulk collect.

create or replace package body a as

    function func return my_type is
        begin
           select *
             from mytable;
             bulk collect into myparam;
           return myparam;
        end func;
end a