问:
jQuery: any suggestions how to preload all images in dom sequentially?
any ideas about it? any plugin? I want find all img tag and show them sequentially?
thank you</p>

答:
I used this function on a website to preload a list of images in a specific order sequentially:

It also maintains a progress indicator.

```<code>MicrositeMedia.ImagePreLoader = function (_settings) {
var self = this;

var defaults = {
    list: [],
    rootpath: '',
    onFinished: function () { },
    onItemFinished: null,
    containerId: '#preload-container'
}

this.settings = $.extend(defaults, _settings);
this.progressElm = 'preloadProgressIndicator';
//this.settings.list.pop();
var listSize = _settings.list.length;

MicrositeUtils.Logger.log("listSize: " + listSize);

this.current = 0;

this.init = function () {
    //MicrositeUtils.Logger.log("ImagePreLoader - init()");
    //
    $(this.settings.containerId).show();
    this.loadNext();
}

// list of already loaded items
var loadList = [];
var curImg = new Image();

this.loadNext = function () {
    if (listSize && listSize != 0) {
        // our current Image object
        var key = this.settings.list.shift();

        curImg.src = this.settings.rootpath + key;

        curImg.onerror = function () {
            //this.loadNext();
            MicrositeUtils.Logger.log("Error while loading image" + curImg.src.toString());
        }

        //MicrositeUtils.Logger.log('curImg.src: ' + curImg.src);
        // when it loads, it triggers the next load event.
        curImg.onload = function () {
            // item loading finished
            //MicrositeUtils.Logger.log("current: " + key + ", src :" + curImg.src + "current: " + self.current);
            loadList.push(curImg.src);

            // fire single item loaded event.
            if (self.settings.onItemFinished) {
                self.settings.onItemFinished(self.current, curImg.src);
            }

            // next
            self.current += 1;

            // update loader progress indicator.
            self.updateProgressIndicator(curImg.src, self.current, listSize);

            MicrositeUtils.Logger.log("loading image " + self.current + "/" + listSize);
            if (self.current == listSize) {
                // last element has loaded, fire the complete event
                self.complete();

            }
            else {
                // call the next one recursively
                self.loadNext();

            }

        };

    }
    else {
        MicrositeUtils.Logger.log("ImageLoader.loadNext(): nothing to load!");
    }
}

this.complete = function () {

    // clean up
    $(this.settings.containerId).fadeOut('slow', function () {
        // last element has loaded, fire the onfinished event
        if (self.settings.onFinished) self.settings.onFinished();
    });

}

this.updateProgressIndicator = function (text, idx, max) {
    var elm = this.progressElm;
    var percent = (Math.round((idx / max) * 100)) + "%";

    if (!document.getElementById(elm)) {
        // insert element
        $('<div id="' + elm + '"></div>')
            .appendTo(this.settings.containerId);
    }

    //MicrositeUtils.Logger.log(percent);
    $('#' + elm).html(percent);
}
</code>```

}

I called it like this:

```<code>this.imagePreloader = new MicrositeMedia.ImagePreLoader({
        list: preloadList,
        rootpath: self.appPath + '/assets/images',
        onFinished: function () {
            //MicrositeUtils.Logger.log("Preload (onfinished) - all done!");
            self.LoadInitialSection();
        },
        onItemFinished: function (item, src) {
            //MicrositeUtils.Logger.log("Preload (onitemfinished) - [item, src]: [" + item + ", " + src + "]");
        }
    });

    this.imagePreloader.init();
</code>```

list is the array of image names.

rootpath is, as the name suggests, a the path prefix for all the images you need to preload. It's your application's images path, in general.

containerId is your preloader Container, if you want to use a background and a progress indicator. If you need only preloading in the background, set this to en empty string.

onFinished contains normally a function which fires, when all preloading is finished. Typically, you can present your images at this point.

onItemFinished is a function you need fired after each image loaded.

You can omit the MicrositeUtils.Logger.log function or just implement it with your own routine.

Body:
I used this function on a website to preload a list of images in a specific order sequentially:

It also maintains a progress indicator.

MicrositeMedia.ImagePreLoader = function (_settings) {
var self = this;

var defaults = {
    list: [],
    rootpath: '',
    onFinished: function () { },
    onItemFinished: null,
    containerId: '#preload-container'
}

this.settings = $.extend(defaults, _settings);
this.progressElm = 'preloadProgressIndicator';
//this.settings.list.pop();
var listSize = _settings.list.length;

MicrositeUtils.Logger.log("listSize: " + listSize);

this.current = 0;

this.init = function () {
    //MicrositeUtils.Logger.log("ImagePreLoader - init()");
    //
    $(this.settings.containerId).show();
    this.loadNext();
}

// list of already loaded items
var loadList = [];
var curImg = new Image();

this.loadNext = function () {
    if (listSize && listSize != 0) {
        // our current Image object
        var key = this.settings.list.shift();

        curImg.src = this.settings.rootpath + key;

        curImg.onerror = function () {
            //this.loadNext();
            MicrositeUtils.Logger.log("Error while loading image" + curImg.src.toString());
        }

        //MicrositeUtils.Logger.log('curImg.src: ' + curImg.src);
        // when it loads, it triggers the next load event.
        curImg.onload = function () {
            // item loading finished
            //MicrositeUtils.Logger.log("current: " + key + ", src :" + curImg.src + "current: " + self.current);
            loadList.push(curImg.src);

            // fire single item loaded event.
            if (self.settings.onItemFinished) {
                self.settings.onItemFinished(self.current, curImg.src);
            }

            // next
            self.current += 1;

            // update loader progress indicator.
            self.updateProgressIndicator(curImg.src, self.current, listSize);

            MicrositeUtils.Logger.log("loading image " + self.current + "/" + listSize);
            if (self.current == listSize) {
                // last element has loaded, fire the complete event
                self.complete();

            }
            else {
                // call the next one recursively
                self.loadNext();

            }

        };

    }
    else {
        MicrositeUtils.Logger.log("ImageLoader.loadNext(): nothing to load!");
    }
}

this.complete = function () {

    // clean up
    $(this.settings.containerId).fadeOut('slow', function () {
        // last element has loaded, fire the onfinished event
        if (self.settings.onFinished) self.settings.onFinished();
    });

}

this.updateProgressIndicator = function (text, idx, max) {
    var elm = this.progressElm;
    var percent = (Math.round((idx / max) * 100)) + "%";

    if (!document.getElementById(elm)) {
        // insert element
        $('<div id="' + elm + '"></div>')
            .appendTo(this.settings.containerId);
    }

    //MicrositeUtils.Logger.log(percent);
    $('#' + elm).html(percent);
}

}

I called it like this:

this.imagePreloader = new MicrositeMedia.ImagePreLoader({
        list: preloadList,
        rootpath: self.appPath + '/assets/images',
        onFinished: function () {
            //MicrositeUtils.Logger.log("Preload (onfinished) - all done!");
            self.LoadInitialSection();
        },
        onItemFinished: function (item, src) {
            //MicrositeUtils.Logger.log("Preload (onitemfinished) - [item, src]: [" + item + ", " + src + "]");
        }
    });

    this.imagePreloader.init();

list is the array of image names.

rootpath is, as the name suggests, a the path prefix for all the images you need to preload. It's your application's images path, in general.

containerId is your preloader Container, if you want to use a background and a progress indicator. If you need only preloading in the background, set this to en empty string.

onFinished contains normally a function which fires, when all preloading is finished. Typically, you can present your images at this point.

onItemFinished is a function you need fired after each image loaded.

You can omit the MicrositeUtils.Logger.log function or just implement it with your own routine.


来源: stackexchange

问:
How to use React.FC<props> type when the children can either be a React node or a function
I have this sample component

```<code>import React, { FC, ReactNode, useMemo } from "react";
import PropTypes from "prop-types";

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props) {
  const val = useMemo(() => {
    return 1;
  }, []);

  return (
    <div>
      {typeof props.children === "function"
        ? props.children(val)
        : props.children}
    </div>
  );
};

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

export default Comp;
</code>```

My intent here is that the children prop of the component can either be

a node, which is described as

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

a function, (or a "render prop") which simply gets a value from inside the component and returns another node

the point here is to be explicit, that the children can either be the one (node, which is pretty much everything) or the other (which is simply a function)

The problem

I am facing the following issues however with the type check.

if I leave the code as presented here, I get the following error message on the line ? props.children(val)

This expression is not callable.
  Not all constituents of type 'Function | ((x: number) => ReactNode) | (string & {}) | (number & {}) | (false & {}) | (true & {}) | ({} & string) | ({} & number) | ({} & false) | ({} & true) | (((x: number) => ReactNode) & string)

I do not understand this error.

if I change the Props type to be

```<code>type Props = {
  children: (x: number) => ReactNode;
};
</code>```

and rely on React's own type PropsWithChildren
 = P & { children?: ReactNode }; to handle the case where children is not a function, then I get the error

(property) children?: PropTypes.Validator<(x: number) => React.ReactNode>
  Type 'Validator' is not assignable to type 'Validator<(x: number) => ReactNode>'.
    Type 'ReactNodeLike' is not assignable to type '(x: number) => ReactNode'.
      Type 'string' is not assignable to type '(x: number) => ReactNode'.ts(2322)
  Comp.tsx(5, 3): The expected type comes from property 'children' which is declared here on type

on the line children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired

The only solution is to leave the Props type as

```<code>type Props = {
  children: (x: number) => ReactNode;
};
</code>```

and also change the Comp.propTypes to be children: PropTypes.func.isRequired, which is not what I want, since I want to be explicit.

The question

How can I keep the code explicit, as presented at the start of this question, and also not have the type checking throw errors on me?

CodeSandbox link

答:
I think that global union might help:</p>

```<code>type Props = {
  children: ((x: number) => ReactNode);
} | {
  children: ReactNode;
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this sample component

import React, { FC, ReactNode, useMemo } from "react";
import PropTypes from "prop-types";

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props) {
  const val = useMemo(() => {
    return 1;
  }, []);

  return (

      {typeof props.children === "function"
        ? props.children(val)
        : props.children}

  );
};

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

export default Comp;

My intent here is that the children prop of the component can either be

a node, which is described as

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

a function, (or a "render prop") which simply gets a value from inside the component and returns another node

the point here is to be explicit, that the children can either be the one (node, which is pretty much everything) or the other (which is simply a function)

The problem

I am facing the following issues however with the type check.

if I leave the code as presented here, I get the following error message on the line ? props.children(val)

This expression is not callable.
  Not all constituents of type 'Function | ((x: number) => ReactNode) | (string & {}) | (number & {}) | (false & {}) | (true & {}) | ({} & string) | ({} & number) | ({} & false) | ({} & true) | (((x: number) => ReactNode) & string)

I do not understand this error.

if I change the Props type to be

type Props = {
  children: (x: number) => ReactNode;
};

and rely on React's own type PropsWithChildren
 = P & { children?: ReactNode }; to handle the case where children is not a function, then I get the error

(property) children?: PropTypes.Validator<(x: number) => React.ReactNode>
  Type 'Validator' is not assignable to type 'Validator<(x: number) => ReactNode>'.
    Type 'ReactNodeLike' is not assignable to type '(x: number) => ReactNode'.
      Type 'string' is not assignable to type '(x: number) => ReactNode'.ts(2322)
  Comp.tsx(5, 3): The expected type comes from property 'children' which is declared here on type

on the line children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired

The only solution is to leave the Props type as

type Props = {
  children: (x: number) => ReactNode;
};

and also change the Comp.propTypes to be children: PropTypes.func.isRequired, which is not what I want, since I want to be explicit.

The question

How can I keep the code explicit, as presented at the start of this question, and also not have the type checking throw errors on me?

CodeSandbox link

Body:
I think that global union might help:

type Props = {
  children: ((x: number) => ReactNode);
} | {
  children: ReactNode;
};


问:
flask dynamic host path
I have following simple flask

templates/fileform.html

```<code>  <html>
      <head>
          <title>Simple file upload using Python Flask</title>
      </head>
      <body>
          <form action="/getSignature" method="post" enctype="multipart/form-data">
              Choose the file: <input type="file" name="photo"/><BR>
                  <input type="submit" value="Get Signature"/>
          </form>
      </body>
  </html>
</code>```

templates/result.html

```<code>  <html>
  <body>
      <p>Signature for file : {{ variable }}</p>
  </body>
  </html>
</code>```

app.py

```<code>  import os
  from flask import Flask, request, render_template, url_for, redirect
  import rsa
  from binascii import hexlify
  import pickle

  SIGNING_KEY = os.getenv('SIGNING_KEY')

  app = Flask(__name__)

  @app.route("/")
  def fileFrontPage():
      return render_template('fileform.html')

  def _sign_file(private_key_file, filename):
      print("Loading private signing key")
      with open(private_key_file,'r') as fh:
          privkey = rsa.PrivateKey.load_pkcs1(fh.read(), 'PEM')
      print("Signing file")
      with open(filename,'rb') as fh:
          signature = rsa.sign(fh, privkey, "SHA-1")
      signature = hexlify(bytearray(signature)) #Send as byte array
      return signature

  @app.route("/getSignature", methods=['POST'])
  def handleFileUpload():
      if 'photo' in request.files:
          photo = request.files['photo']
          if photo.filename != '':
              filepath = os.path.join('/flask/files', photo.filename)
              photo.save(filepath)
              signature = _sign_file(SIGNING_KEY, filepath)
              os.remove(filepath)
      return render_template('result.html', variable=signature)

  if __name__ == '__main__':
      app.run(host='0.0.0.0', port=5000)
</code>```

This works fine on local host. But I am serving it at domain.com/signature via Nginx. When I click Get Signature it goes to domain.com/getSignature and shows

```<code>405 Method Not Allowed
Code: MethodNotAllowed
Message: The specified method is not allowed against this resource.
Method: POST
ResourceType: OBJECT
RequestId: CAB22446BEAE3B3F
HostId: cYGbt4sjHpFfrp6iBXvuYx4qzk7dkT4BqpNNJYFbeMjz34kYLtnr/RTxp8CsqvEoHTx/fVQmWsE=
</code>```

it need to go to domain.com/signature/getSignature

i tried to add app.config["APPLICATION_ROOT"] = "/signature/" but didn't work.

How can I change the host for route("/getSignature") ?

答:
Your form action should go to Nginx endpoint if Nginx is proxying it to your flask route. Based on what you said Nginx is listening on domain.com/signature Give this a try.

```<code><form action="domain.com/signature/getSignature" method="post" enctype="multipart/form-data">
              Choose the file: <input type="file" name="photo"/><BR>
                  <input type="submit" value="Get Signature"/>
</form>
</code>```

or

```<code><form action="/signature/getSignature" method="post" enctype="multipart/form-data">
              Choose the file: <input type="file" name="photo"/><BR>
                  <input type="submit" value="Get Signature"/>
</form>
</code>```

Title: flask dynamic host path

Body:
I have following simple flask

templates/fileform.html

          <title>Simple file upload using Python Flask</title>

          <form action="/getSignature" method="post" enctype="multipart/form-data">
              Choose the file: <input type="file" name="photo"/>

                  <input type="submit" value="Get Signature"/>
          </form>

templates/result.html

Signature for file : {{ variable }}

app.py

  import os
  from flask import Flask, request, render_template, url_for, redirect
  import rsa
  from binascii import hexlify
  import pickle

  SIGNING_KEY = os.getenv('SIGNING_KEY')

  app = Flask(__name__)

  @app.route("/")
  def fileFrontPage():
      return render_template('fileform.html')

  def _sign_file(private_key_file, filename):
      print("Loading private signing key")
      with open(private_key_file,'r') as fh:
          privkey = rsa.PrivateKey.load_pkcs1(fh.read(), 'PEM')
      print("Signing file")
      with open(filename,'rb') as fh:
          signature = rsa.sign(fh, privkey, "SHA-1")
      signature = hexlify(bytearray(signature)) #Send as byte array
      return signature

  @app.route("/getSignature", methods=['POST'])
  def handleFileUpload():
      if 'photo' in request.files:
          photo = request.files['photo']
          if photo.filename != '':
              filepath = os.path.join('/flask/files', photo.filename)
              photo.save(filepath)
              signature = _sign_file(SIGNING_KEY, filepath)
              os.remove(filepath)
      return render_template('result.html', variable=signature)

  if __name__ == '__main__':
      app.run(host='0.0.0.0', port=5000)

This works fine on local host. But I am serving it at domain.com/signature via Nginx. When I click Get Signature it goes to domain.com/getSignature and shows

405 Method Not Allowed
Code: MethodNotAllowed
Message: The specified method is not allowed against this resource.
Method: POST
ResourceType: OBJECT
RequestId: CAB22446BEAE3B3F
HostId: cYGbt4sjHpFfrp6iBXvuYx4qzk7dkT4BqpNNJYFbeMjz34kYLtnr/RTxp8CsqvEoHTx/fVQmWsE=

it need to go to domain.com/signature/getSignature

i tried to add app.config["APPLICATION_ROOT"] = "/signature/" but didn't work.

How can I change the host for route("/getSignature") ?

Body:
Your form action should go to Nginx endpoint if Nginx is proxying it to your flask route. Based on what you said Nginx is listening on domain.com/signature Give this a try.

<form action="domain.com/signature/getSignature" method="post" enctype="multipart/form-data">
              Choose the file: <input type="file" name="photo"/><BR>
                  <input type="submit" value="Get Signature"/>
</form>

or

<form action="/signature/getSignature" method="post" enctype="multipart/form-data">
              Choose the file: <input type="file" name="photo"/><BR>
                  <input type="submit" value="Get Signature"/>
</form>


问:
Calculating speed from 2 points
I know this question has been asked a lot, but not yet to my satisfaction. I am trying to use the GPS of an Android device to calculate speed. A lot of people seem to reply by saying to simply use the getSpeed() function of the Location object. From what I understand though, getSpeed() will only work on certain devices that have a speed sensor built into the GPS receiver chip. I want my application to work regardless of this, so I am using the following haversine formula:

```<code>private double CalculateHaversineMI(double lat1, double long1, double lat2,double long2) {
    double dlong = (long2 - long1) * (Math.PI / 180.0f);
    double dlat = (lat2 - lat1) * (Math.PI / 180.0f);
    double a = Math.pow(Math.sin(dlat / 2.0), 2)
        + Math.cos(lat1 * (Math.PI / 180.0f))
        * Math.cos(lat2 * (Math.PI / 180.0f))
        * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 3956 * c;

    return d;
}
</code>```

Now what I'm trying to do is figure out how to calculate speed from this. Can anyone help me please?

答:
What I can see is that your function returns correct path distance between 2 points on a sphere - it is d. But, this formula is needed only if you have 2 points on a sphere that are not close to each other (means central angle of their separation is not small, central angle of 1 degree corresponds to distance of 111 km approx, just to get feeling). If they are close to each other (which is the case for people moving and slow speed vehicles), then you do not need this formula. You can simply and very accurately approximate arc on the sphere with the straight line, and then calculation becomes trivial.

Sample GPS position at regular time periods. Calculate distance from the last position obtained. For that purpose you may use distanceTo() function from android.location.Location.

Calculate speed by dividing distance with time elapsed between 2 measurements.

Average calculated speeds for more accurate results, but ensure that you do not lose sensitivity to speed changes. So, you would need some trade-off on number of samples averaged.

ContentLicense: CC BY-SA 3.0

Title: Calculating speed from 2 points

Body:
I know this question has been asked a lot, but not yet to my satisfaction. I am trying to use the GPS of an Android device to calculate speed. A lot of people seem to reply by saying to simply use the getSpeed() function of the Location object. From what I understand though, getSpeed() will only work on certain devices that have a speed sensor built into the GPS receiver chip. I want my application to work regardless of this, so I am using the following haversine formula:

private double CalculateHaversineMI(double lat1, double long1, double lat2,double long2) {
    double dlong = (long2 - long1) * (Math.PI / 180.0f);
    double dlat = (lat2 - lat1) * (Math.PI / 180.0f);
    double a = Math.pow(Math.sin(dlat / 2.0), 2)
        + Math.cos(lat1 * (Math.PI / 180.0f))
        * Math.cos(lat2 * (Math.PI / 180.0f))
        * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 3956 * c;

    return d;
}

Now what I'm trying to do is figure out how to calculate speed from this. Can anyone help me please?


问:
Why POST request from Unity return empty in php?
I want to create Register and Login in my game, i created a simple database, and post request from off documentation by Unity. But in php $_POST['any'] always return empty.

I try with $_GET['any'], and it work, but need to use POST.

This is c# code:

```<code> private IEnumerator IESignUp()
{
    List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
    formData.Add(new MultipartFormDataSection("username=username&password=12345678"));
    //string.Format("username={0}&password={1}", usernameInput.text, passwordInput.text)
    UnityWebRequest www = UnityWebRequest.Post("http://multiplayer_game:8080/sing_up.php", formData);
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        popupWindow.Show("Network not respond!", www.error, PopupWindow.Type.Error);
    }
    else
    {
        Debug.Log("Form upload complete!");
    }
}
</code>```

And this is php code:

```<code>  if(isset($_POST['username']) && isset($_POST['password'])) {
$sql = "INSERT INTO players (username, password, mail, points, serrviums, skin_id, weapon_id, inventory) VALUES ('".$_POST['username']."', '".$_POST['password']."', 'test@mail.ru', 0, 0, 0, 0, '0|0')";

if(mysqli_query($connection, $sql))
    echo 'Successful';
else
    echo 'Error';
</code>```

}

答:
Your php file is sing_up.php -- not sign_up.php?
I've been foiled by worse.</p>

Body:
I want to create Register and Login in my game, i created a simple database, and post request from off documentation by Unity. But in php $_POST['any'] always return empty.

I try with $_GET['any'], and it work, but need to use POST.

This is c# code:

 private IEnumerator IESignUp()
{
    List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
    formData.Add(new MultipartFormDataSection("username=username&password=12345678"));
    //string.Format("username={0}&password={1}", usernameInput.text, passwordInput.text)
    UnityWebRequest www = UnityWebRequest.Post("http://multiplayer_game:8080/sing_up.php", formData);
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        popupWindow.Show("Network not respond!", www.error, PopupWindow.Type.Error);
    }
    else
    {
        Debug.Log("Form upload complete!");
    }
}

And this is php code:

  if(isset($_POST['username']) && isset($_POST['password'])) {
$sql = "INSERT INTO players (username, password, mail, points, serrviums, skin_id, weapon_id, inventory) VALUES ('".$_POST['username']."', '".$_POST['password']."', 'test@mail.ru', 0, 0, 0, 0, '0|0')";

if(mysqli_query($connection, $sql))
    echo 'Successful';
else
    echo 'Error';

}


问:
How to refer to a file inside spring boot application jar as a -D property value while starting the app from command line?
I have a simple spring boot application that needs java.security.krb5.conf property value set to a custom krb5.conf file. I have added the file inside the src/main/resources folder and maven make it packaged into the jar.

to start the app , I run
java -jar -Djava.security.krb5.conf=<localPath>/krb5.conf my-jar.jar

currently I have to give the <localPath> as the path to the file on my machine. Is there a way to refer to the file inside the jar so that I can run in any machine without creating the file file first on the machine?

things I tried so far:

give -Djava.security.krb5.conf=classpath:krb5.conf (also ./krb5.conf). Didn't work

I see most of the examples for 'how to read files from class path' refer to getClass.getResource (filename). So I tried do getClass.getResource (filename).getPath() so that I can set it as java.security.krb5.conf system property while starting the app in main class instead of passing from command line. But the string that getPath shows is something like /<diskPath>/my-jar.jar!/BOOT-INF/classes!/krb5.conf and this path is not working when I try to read the file for testing.

Create a copy of the file to the running dir on-the-fly, in main method before calling SprinApplication.run. This is what I am doing now.

```<code>    try(
       InputStream in = new ClassPathResource("krb5.conf").getInputStream();
       OutputStream out = new FileOutputStream( new File("krb5copy.conf"));) {
       IOUtils.copy(in, out);
    }
    System.setProperty("java.security.krb5.conf","krb5copy.conf");
</code>```

If there is a solution for this question , I can see other use cases such as providing the trustore file included in jar as javax.net.ssl.trustStore etc.

答:
The code that reads the krb5.conf configuration file uses FileInputStream, which requires the path to the file and doesn't "understand" classpath: prefix.

The idea below is to locate the file on the classpath and from that to get the path to the file:

```<code>ClassPathResource resource = new ClassPathResource("krb5.conf");
try
{
   String fileSpec = resource.getURL().getFile();
   System.setProperty("java.security.krb5.conf", fileSpec);
}
catch (IOException e)
{
   // TODO handle the exception
   e.printStackTrace();
}
</code>```

EDIT: When packaged as SpringBoot fat JAR, trying to read the file with FileInputStream results in java.io.FileNotFoundException: file:/<path-to-jar/<jar-name>.jar!/BOOT-INF/classes!/krb5.conf (No such file or directory) :-(

Body:
I have a simple spring boot application that needs java.security.krb5.conf property value set to a custom krb5.conf file. I have added the file inside the src/main/resources folder and maven make it packaged into the jar.

to start the app , I run
java -jar -Djava.security.krb5.conf=<localPath>/krb5.conf my-jar.jar

currently I have to give the <localPath> as the path to the file on my machine. Is there a way to refer to the file inside the jar so that I can run in any machine without creating the file file first on the machine?

things I tried so far:

give -Djava.security.krb5.conf=classpath:krb5.conf (also ./krb5.conf). Didn't work

I see most of the examples for 'how to read files from class path' refer to getClass.getResource (filename). So I tried do getClass.getResource (filename).getPath() so that I can set it as java.security.krb5.conf system property while starting the app in main class instead of passing from command line. But the string that getPath shows is something like /<diskPath>/my-jar.jar!/BOOT-INF/classes!/krb5.conf and this path is not working when I try to read the file for testing.

Create a copy of the file to the running dir on-the-fly, in main method before calling SprinApplication.run. This is what I am doing now.

    try(
       InputStream in = new ClassPathResource("krb5.conf").getInputStream();
       OutputStream out = new FileOutputStream( new File("krb5copy.conf"));) {
       IOUtils.copy(in, out);
    }
    System.setProperty("java.security.krb5.conf","krb5copy.conf");

If there is a solution for this question , I can see other use cases such as providing the trustore file included in jar as javax.net.ssl.trustStore etc.

Body:
The code that reads the krb5.conf configuration file uses FileInputStream, which requires the path to the file and doesn't "understand" classpath: prefix.

The idea below is to locate the file on the classpath and from that to get the path to the file:

ClassPathResource resource = new ClassPathResource("krb5.conf");
try
{
   String fileSpec = resource.getURL().getFile();
   System.setProperty("java.security.krb5.conf", fileSpec);
}
catch (IOException e)
{
   // TODO handle the exception
   e.printStackTrace();
}

EDIT: When packaged as SpringBoot fat JAR, trying to read the file with FileInputStream results in java.io.FileNotFoundException: file:/<path-to-jar/<jar-name>.jar!/BOOT-INF/classes!/krb5.conf (No such file or directory) :-(


问:
nodejs upload 2 single image in 2 different folder
I am trying to upload 2 images in different folder but got errors. I have use array for multer but still shows unexpected field or filename. I have use node as a server using multer

my code is

```<code>const DIR = './fabric/img/';
const designDIR = './fabric/design/';
const storage = multer.diskStorage({

 destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});
const designstorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, designDIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});

var upload = multer({
  storage: storage,
  designstorage: designstorage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
});

router.post('/fabric', upload.any(), (req, res, next) => {

  const io = req.app.get('io');
  const product = new db.fabric({
    image: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/" + req.files.filename,
    design: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/design/" + req.files.filename,

  });

  product.save().then(result => {
    console.log(result);
    res.status(201).json({
      message: "product added successfully!",
      productCreated: {
        image: result.image,
        design: result.design
      }
    })
    io.emit('productAdded');
  }).catch(err => {
    console.log(err),
      res.status(500).json({
        error: err
      });
  })
})
</code>```

got following error when post from postman "image": "http://localhost:3000/img/undefined"

答:
try with req.files[0].originalname, req.files[1].originalname,
if not check with console then you will get the required fieldname</p>

Body:
I am trying to upload 2 images in different folder but got errors. I have use array for multer but still shows unexpected field or filename. I have use node as a server using multer

my code is

const DIR = './fabric/img/';
const designDIR = './fabric/design/';
const storage = multer.diskStorage({

 destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});
const designstorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, designDIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});

var upload = multer({
  storage: storage,
  designstorage: designstorage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  }
});

router.post('/fabric', upload.any(), (req, res, next) => {

  const io = req.app.get('io');
  const product = new db.fabric({
    image: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/" + req.files.filename,
    design: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/design/" + req.files.filename,

  });

  product.save().then(result => {
    console.log(result);
    res.status(201).json({
      message: "product added successfully!",
      productCreated: {
        image: result.image,
        design: result.design
      }
    })
    io.emit('productAdded');
  }).catch(err => {
    console.log(err),
      res.status(500).json({
        error: err
      });
  })
})

got following error when post from postman "image": "http://localhost:3000/img/undefined"


答:
give -Djava.security.krb5.conf=classpth:krb5.conf (also ./krb5.conf).
  Didn't work

It's not 'classpth' it's 'classpath', actually. AND with a slash after it.

-Djava.security.krb5.conf=classpath/:krb5.conf should work.

Title: How to refer to a file inside spring boot application jar as a -D property value while starting the app from command line?


问:
preg_replace(): Compilation failed: invalid range in character class at offset 11 in Laravel Slug
i'm building an Arabic Slug system form my Blog App

when i add a new Slug i got this error

preg_replace(): Compilation failed: invalid range in character class at offset 11

controller

```<code>public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\s-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}

public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');

    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
</code>```

Route

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

答:
You have a extra - after \s.

Replace:

```<code>$string = preg_replace("/[^a-z0-9_\s-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
</code>```

with

```<code>$string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
</code>```

Or fix it to match your regex, like escaping it \-.

Body:
i'm building an Arabic Slug system form my Blog App

when i add a new Slug i got this error

preg_replace(): Compilation failed: invalid range in character class at offset 11

controller

public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\s-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}

public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');

    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}

Route

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

Body:
You have a extra - after \s.

Replace:

$string = preg_replace("/[^a-z0-9_\s-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

with

$string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

Or fix it to match your regex, like escaping it \-.


问:
Output the index of map()
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}</code>```

```

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

答:
How about:

```<code>// You can just fill an array with the required number of null elements
const arr = new Array(9).fill(null);
const div = document.querySelector('.container');
// Note that index is the second parameter of the callback passed to map
div.innerHTML = arr.map((val, index) => {
    const count = index + 1;
    // If you prepend the count with "it-", the class name is valid
    return `<div class="it it-${count}">${count}</div>`;
}).join('');
</code>```

Fiddle

Title: Output the index of map()

Body:
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');

* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

Body:
How about:

// You can just fill an array with the required number of null elements
const arr = new Array(9).fill(null);
const div = document.querySelector('.container');
// Note that index is the second parameter of the callback passed to map
div.innerHTML = arr.map((val, index) => {
    const count = index + 1;
    // If you prepend the count with "it-", the class name is valid
    return `<div class="it it-${count}">${count}</div>`;
}).join('');

Fiddle


问:
How can i get spring-boot main-class package name
I want to make a spring-boot starter,so i need to get package name of application main-class.
How can i get it?
Sometimes,you can use listener for spring boot,but it must configure in application.properties.</p>

答:
You could use the fact that the main class will problably be annotated with @SpringBootApplication and search for that class in the Spring Context. Implementing something like:

```<code>@Service
public class ApplicationFinder {

  @Autowired private ApplicationContext context;

  public String findBootClass() {
    Map<String, Object> candidates = context.getBeansWithAnnotation(SpringBootApplication.class);
    return candidates.isEmpty() ? null : candidates.values().toArray()[0].getClass();
  }
}
</code>```

Once you jave the class name you can string slice it to extract the package.

Body:
You could use the fact that the main class will problably be annotated with @SpringBootApplication and search for that class in the Spring Context. Implementing something like:

@Service
public class ApplicationFinder {

  @Autowired private ApplicationContext context;

  public String findBootClass() {
    Map<String, Object> candidates = context.getBeansWithAnnotation(SpringBootApplication.class);
    return candidates.isEmpty() ? null : candidates.values().toArray()[0].getClass();
  }
}

Once you jave the class name you can string slice it to extract the package.


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

答:
Two different lazy solutions in Python, using the itertools module.

Using itertools.groupby (and accumulate)

from itertools import accumulate, groupby

result = (
    item
    for _, group in groupby(x, key=lambda n: n < 0)
    for item in enumerate(accumulate(group), 1)
)
```

<h3>Using itertools.accumulate with a custom accumulation function</h3>

<pre class="lang-py prettyprint-override"><code>from itertools import accumulate

def sign_count_sum(count_sum, value):
    count, prev_sum = count_sum
    same_sign = (prev_sum < 0) is (value < 0)
    if same_sign:
        return count + 1, prev_sum + value
    else:
        return 1, value

result = accumulate(x, sign_count_sum, initial=(0, 0))
next(result)  # needed to skip the initial (0, 0) item
</code>```

The initial keyword argument was added in Python 3.8. In earlier versions you can use itertools.chain to prepend the (0,0)-tuple:

result = accumulate(chain([(0, 0)], x), sign_count_sum)
```

<p>The output is as expected:</p>

<pre class="lang-py prettyprint-override"><code>for (i, v), (c, s) in zip(enumerate(x), result):
    print(f"{i:3} {v:7.3f} {c:3} {s:7.3f}")
</code>```

```<code>  0  -0.010   1  -0.010
  1   0.003   1   0.003
  2  -0.002   1  -0.002
  3   0.018   1   0.018
  4   0.002   2   0.020
  5   0.006   3   0.026
  6  -0.012   1  -0.012
  7   0.014   1   0.014
  8  -0.017   1  -0.017
  9  -0.007   2  -0.024
 10   0.002   1   0.002
 11   0.002   2   0.004
 12  -0.004   1  -0.004
 13   0.015   1   0.015
 14   0.002   2   0.017
 15  -0.001   1  -0.001
 16  -0.008   2  -0.009
 17   0.010   1   0.010
 18  -0.018   1  -0.018
 19   0.046   1   0.046
</code>```

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
Two different lazy solutions in Python, using the itertools module.

Using itertools.groupby (and accumulate)

from itertools import accumulate, groupby

result = (
    item
    for _, group in groupby(x, key=lambda n: n < 0)
    for item in enumerate(accumulate(group), 1)
)

Using itertools.accumulate with a custom accumulation function

from itertools import accumulate

def sign_count_sum(count_sum, value):
    count, prev_sum = count_sum
    same_sign = (prev_sum < 0) is (value < 0)
    if same_sign:
        return count + 1, prev_sum + value
    else:
        return 1, value

result = accumulate(x, sign_count_sum, initial=(0, 0))
next(result)  # needed to skip the initial (0, 0) item

The initial keyword argument was added in Python 3.8. In earlier versions you can use itertools.chain to prepend the (0,0)-tuple:

result = accumulate(chain([(0, 0)], x), sign_count_sum)

The output is as expected:

for (i, v), (c, s) in zip(enumerate(x), result):
    print(f"{i:3} {v:7.3f} {c:3} {s:7.3f}")

  0  -0.010   1  -0.010
  1   0.003   1   0.003
  2  -0.002   1  -0.002
  3   0.018   1   0.018
  4   0.002   2   0.020
  5   0.006   3   0.026
  6  -0.012   1  -0.012
  7   0.014   1   0.014
  8  -0.017   1  -0.017
  9  -0.007   2  -0.024
 10   0.002   1   0.002
 11   0.002   2   0.004
 12  -0.004   1  -0.004
 13   0.015   1   0.015
 14   0.002   2   0.017
 15  -0.001   1  -0.001
 16  -0.008   2  -0.009
 17   0.010   1   0.010
 18  -0.018   1  -0.018
 19   0.046   1   0.046


问:
pySpark with conda integration throwing error pyspark not recognized
Steps followed:
Installed Java,Python,Spark,Anaconda and set up path in each.But pyspark in command prompt did not link Jupyter to notebook.

Getting the following error:

"'pyspark' is not recognized as an internal or external command,operable program or batch file."

答:
```<code>    Follow these steps:
    Install JAVA
    1.Download Python
    Python 3.x
    [https://www.python.org/downloads/][1]

    2.Set Path
    As we have select the "set path" option we don’t have o set the path manually.
    3.Verify Python Install or not
    a)
    Cmd>python -V
    b)
    Open Python terminal by writing "python" command in the terminal-IDLEs

    InStall spark
   Verify PySpark Installed or not:-
   ===================================================
   Cmd>pyspark

   It will open pyspark shell i.e python shell i.e IDLEs
   IDLEs is an interactive shell to write python applications

   First Pyspark Application:-
   ===================================================
   We can write PySpark Application in 2 modes. They are:
   1.Interactive --Pysaprk Shell
   2.Batch Application---IDEs --Integrated Development Environments
                    (Jupyter Notebook,Pycharms,etc)

   How to develop first pyspark appliction in interactive mode??
   ===================================================
   e.g Load local file and count no.of rows and print data

   Cmd>pyspark
   --> it will open pyspark ahell
   -->It is created sparkContext with variable name "sc"
   -->SparkContext is a predefined class,it is required to write Spark Application
   >>>sc
   <SparkContext master=local[*] appName=PySparkShell>

    ANACONDA Installation:
    ============================================
    Jupyter Notebook installation

    1.Download Anaconda
    https://www.anaconda.com/distribution/

    2.Install Anaconda
    By double click .exe file choose all default options
    3.set Path Variable (This is optional when se;ect add path environment at the time of
    installation)
    4.Start Anaconda and Open Jupyter
    Configuring PySpark with Jupyter Notebook:-
    ============================================
    1.Python or Anaconda software must be installed(Jupiter Notebook)
    2.PySpark must be installed.
    How to open Pyspark:
    ==================
    Cmd>pyspark
    How PySpark to start Jupyter Notebook:
    ==========================
    We can start Jupyter notebook in two ways. They are:

    1.Start Anaconda Navigater--->Launch Jupyter Notebook
    2.Open command prompt and type
   Cmd>jupyter notebook
Here we write Python Application
Set Environmental Variable:-
=========================
PYSPARK_DRIVER_PYTHON=jupyter
PYSPAR_DRIVER_PYTHON_OPTS=notebook
  [1]: https://www.python.org/downloads/
</code>```


问:
Converting String array to java.util.List
How do I convert a String array to a java.util.List?

答:
```<code>import java.util.Collections;

List myList = new ArrayList();
String[] myArray = new String[] {"Java", "Util", "List"};

Collections.addAll(myList, myArray);
</code>```


问:
A same suid + system program, different outputs on different systems
I write a simple program named suid.c:

int main(int argc, char* argv[]) {
        system(argv[1]);
}
```

<p>Compile it with gcc then set suid permission (root user now):</p>

```# gcc suid.c -o suid
# chmod +s suid
```

I tried to run ./suid id with the www-data user on different virtual machines, but the output is different.

The output in kali 2019: id=33(www-data) gid=33(www-data) groups=33(www-data)

The output in ubuntu trusty(a old linux): uid=33(www-data) gid=33(www-data) euid=0(root) egid=0(root) groups=0(root),33(www-data)

Why is that? Has anything changed in Linux?

答:
As noted in a comment above, you're seeing the effects of system() dropping setuid on purpose (indirectly via bash).

My Amazon Linux instance notes for system(3):

Do not use system() from a program with set-user-ID or set-group-ID privileges, because strange values for some environment  variables  might
  be  used  to  subvert  system integrity.  Use the exec(3) family of functions instead, but not execlp(3) or execvp(3).  system() will not, in
  fact, work properly from programs with set-user-ID or set-group-ID privileges on systems on which /bin/sh is bash version  2,  since  bash  2
  drops privileges on startup.  (Debian uses a modified bash which does not do this when invoked as sh.)

Running system() from a setuid program is super dangerous because it's way, way easier to subvert your intentions than you think (hijacking $IFS would be a good place to start).

Using one of the exec functions at least gets the shell out of the way, but there's often another shell down the road.

If you absolutely have to do this, you can call setuid(geteuid()); prior to system(), which essentially throws away the fact that you're in a setuid environment - where real and effective users are different - by saying that both are the elevated user. Likewise with group. This is probably a terrible idea.

I might suggest that if you have to ask SO how to do setuid, you may not be in the best position to do it safely.

Body:
I write a simple program named suid.c:

int main(int argc, char* argv[]) {
        system(argv[1]);
}

Compile it with gcc then set suid permission (root user now):

# gcc suid.c -o suid
# chmod +s suid

I tried to run ./suid id with the www-data user on different virtual machines, but the output is different.

The output in kali 2019: id=33(www-data) gid=33(www-data) groups=33(www-data)

The output in ubuntu trusty(a old linux): uid=33(www-data) gid=33(www-data) euid=0(root) egid=0(root) groups=0(root),33(www-data)

Why is that? Has anything changed in Linux?


问:
can someone help me on one of my website l deployed, facing redirection warning and tried to fix it not to no avail
```<code>  <?php
include('security.php');

if (isset($_POST['login_btn'])) {
    $email_login = $_POST['email'];
    $password_login = $_POST['password'];

    $query = "SELECT * FROM register WHERE email='$email_login' AND password='$password_login' ";
    $query_run = mysqli_query($connection, $query);
    $usertypes = mysqli_fetch_array($query_run);

    if ($usertypes['usertype'] == "admin") {
        $_SESSION['username'] = $email_login;
        header('Location:/index.php');

    } else if($usertypes['usertype'] == "user"){
        $_SESSION['username'] = $email_login;
        header('Location:../index.php');

    }else{
        $_SESSION['status'] = "Email or Password is invalid";
        header('Location:login.php');
    }
}
?>
</code>```

Warning: Cannot modify header information - headers already sent by
  (output started at
      /home/imvvsmcb/public_html/admin/database/dbconfig.php:1) in
      /home/imvvsmcb/public_html/admin/logincode.php on line 14

答: thanks for all your help, l fixed it the problem is not in the file l though it was, the bug was in my dbconfig file l had a link to my css</p>

Body:
  <?php
include('security.php');

if (isset($_POST['login_btn'])) {
    $email_login = $_POST['email'];
    $password_login = $_POST['password'];

    $query = "SELECT * FROM register WHERE email='$email_login' AND password='$password_login' ";
    $query_run = mysqli_query($connection, $query);
    $usertypes = mysqli_fetch_array($query_run);

    if ($usertypes['usertype'] == "admin") {
        $_SESSION['username'] = $email_login;
        header('Location:/index.php');

    } else if($usertypes['usertype'] == "user"){
        $_SESSION['username'] = $email_login;
        header('Location:../index.php');

    }else{
        $_SESSION['status'] = "Email or Password is invalid";
        header('Location:login.php');
    }
}
?>

Warning: Cannot modify header information - headers already sent by
  (output started at
      /home/imvvsmcb/public_html/admin/database/dbconfig.php:1) in
      /home/imvvsmcb/public_html/admin/logincode.php on line 14


问:
how to randomly select from a list in a column of lists in a pandas dataframe
I have the following dataframe:

```<code>MyAge    Ages       Names
7       [3,10,15]   ['Tom','Jack','Sara']
6       [12,6,5,13] ['Nora','Betsy','John','Jill']
15      [24,3,65,15]['Tala','Jane','Bill','Mark']
</code>```

I want to generate a new column that produces a randomly selected name for each row from the list of Names, so that the age of the person with that randomly selected name is less than or equal to MyAge. The column Ages reflects the ages of each person in the Names column.

So one possible outcome is the following:

```<code>MyAge    Ages       Names                             RandomName   RandomPersonAge
7       [3,10,15]   ['Tom','Jack','Sara']             'Tom'        3
6       [12,6,5,13] ['Nora','Betsy','John','Jill']    'Betsy'      6
15      [24,3,65,15]['Tala','Jane','Bill','Mark']     'Jane'       3
</code>```

答:
Given that the number of ages and names can be different for each row, first create a random index to based on the number of ages/names per row using a list comprehension.  Then use more list comprehensions to index the names and ages. Finally, assign the results back to the original dataframe.

```<code># Sample data.
df = pd.DataFrame({
    "MyAge": [7, 6, 15],
    "Ages": [[3, 10, 15], [12, 6, 5, 13], [24, 3, 65, 15]],
    "Names": [['Tom', 'Jack', 'Sara'], ['Nora', 'Betsy', 'John', 'Jill'], ['Tala', 'Jane', 'Bill', 'Mark']]
})

# Solution.
np.random.seed(0)
random_index = [np.random.randint(len(ages)) for ages in df['Ages']]
names = [names[idx] for idx, names in zip(random_index, df['Names'])]
ages = [ages[idx] for idx, ages in zip(random_index, df['Ages'])]
>>> df.assign(RandomName=names, RandomPersonAge=ages)
    MyAge   Ages        Names                     RandomName    RandomPersonAge
0   7   [3, 10, 15]     [Tom, Jack, Sara]         Tom            3
1   6   [12, 6, 5, 13]  [Nora, Betsy, John, Jill] Jill          13
2   15  [24, 3, 65, 15] [Tala, Jane, Bill, Mark]  Jane           3
</code>```

To choose the random ages such that they are less than or equal to the value in MyAge, we should first flatten the data.  We'll use a conditional, nested list comprehension to filter the data such that each row contains the index together with the name and equivalent age where the age is less than or equal to MyAge.  We'll then create a dataframe from this filtered data and set the index based on the first column which is the name to the original dataframe's index. The rows in the dataframe are randomly shuffled via sample(frac=1).  We then group on the index and take the first random row.  We then join the result back to the original dataframe (the join is done based on the index by default).

```<code>filtered_data = (
    [(idx, name, age)
     for idx, (my_age, ages, names) in df.iterrows()
     for age, name in zip(ages, names)
     if age <= my_age]
)
random_names_and_ages = (
    pd.DataFrame(filtered_data, columns=[df.index.name, 'RandomName', 'RandomPersonAge'])
    .set_index(df.index.name)
    .sample(frac=1)  # Randomly huffle the rows in the dataframe.
    .groupby(level=0)[['RandomName', 'RandomPersonAge']]  # Groupby 'ID' and take the first random row.
    .first()
)
>>> df.join(random_names_and_ages)
   MyAge             Ages                      Names RandomName  \
0      7      [3, 10, 15]          [Tom, Jack, Sara]        Tom
1      6   [12, 6, 5, 13]  [Nora, Betsy, John, Jill]       John
2     15  [24, 3, 65, 15]   [Tala, Jane, Bill, Mark]       Jane

   RandomPersonAge
0                3
1                5
2                3
</code>```

Body:
I have the following dataframe:

MyAge    Ages       Names
7       [3,10,15]   ['Tom','Jack','Sara']
6       [12,6,5,13] ['Nora','Betsy','John','Jill']
15      [24,3,65,15]['Tala','Jane','Bill','Mark']

I want to generate a new column that produces a randomly selected name for each row from the list of Names, so that the age of the person with that randomly selected name is less than or equal to MyAge. The column Ages reflects the ages of each person in the Names column.

So one possible outcome is the following:

MyAge    Ages       Names                             RandomName   RandomPersonAge
7       [3,10,15]   ['Tom','Jack','Sara']             'Tom'        3
6       [12,6,5,13] ['Nora','Betsy','John','Jill']    'Betsy'      6
15      [24,3,65,15]['Tala','Jane','Bill','Mark']     'Jane'       3

Body:
Given that the number of ages and names can be different for each row, first create a random index to based on the number of ages/names per row using a list comprehension.  Then use more list comprehensions to index the names and ages. Finally, assign the results back to the original dataframe.

# Sample data.
df = pd.DataFrame({
    "MyAge": [7, 6, 15],
    "Ages": [[3, 10, 15], [12, 6, 5, 13], [24, 3, 65, 15]],
    "Names": [['Tom', 'Jack', 'Sara'], ['Nora', 'Betsy', 'John', 'Jill'], ['Tala', 'Jane', 'Bill', 'Mark']]
})

# Solution.
np.random.seed(0)
random_index = [np.random.randint(len(ages)) for ages in df['Ages']]
names = [names[idx] for idx, names in zip(random_index, df['Names'])]
ages = [ages[idx] for idx, ages in zip(random_index, df['Ages'])]
>>> df.assign(RandomName=names, RandomPersonAge=ages)
    MyAge   Ages        Names                     RandomName    RandomPersonAge
0   7   [3, 10, 15]     [Tom, Jack, Sara]         Tom            3
1   6   [12, 6, 5, 13]  [Nora, Betsy, John, Jill] Jill          13
2   15  [24, 3, 65, 15] [Tala, Jane, Bill, Mark]  Jane           3

To choose the random ages such that they are less than or equal to the value in MyAge, we should first flatten the data.  We'll use a conditional, nested list comprehension to filter the data such that each row contains the index together with the name and equivalent age where the age is less than or equal to MyAge.  We'll then create a dataframe from this filtered data and set the index based on the first column which is the name to the original dataframe's index. The rows in the dataframe are randomly shuffled via sample(frac=1).  We then group on the index and take the first random row.  We then join the result back to the original dataframe (the join is done based on the index by default).

filtered_data = (
    [(idx, name, age)
     for idx, (my_age, ages, names) in df.iterrows()
     for age, name in zip(ages, names)
     if age <= my_age]
)
random_names_and_ages = (
    pd.DataFrame(filtered_data, columns=[df.index.name, 'RandomName', 'RandomPersonAge'])
    .set_index(df.index.name)
    .sample(frac=1)  # Randomly huffle the rows in the dataframe.
    .groupby(level=0)[['RandomName', 'RandomPersonAge']]  # Groupby 'ID' and take the first random row.
    .first()
)
>>> df.join(random_names_and_ages)
   MyAge             Ages                      Names RandomName  \
0      7      [3, 10, 15]          [Tom, Jack, Sara]        Tom
1      6   [12, 6, 5, 13]  [Nora, Betsy, John, Jill]       John
2     15  [24, 3, 65, 15]   [Tala, Jane, Bill, Mark]       Jane

   RandomPersonAge
0                3
1                5
2                3


问:
Get values from OkHttp Response Java
I am trying to get values from a OkHttp response body string but am getting the following error

```<code>java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
</code>```

The response body string looks like this( response.body().toString() )

```<code>        {
            "MerchantRequestID":"000000000000",
            "CheckoutRequestID":"170220202216211826",
            "ResponseCode": "0",
            "ResponseDescription":"Request accepted for processing",
            "CustomerMessage":"Request accepted for processing"
        }
</code>```

I am parsing it like this

```<code>Gson g = new Gson();
SuccessResponse resp = g.fromJson(resp.body().toString(),SuccessResponse.class);
</code>```

How do i get the individual values from the response string.

答:
You can create POJO with that fields (manually or using services like this ). Then you can create instance of your POJO this way : </p>

```<code>String json = "{'MerchantRequestID': '000000000000','CheckoutRequestID':'170220202216211826','ResponseCode': '0','ResponseDescription':'Request accepted for processing','CustomerMessage':'Request accepted for processing'}";
    Gson g = new Gson();
    Example example = g.fromJson(json, Example.class);
    System.out.print(example.getCheckoutRequestID());
</code>```

Title: Get values from OkHttp Response Java

Body:
I am trying to get values from a OkHttp response body string but am getting the following error

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

The response body string looks like this( response.body().toString() )

        {
            "MerchantRequestID":"000000000000",
            "CheckoutRequestID":"170220202216211826",
            "ResponseCode": "0",
            "ResponseDescription":"Request accepted for processing",
            "CustomerMessage":"Request accepted for processing"
        }

I am parsing it like this

Gson g = new Gson();
SuccessResponse resp = g.fromJson(resp.body().toString(),SuccessResponse.class);

How do i get the individual values from the response string.

Body:
You can create POJO with that fields (manually or using services like this ). Then you can create instance of your POJO this way :

String json = "{'MerchantRequestID': '000000000000','CheckoutRequestID':'170220202216211826','ResponseCode': '0','ResponseDescription':'Request accepted for processing','CustomerMessage':'Request accepted for processing'}";
    Gson g = new Gson();
    Example example = g.fromJson(json, Example.class);
    System.out.print(example.getCheckoutRequestID());


问:
Non-parseable POM SpringBoot

My Project was working fine then I needed to add a dependency, After
adding the dependency I was not able to Import class file from newly
added dependency so I Updated the project Maven, Update Project after
that I started facing this issue.

I have tried these options.

```<code>1: Deleted .m2 directory
2: Deleted workspace
3: Re-Installed Maven
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mcs.pmay</groupId>
<artifactId>pmay</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>pmay</name>
<description>PMAY Project - Housing for All</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.6.2</version><!--$NO-MVN-MAN-VER$ -->
    </dependency>
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>de.mkammerer</groupId>
        <artifactId>argon2-jvm</artifactId>
        <version>2.2</version>
    </dependency>
    <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional> </dependency> -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.7</version>
    </dependency>
   <dependency>
     <groupId>javaxt</groupId>
     <artifactId>javaxt-core</artifactId>
     <version>1.8.1</version>
   </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
<repositories>
   <repository>
     <id>javaxt.com</id>
     <url>http://www.javaxt.com/maven</url>
   </repository>
</repositories>
</code>```

``````

答:
If the XML is well formed and there are no issues with the repositories, try using the previous version of Spring boot starter. Example - </p>

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
</code>```

<p>And do a maven update, it should work. </p>

Title: Non-parseable POM SpringBoot

Body:
My Project was working fine then I needed to add a dependency, After
adding the dependency I was not able to Import class file from newly
added dependency so I Updated the project Maven, Update Project after
that I started facing this issue.

I have tried these options.

1: Deleted .m2 directory
2: Deleted workspace
3: Re-Installed Maven

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mcs.pmay</groupId>
<artifactId>pmay</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>pmay</name>
<description>PMAY Project - Housing for All</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.6.2</version>
    </dependency>
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>de.mkammerer</groupId>
        <artifactId>argon2-jvm</artifactId>
        <version>2.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.7</version>
    </dependency>
   <dependency>
     <groupId>javaxt</groupId>
     <artifactId>javaxt-core</artifactId>
     <version>1.8.1</version>
   </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
<repositories>
   <repository>
     <id>javaxt.com</id>
     <url>http://www.javaxt.com/maven</url>
   </repository>
</repositories>

Body:
If the XML is well formed and there are no issues with the repositories, try using the previous version of Spring boot starter. Example -

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

And do a maven update, it should work.


问:
Laravel On-Demand Notification with CC
I'm sending notifications using the facade and it works well for addressing multiple 'to' emails however I need to be able to CC someone else in.

Notification::route('mail', ['user1@domain.com', 'user2@domain.com'])->notify(new InvoicePaid($invoice));

I am hoping to address user1, and cc user2.  Is it possible with the notification facade?

答:
I suppose a solution (not as elegant as I would want), is to include the cc into the array that is passed and then define it in the MailMessage().

$data = array('name' => 'User Name', 'count' => 6, 'body' => 'My str', 'cc' = > 'user2@domain.com');

On the Notification

```<code>public function toMail($notifiable)
    {
        $cc = $this->data['cc'];

return (new MailMessage)
                    ->cc($cc)

</code>```

Title: Laravel On-Demand Notification with CC

Body:
I suppose a solution (not as elegant as I would want), is to include the cc into the array that is passed and then define it in the MailMessage().

$data = array('name' => 'User Name', 'count' => 6, 'body' => 'My str', 'cc' = > 'user2@domain.com');

On the Notification

public function toMail($notifiable)
    {
        $cc = $this->data['cc'];

return (new MailMessage)
                    ->cc($cc)


问:
Perl If with "+", "-", "*", "/"
I have this code:

```<code>print ("First Value: ");
$valor1 = <STDIN>;
print ("Second Value: ");
$valor2 = <STDIN>;
print ("Operator: ");
$op = <STDIN>;
if ($op == "+")
{
    $total = $valor1 + $valor2;
    print ($total);
}

elsif ($op == "-")
{
    $total = $valor1 - $valor2;
    print ($total);
}

elsif ($op== "*")
{
    $total = $valor1 * $valor2;
    print ($total);
}

elsif ($op == "/")
{
    $total = $valor1 / $valor2;
    print ($total);
}
</code>```

He reads everything correctly, but when he enters the condition if the user types "-", "/" or "*" he always enters the first condition and makes a sum and i wanted to figured out why.

答:
Please see the following piece of code which implements few mathematical functions.

Note: comparison == is for numbers, you should use eq for op as it is a string

```<code>use strict;
use warnings;
use feature 'say';

my($a,$b,$op,$total);

$a  = get_input('First Value: ');
$b  = get_input('Second Value: ');
$op = get_input('Operator: ');

$total = $a + $b  if $op eq '+';
$total = $a - $b  if $op eq '-';
$total = $a * $b  if $op eq '*';
$total = $a / $b  if $op eq '/';
$total = $a ** $b if $op eq '**';

say "$a $op $b = $total";

sub get_input {
    my $msg = shift;

    print $msg;
    my $ret = <STDIN>;
    chomp $ret;

    return $ret;
}
</code>```

Title: Perl If with "+", "-", "*", "/"

Body:
I have this code:

print ("First Value: ");
$valor1 = <STDIN>;
print ("Second Value: ");
$valor2 = <STDIN>;
print ("Operator: ");
$op = <STDIN>;
if ($op == "+")
{
    $total = $valor1 + $valor2;
    print ($total);
}

elsif ($op == "-")
{
    $total = $valor1 - $valor2;
    print ($total);
}

elsif ($op== "*")
{
    $total = $valor1 * $valor2;
    print ($total);
}

elsif ($op == "/")
{
    $total = $valor1 / $valor2;
    print ($total);
}

He reads everything correctly, but when he enters the condition if the user types "-", "/" or "*" he always enters the first condition and makes a sum and i wanted to figured out why.

Body:
Please see the following piece of code which implements few mathematical functions.

Note: comparison == is for numbers, you should use eq for op as it is a string

use strict;
use warnings;
use feature 'say';

my($a,$b,$op,$total);

$a  = get_input('First Value: ');
$b  = get_input('Second Value: ');
$op = get_input('Operator: ');

$total = $a + $b  if $op eq '+';
$total = $a - $b  if $op eq '-';
$total = $a * $b  if $op eq '*';
$total = $a / $b  if $op eq '/';
$total = $a ** $b if $op eq '**';

say "$a $op $b = $total";

sub get_input {
    my $msg = shift;

    print $msg;
    my $ret = <STDIN>;
    chomp $ret;

    return $ret;
}


问:
Adding a number to certain elements of an array
I have an array in numpy:

```<code>[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]
</code>```

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

答:
You could create a mask based on your criteria and then add 100 to each value.</p>

```<code>arr = np.array([[1,  2,  3],
                [4,  5,  6],
                [7,  8, 9],
                [10, 11, 12]])
mask = (arr >= 3) & (arr <= 8)
arr[mask] += 100
</code>```

Body:
I have an array in numpy:

[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

Body:
You could create a mask based on your criteria and then add 100 to each value.

arr = np.array([[1,  2,  3],
                [4,  5,  6],
                [7,  8, 9],
                [10, 11, 12]])
mask = (arr >= 3) & (arr <= 8)
arr[mask] += 100


问:
How can I use onClick on stateless component in React?
I want to use onClick on a stateless compoenent but it's reject an error like : onClick listener to be a function, instead got a value of object type.

I need to show and hide component on click.
Example when I click on the <ResultCard/> component I want to hide him and show <ResultDetail/>

State React Component :

```<code>import React, { Component } from "react";
import ResultCard from "./ResultCard";
import "../../assets/css/Result.css";
import Spinner from "../Spinner";
import { getApiToken, getParisByPrice } from "../../services/api";
import Modal from "../Modal";
import "../../assets/css/BudgetEntry.css";
import modify from "../../assets/images/modify.png";
import ResultDetail from "./ResultDetail";

class Results extends Component {
  state = {
    priceValue: "",
    showResult: true
  };

  showResultDetail = () => {

    this.setState({ showResult: false });
  };

  closeResultDetails = () => {

    this.setState({ showResult: true });
  };

  render() {
    return (
      <div className="results-container">

        {this.state.loading ? (
          <Spinner />
        ) : (
          <div className={"row"}>
            {this.state.showResult ?
            (
              this.state.paris.map(details => (
                <ResultCard
                  key={details.id}
                  id={details.id}
                  showResultDetail={this.showResultDetail}
                  prefix={details.prefix}
                  costPerDay={details.average_cost_per_day}
                  logoSports={details.infrastructure.map(home =>
                    home.logo_path.map(path_image => (
                      <img
                        src={path_image}
                        alt="icon-sports"
                        style={{ width: 20 }}
                        key={path_image}
                      />
                    ))
                  )}
                />
              ))
            )
              :
            (
              <ResultDetail closeResultDetail={this.closeResultDetails}/>
            )
            }
          </div>
        )}
      </div>
    );
  }
}

export default Results;

</code>```

ResultCard (who is stateless component):

```<code>import React from 'react';
import '../../assets/css/ResultCard.css';

const ResultCard = ({prefix, costPerDay, logoSports, showResultDetail, id}) => {

  return (
    <div className="card" onClick={showResultDetail} id={id}>
      <p style={{margin:5}}>{prefix}</p>
      <p style={{margin:1}}>arrondissement</p>
      <p>{costPerDay} $</p>
      {logoSports}
    </div>
  )

};

export default ResultCard;
</code>```

ResultDetail (who is stateless component):

```<code>import React from 'react';

const ResultDetail = (closeResultDetail) => (

      <div onClick={closeResultDetail}>
        <p>Result detail</p>
      </div>
)

export default ResultDetail;
</code>```

thank for your help

答:
in Results you define

```<code>showResultDetail = () => {
    this.setState( {showResult: false });
};
</code>```

as a function without arguments. You then pass

```<code>showResultDetail={(e) => this.showResultDetail(e)}
</code>```

as a function with an event argument to your ResultCard. If you change that to

```<code>showResultDetail={this.showResultDetail}
</code>```

your problem might already be fixed.

Edit: Here is a minimal snippet that does what you're looking for, I think.

const ResultCard = ({showResultDetail, show}) => {
  return
{show?'Click me!':''}

};
class Results extends React.Component {
  state = {
    priceValue: "",
    showResult: true
  };
  showResultDetail = () => {
    this.setState({ showResult: false });
  };
  render() {
      return <ResultCard show={this.state.showResult}
           showResultDetail={this.showResultDetail}/>
  }
}
ReactDOM.render(<Results/>, document.getElementById('root'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  width: 200px;
  height: 50px;
  background: lightgray;
  text-align: center;
  line-height: 50px;
}</code>```

```

Body:
I want to use onClick on a stateless compoenent but it's reject an error like : onClick listener to be a function, instead got a value of object type.

I need to show and hide component on click.
Example when I click on the <ResultCard/> component I want to hide him and show <ResultDetail/>

State React Component :

import React, { Component } from "react";
import ResultCard from "./ResultCard";
import "../../assets/css/Result.css";
import Spinner from "../Spinner";
import { getApiToken, getParisByPrice } from "../../services/api";
import Modal from "../Modal";
import "../../assets/css/BudgetEntry.css";
import modify from "../../assets/images/modify.png";
import ResultDetail from "./ResultDetail";

class Results extends Component {
  state = {
    priceValue: "",
    showResult: true
  };

  showResultDetail = () => {

    this.setState({ showResult: false });
  };

  closeResultDetails = () => {

    this.setState({ showResult: true });
  };

  render() {
    return (

        {this.state.loading ? (
          <Spinner />
        ) : (

            {this.state.showResult ?
            (
              this.state.paris.map(details => (
                <ResultCard
                  key={details.id}
                  id={details.id}
                  showResultDetail={this.showResultDetail}
                  prefix={details.prefix}
                  costPerDay={details.average_cost_per_day}
                  logoSports={details.infrastructure.map(home =>
                    home.logo_path.map(path_image => (

                    ))
                  )}
                />
              ))
            )
              :
            (
              <ResultDetail closeResultDetail={this.closeResultDetails}/>
            )
            }

        )}

    );
  }
}

export default Results;

ResultCard (who is stateless component):

import React from 'react';
import '../../assets/css/ResultCard.css';

const ResultCard = ({prefix, costPerDay, logoSports, showResultDetail, id}) => {

  return (

{prefix}

arrondissement

{costPerDay} $

      {logoSports}

  )

};

export default ResultCard;

ResultDetail (who is stateless component):

import React from 'react';

const ResultDetail = (closeResultDetail) => (

Result detail

)

export default ResultDetail;

thank for your help

Body:
in Results you define

showResultDetail = () => {
    this.setState( {showResult: false });
};

as a function without arguments. You then pass

showResultDetail={(e) => this.showResultDetail(e)}

as a function with an event argument to your ResultCard. If you change that to

showResultDetail={this.showResultDetail}

your problem might already be fixed.

Edit: Here is a minimal snippet that does what you're looking for, I think.

const ResultCard = ({showResultDetail, show}) => {
  return <div className="card" onClick={showResultDetail}>{show?'Click me!':''}</div>
};
class Results extends React.Component {
  state = {
    priceValue: "",
    showResult: true
  };
  showResultDetail = () => {
    this.setState({ showResult: false });
  };
  render() {
      return <ResultCard show={this.state.showResult}
           showResultDetail={this.showResultDetail}/>
  }
}
ReactDOM.render(<Results/>, document.getElementById('root'))

.card {
  width: 200px;
  height: 50px;
  background: lightgray;
  text-align: center;
  line-height: 50px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id='root'></div>


问:
axios use of data server argument
I am trying to axios to contact a remote server
If I used the following format, my server never seems to parse the data arguments

```<code>axios({
    url: API_URL + 'oauth/token',
    method:'post',
    data: {
        grant_type: 'password',
        username: user.username,
        password: user.password,
        scope: 'webclient'
          },
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })
</code>```

But if I use the vulgar format

```<code>axios({
    url: API_URL + 'oauth/token',
    method: 'post',
       data:'grant_type=password&username='+user.username+'&password='+user.password+'&scope=webclient',
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })
</code>```

Every works as expected, so can anybody tell me what the difference is between the two different forms of the data argument?

答:
As suggested by both previous answers, the issue is the type of data the server is prepared to accept, with out setting a Content-Type, axious defaults to Json.

In my case my server is configure to accept URL encode style connection.  Sending it as a 'data' object is invalid, it most be sent using params.  Since I am not sending any data using data: it seems that axios decides that it can remove any attempt by myself to set a Content-Type.

I am using the following code that removes that vulgar data set up

```<code>url: API_URL + 'oauth/token',
    method:'post',
       params: {
        grant_type: 'password',
        username: user.username,
        password: user.password,
        scope: 'webclient'
          },
    auth: {
        username:'foo',
        password:'foobar'
    },
    responseType:'json',
  })
</code>```

Title: axios use of data server argument

Body:
I am trying to axios to contact a remote server
If I used the following format, my server never seems to parse the data arguments

axios({
    url: API_URL + 'oauth/token',
    method:'post',
    data: {
        grant_type: 'password',
        username: user.username,
        password: user.password,
        scope: 'webclient'
          },
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })

But if I use the vulgar format

axios({
    url: API_URL + 'oauth/token',
    method: 'post',
       data:'grant_type=password&username='+user.username+'&password='+user.password+'&scope=webclient',
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })

Every works as expected, so can anybody tell me what the difference is between the two different forms of the data argument?

Body:
As suggested by both previous answers, the issue is the type of data the server is prepared to accept, with out setting a Content-Type, axious defaults to Json.

In my case my server is configure to accept URL encode style connection.  Sending it as a 'data' object is invalid, it most be sent using params.  Since I am not sending any data using data: it seems that axios decides that it can remove any attempt by myself to set a Content-Type.

I am using the following code that removes that vulgar data set up

url: API_URL + 'oauth/token',
    method:'post',
       params: {
        grant_type: 'password',
        username: user.username,
        password: user.password,
        scope: 'webclient'
          },
    auth: {
        username:'foo',
        password:'foobar'
    },
    responseType:'json',
  })


问:
ARM Cortex-M3 PC loaded with invalid address?
On a device with 128kB flash (0x0-0x0001FFFF) and 20kB SRAM (0x20000000-0x20004FFF), why would the PC (program counter) be set to an address in the range 0x1001xxxx?

Am I looking at incorrect disassembly?

Are there "special" bits used by the ARM core?

Is that an access to a flash region that I have not yet found the documentation for?

...?

答:
Anything below 0x20000000 is valid code address space for Cortex-M. This could be implemented as ROM, flash, or remapped RAM - it's entirely device specific.

If it's immediately after boot, some type of ROM wouldn't be unsurprising, but a better answer will need more details of device and exactly when this occurs ...


问:
Storing usage data about iOS app against the app store guidelines?
What I would like to know is whether there is anything wrong (in terms of the law, and App Store guidelines) with storing information about your application, and broadcasting it to an online location for gathering.

Specifically, an application which would normally not connect to the internet, connecting when it starts up and storing usage information like time of day, the device ID, and how long the person uses it for.

I'm guessing this sort of behavior is fine so long as you get the users consent first?

答: It’s fine if you ask the user first and give him an option to turn this feature off. We were once spanked out of the App Store simply for uploading a new game high-score record without a cancel button. It’s quite a long time and the rules might have changed, but better safe then sorry and your users will like the confirmation screen, too.</p>


问:
Output the index of map()
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}</code>```

```

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

答:
You have to apply the innerHTML while you're mapping through the values and use the += assignment operator to concatenate each value.</p>

```<code>const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
arr.map(val => div.innerHTML += `<div class='it'>${val}</div>`)
</code>```

Title: Output the index of map()

Body:
I want to output the index of each element using map().

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');

* {
    margin: 0;
    padding: 0;
}
.it {
    border: 2px solid;
    background-color: burlywood;
    color: white;
    width: 60px;
    height: 50px;
}

How to output indexes of each element inside div.innerHTML = arr.map((index,val) => "
"+val+"
" ).join('');?

Body:
You have to apply the innerHTML while you're mapping through the values and use the += assignment operator to concatenate each value.

const arr = [1,2,3,4,5,6,7,8,9];
const div = document.querySelector('.container')
arr.map(val => div.innerHTML += `<div class='it'>${val}</div>`)