问:
What is the correct way to use a value converter to assign a selector(drawable) in mvvm cross
I have a View

```<code><Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
         android:background="@drawable/sel_fragfinder_toolbar_selection_selected"
            local:MvxBind="Drawable DiscoverYourScent;Converter=ButtonState"
            android:layout_weight="1"
            android:textColor="@android:color/white"
            android:textAllCaps="false"
            android:layout_marginRight="10dp"
            android:padding="10dp"
            android:text="Discover your scent" />
</code>```

Where I have bind property for converter:

```<code>public class ButtonStateValueConverter : MvxValueConverter<bool,int>
    {
        protected override int Convert(bool value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value) {
              return  Resource.Drawable.sel_fragfinder_toolbar_selection_selected;
            }else{
              return  Resource.Drawable.sel_fragfinder_toolbar_selection_not_selected;
            }
        }
    }
</code>```

In View Model, I am setting

```<code>private bool _discoverYourScent;
        public bool DiscoverYourScent
        {
            get { return _discoverYourScent; }
            set { _discoverYourScent = value; RaisePropertyChanged(() => DiscoverYourScent); }
        }
</code>```

And I am setting DiscoverYourScent = true;

Currently It is not setting .... What is the correct way to use a value converter to assign a selector(drawable) in mvvm cross

答:
Your binding expression is:

```<code>Drawable DiscoverYourScent;Converter=ButtonState
</code>```

The problem here is that you have a ; semicolon between your Source Target assignment and your Converter statements.

It needs to be a , comma.

```<code>Drawable DiscoverYourScent, Converter=ButtonState
</code>```

Alternatively you can also write:

```<code>Drawable ButtonState(DiscoverYourScent)
</code>```

You should see your ValueConverter be hit now if the rest of the binding is correct. I believe you want to bind to Background as Source and not Drawable. Latter does not seem to be a public property on Button.

As Kiliman points out in the comments to the OP, you could also try your luck setting the Selected property instead, and don't change your Drawable. Just make sure the Drawable you use has the correct states.

Body:
I have a View

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
         android:background="@drawable/sel_fragfinder_toolbar_selection_selected"
            local:MvxBind="Drawable DiscoverYourScent;Converter=ButtonState"
            android:layout_weight="1"
            android:textColor="@android:color/white"
            android:textAllCaps="false"
            android:layout_marginRight="10dp"
            android:padding="10dp"
            android:text="Discover your scent" />

Where I have bind property for converter:

public class ButtonStateValueConverter : MvxValueConverter<bool,int>
    {
        protected override int Convert(bool value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value) {
              return  Resource.Drawable.sel_fragfinder_toolbar_selection_selected;
            }else{
              return  Resource.Drawable.sel_fragfinder_toolbar_selection_not_selected;
            }
        }
    }

In View Model, I am setting

private bool _discoverYourScent;
        public bool DiscoverYourScent
        {
            get { return _discoverYourScent; }
            set { _discoverYourScent = value; RaisePropertyChanged(() => DiscoverYourScent); }
        }

And I am setting DiscoverYourScent = true;

Currently It is not setting .... What is the correct way to use a value converter to assign a selector(drawable) in mvvm cross

Body:
Your binding expression is:

Drawable DiscoverYourScent;Converter=ButtonState

The problem here is that you have a ; semicolon between your Source Target assignment and your Converter statements.

It needs to be a , comma.

Drawable DiscoverYourScent, Converter=ButtonState

Alternatively you can also write:

Drawable ButtonState(DiscoverYourScent)

You should see your ValueConverter be hit now if the rest of the binding is correct. I believe you want to bind to Background as Source and not Drawable. Latter does not seem to be a public property on Button.

As Kiliman points out in the comments to the OP, you could also try your luck setting the Selected property instead, and don't change your Drawable. Just make sure the Drawable you use has the correct states.


来源: stackexchange

问:
Unable to Creating Work Profile (Profile owner) in Some Android 5.0+ devices?
I am facing one problem and i am not getting solution on internet. My problem is- in some devices like samsung and motorola which have android 5.0+ version i am unable to create work profile(TestDPC app on playstore). What's the reason please if anybody know explain it please.
This is the code checked by android at time of work profile creation-

```<code>  PackageManager pm=getPackageManager();
    System.out.println(" can create profile="+ pm.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));
</code>```

Is There an option to change that thing so that i can create a work profile in every device.

Thank you

答:
By checking code

```<code>pm.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));
</code>```

if device has a managed user than only it can create a work profile otherwise won't allow to create work profile.Device should have this managed user feature.

ContentLicense: CC BY-SA 3.0

Body:
I am facing one problem and i am not getting solution on internet. My problem is- in some devices like samsung and motorola which have android 5.0+ version i am unable to create work profile(TestDPC app on playstore). What's the reason please if anybody know explain it please.
This is the code checked by android at time of work profile creation-

  PackageManager pm=getPackageManager();
    System.out.println(" can create profile="+ pm.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));

Is There an option to change that thing so that i can create a work profile in every device.

Thank you

Body:
By checking code

pm.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));

if device has a managed user than only it can create a work profile otherwise won't allow to create work profile.Device should have this managed user feature.


问:
How to modify only one element in a react .map function?
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case? </p>

```<code>changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (
    <div>
    <ul className="list-group">
    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>
        <div className="commentHolder" key={i}>
            <p>{secondData.text}</p>
            <p>{secondData.category}</p>
            <p>{secondData.organization}</p>
            <button> UpButton </button> <br />
            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}
        </div>
      )
    )}
    </ul>
    </div>
  )
}
</code>```

答:
You can keep track of which comment should have SetComment component instead.

constructor(props) {
  super(props);
  this.state = {
    // init commentReplyIds as empty array
    commentReplyIds : [],
    // ... rest of your state
  }
}

changeIsReply(commentId) {
  const newCommentReplyIds = [...this.state.commentReplyIds. commentId];
  this.setState(
    {commentReplyIds: newCommentReplyIds}
  );
}

  render() {
  // in here I am using the data.text as the unique id of each comment, you can use other serializable value.
  return (

    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>

{secondData.text}

{secondData.category}

{secondData.organization}

            <button> UpButton </button>

            <button> DownButton </button>
            <button onClick = {() => this.changeIsReply(secondData.text)} > Reply </button>
            {this.state.commentReplyIds.includes(secondData.text) ? <SetComment id={secondData.key} /> : null}

      )
    )}

  )
}```

With this approach, you can have multiple SetComment components, in different comments of which the user has clicked the reply comment button.

Body:
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case?

changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (

    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>

{secondData.text}

{secondData.category}

{secondData.organization}

            <button> UpButton </button>

            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}

      )
    )}

  )
}

Body:
You can keep track of which comment should have SetComment component instead.

constructor(props) {
  super(props);
  this.state = {
    // init commentReplyIds as empty array
    commentReplyIds : [],
    // ... rest of your state
  }
}

changeIsReply(commentId) {
  const newCommentReplyIds = [...this.state.commentReplyIds. commentId];
  this.setState(
    {commentReplyIds: newCommentReplyIds}
  );
}

  render() {
  // in here I am using the data.text as the unique id of each comment, you can use other serializable value.
  return (
    <div>
    <ul className="list-group">
    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>
        <div className="commentHolder" key={i}>
            <p>{secondData.text}</p>
            <p>{secondData.category}</p>
            <p>{secondData.organization}</p>
            <button> UpButton </button> <br />
            <button> DownButton </button>
            <button onClick = {() => this.changeIsReply(secondData.text)} > Reply </button>
            {this.state.commentReplyIds.includes(secondData.text) ? <SetComment id={secondData.key} /> : null}
        </div>
      )
    )}
    </ul>
    </div>
  )
}

With this approach, you can have multiple SetComment components, in different comments of which the user has clicked the reply comment button.


问:
Prgrammably making excel spreadsheets (97 - 2003 format)
I was wondering how difficult it would be to make an application like this. Basically, I have some old html files that use tables. I want to put these tables into excel for easier reading and manipulation. I only have text, I have no numbers of formulas or anything.

Are there any tutorials on how to do this sort of thing?

The application would produce .xls

Thanks

答:
You don't need to reverse-engineer the XLS format; Microsoft documents the excel file format here. Due to the evolution of Excel over the years, it's not exactly a clean specification.

If you don't mind installing a copy of Excel along with your program, using OLE Automation would be much easier.

ContentLicense: CC BY-SA 2.5


问:
Error: JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-8-oracle/jre/bin/java when i run gradle command in terminal
I am working in Ubuntu 16.04. I need to install gradle and the gradle is installed when i checked with sudo apt list --installed command but when i use gradle -version command it shows the following error,
JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-8-oracle/jre/bin/java

In sudo vim /etc/environment file,

```<code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/"
http_proxy="http://username:password@IP:port no/"
https_proxy="https://IP:port no/"
ftp_proxy="ftp://IP:port no/"
</code>```

I don't know where i made mistakes. Please help me.

Thanks.

答:
I see a mismatch. In your enviornment file the JAVA_HOME is set to "/usr/lib/jvm/java-8-openjdk-amd64/" and your mentioned that the error that you got relates to the JAVA_HOME as "/usr/lib/jvm/java-8-oracle/jre/bin/java"

If you JAVA is really installed in /usr/lib/jvm/java-8-oracle directory, then you need to ensure that the JAVA_HOME is set to that directory. And also your PATH reflects $JAVA_HOME/bin in it.

I typically install Oracle JDK/JRE separately in a separate directory such as /usr/local/jdk1.8.0 etc.

Body:
I am working in Ubuntu 16.04. I need to install gradle and the gradle is installed when i checked with sudo apt list --installed command but when i use gradle -version command it shows the following error,
JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-8-oracle/jre/bin/java

In sudo vim /etc/environment file,

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/"
http_proxy="http://username:password@IP:port no/"
https_proxy="https://IP:port no/"
ftp_proxy="ftp://IP:port no/"

I don't know where i made mistakes. Please help me.

Thanks.


问:
How can print Laravel variable with echo
```<code><?php echo Form::open(['method' => 'POST', 'url' => ['/cart/add/'. "{{$product->product_id }}"]] )?>
<?php echo Form::button('Agregar al Carro', ['class' => 'btn-u btn-u-sea-shop btn-u-lg', 'type' => 'submit']) ?>
<?php echo Form::close()  ?>
</code>```

I need to print the variable $product in a template.

答:
you can print variable like that in blade

{{$product}}

see for more details in laravel official site

Body:
<?php echo Form::open(['method' => 'POST', 'url' => ['/cart/add/'. "{{$product->product_id }}"]] )?>
<?php echo Form::button('Agregar al Carro', ['class' => 'btn-u btn-u-sea-shop btn-u-lg', 'type' => 'submit']) ?>
<?php echo Form::close()  ?>

I need to print the variable $product in a template.


问:
Get Id from url() in angular
How to get id from url()
This is my url

```<code>http://localhost:59113/Project/EditProject?id=2
</code>```

I did it using jquery..

```<code>var url = document.URL;
        var id = /id=([^&]+)/.exec(url)[1];
        var result = id ? id : ' ';
</code>```

But I need to do it using angular.Can anyone help me?
I tried this too(updated part)

```<code> var app = angular
                .module("intranet_App", [])
                    app.config("$routeProvider", function ($routeProvider) {
                        $routeProvider.when('/view1/:param1/:param2', {
                            templateUrl: 'Project/EditProject.html',
                            controller: 'myCtrl'
                        })
                    })
                    .controller("myCtrl", ["$scope", "$http", "$location", "$route",  function ($scope, $http, $location, $route) {
                    // alert($location.id)
                    var a = $route.current.params;
                    alert(a.id)
                }])
</code>```

答:
Using $routeParams you can get id,

Updated answer

Use $route instead of $routeParams. Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.

```<code>$route.current.params
</code>```

EDIT

You must do this in .config() method

```<code>app.config(function($routeProvider){
      $routeProvider.when('/view1/:param1/:param2', {
            templateUrl: 'Project/EditProject.html',
            controller: 'myCtrl'
      })
})
</code>```

Title: Get Id from url() in angular

Body:
How to get id from url()
This is my url

http://localhost:59113/Project/EditProject?id=2

I did it using jquery..

var url = document.URL;
        var id = /id=([^&]+)/.exec(url)[1];
        var result = id ? id : ' ';

But I need to do it using angular.Can anyone help me?
I tried this too(updated part)

 var app = angular
                .module("intranet_App", [])
                    app.config("$routeProvider", function ($routeProvider) {
                        $routeProvider.when('/view1/:param1/:param2', {
                            templateUrl: 'Project/EditProject.html',
                            controller: 'myCtrl'
                        })
                    })
                    .controller("myCtrl", ["$scope", "$http", "$location", "$route",  function ($scope, $http, $location, $route) {
                    // alert($location.id)
                    var a = $route.current.params;
                    alert(a.id)
                }])

Body:
Using $routeParams you can get id,

Updated answer

Use $route instead of $routeParams. Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.

$route.current.params

EDIT

You must do this in .config() method

app.config(function($routeProvider){
      $routeProvider.when('/view1/:param1/:param2', {
            templateUrl: 'Project/EditProject.html',
            controller: 'myCtrl'
      })
})


问:
Sending binary through HTTP with React-Native Fetch API
Is there a way to use the Fetch API to upload a binary file (for instance to S3 using a signed URL) ?

That would be a simple PUT for some 'application/octet-stream'.

The XHR library is working, but I believe Fetch is better, especially in a React-Native environment.

Does React-Native Fetch support Blob nowadays?

Ideally I would like to do something like this, but Blob is undefined:

```<code>fetch('https://s3.amazonaws.com/signedUrl/', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/octet-stream',
  },
  body: Blob(filePath)
})
</code>```

答:
I would recommend to use: https://github.com/github/fetch as polyfill for Fetch since is not widely supported.

Fetch documentation sample:

```<code>var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})
</code>```

I am using it as follows:

```<code>var input = document.querySelector('input[type="file"]')

function upload(e) {
  const file = input.files[0];
  const reader = new FileReader();

  reader.onload = (e) => {
    fetch('/avatars', {
      method: 'POST',
      body: e.currentTarget.result
    })
  };

  reader.readAsArrayBuffer(file);
}

input.addEventListener('change', upload, false)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to use the Fetch API to upload a binary file (for instance to S3 using a signed URL) ?

That would be a simple PUT for some 'application/octet-stream'.

The XHR library is working, but I believe Fetch is better, especially in a React-Native environment.

Does React-Native Fetch support Blob nowadays?

Ideally I would like to do something like this, but Blob is undefined:

fetch('https://s3.amazonaws.com/signedUrl/', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/octet-stream',
  },
  body: Blob(filePath)
})

Body:
I would recommend to use: https://github.com/github/fetch as polyfill for Fetch since is not widely supported.

Fetch documentation sample:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

I am using it as follows:

var input = document.querySelector('input[type="file"]')

function upload(e) {
  const file = input.files[0];
  const reader = new FileReader();

  reader.onload = (e) => {
    fetch('/avatars', {
      method: 'POST',
      body: e.currentTarget.result
    })
  };

  reader.readAsArrayBuffer(file);
}

input.addEventListener('change', upload, false)


问:
Is there something wrong with my form?
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

```<code><form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
</code>```

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

```<code>echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';
</code>```

and the vaildator:

```<code>if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}
</code>```

答:
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.

A very basic form handling script would look something like this:

```<code><?php

if ($_SERVER['REQUEST_METHOD'] = 'POST') {
    # do this only if actually handling a POST
    $field1 = $_POST['field1'];
    $field2 = $_POSt['field2'];
    ...etc...

    if ($field1 = '...') {
       // validate $field1
    }
    if ($field2 = '...') {
       // validate $field2
    }
    ... etc...

    if (everything_ok) {
        // do whatever you want with the data. insert into database?
        redirect('elsewhere.php?status=success')
    } else {
       // handle error condition(s)
    }
} // if the script gets here, then the form has to be displayed

<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>

?>
</code>```

Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.

As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.

Title: Is there something wrong with my form?

Body:
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '

Interested in this coupon? Email us!

                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" />

                                              Email: <input name="email" type="text" />

                                              Phone Number: <input name="phone" type="text" />

                                              Comment:

                                              <textarea name="comment" rows="5" cols="30"></textarea>

                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form>

';

and the vaildator:

if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = 'ERROR: Missing Name
';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = 'ERROR: Please Insert a valid Email
';
                                                }
                                                if ($errors) {
                                                    echo '
There were some errors:
 ';
                                                    echo '

', implode('

', $errors), '

';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'Message has been sent
';
                                                }
}

Body:
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.

A very basic form handling script would look something like this:

<?php

if ($_SERVER['REQUEST_METHOD'] = 'POST') {
    # do this only if actually handling a POST
    $field1 = $_POST['field1'];
    $field2 = $_POSt['field2'];
    ...etc...

    if ($field1 = '...') {
       // validate $field1
    }
    if ($field2 = '...') {
       // validate $field2
    }
    ... etc...

    if (everything_ok) {
        // do whatever you want with the data. insert into database?
        redirect('elsewhere.php?status=success')
    } else {
       // handle error condition(s)
    }
} // if the script gets here, then the form has to be displayed

<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>

?>

Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.

As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.


问:
is it an 'anti-pattern' to grab mobile configuration from a remote, 'configuration' server?
I'm new to mobile development and was wondering if it is an anti-pattern to have a remote, configuration server in order to 'configure' a mobile client.  The idea is to avoid configuration details [except the URL to the configuration server] with the mobile distribution and rather connect to the configuration server to grab other details such as third party keys, service endpoints, etc.  Any thoughts. Thanks in advance!!</p>

答:
So long as you are able to secure connections to the the configuration server, using a username/password and SSL encryption it's not an anti-pattern. It would save you from publishing new applications versions just to update some configuration.

What does however sound like a bad idea to me is keeping third-party API keys inside a mobile application.

Can you guarantee that each an every user using you application will not use the keys placed inside the mobile application to use the third party service to their own ends? I don't think anyone can make that guarantee.


答:
$location.search() returns an object, so as per above url

```<code>http://localhost:59113/Project/EditProject?id=2
</code>```

$location.search().id will fetch you an answer.

More Info:

If you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy, To fix this you need to change the following in config file

```<code>$locationProvider.html5Mode(true);
</code>```

Title: Get Id from url() in angular

Body:
$location.search() returns an object, so as per above url

http://localhost:59113/Project/EditProject?id=2

$location.search().id will fetch you an answer.

More Info:

If you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy, To fix this you need to change the following in config file

$locationProvider.html5Mode(true);


问:
How to save a numeric value in a specified location of a CSV file inside for loops in MATLAB?
I want to do this because otherwise I run out of memory to save the values in a matrix, as the dimensions of the matrix increases.

For example,

```<code>for a=1:10000
   for b=1:10000
      M(a,b)=rand;
   end
end
</code>```

Here, the system runs out of memory as it can't store a 10000x10000 matrix.

So, I want to keep writing the (a,b)'th value inside the for loops into the (a,b)'th cell of a csv file (or an xls file, whatever). How do I do that?

I want something like this:

```<code>for a=1:10000
   for b=1:10000
      xlswrite1('file.xls',a,b,rand); % better if I can get a solution with csvwrite, as I prefer CSVs to work with
   end
end
</code>```

But this obviously doesn't work. The error it gives is:

```<code>Error using evalin
Undefined function or variable 'Excel'.

Error in xlswrite1 (line 2)
Excel=evalin('caller','Excel');
</code>```

Then when I add the following lines according to this article,

```<code>Excel = actxserver ('Excel.Application');
File='datafile.xls';
if ~exist(File,'file')
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);
</code>```

it gives this error:

```<code>Error using xlswrite1 (line 82)
Range argument must a string of Excel A1 notation.
</code>```

Can anyone please suggest a simple solution? I can't find any from my online search so far.

答:
I suggest using fprintf:

```<code>N = 100 ;
M = zeros(1,N) ;
filename1 = 'test1.csv';
t1 = tic ;
for a=1:N
   for b=1:N
      M(1,b)=rand;
   end
   dlmwrite(filename1,M,'-append')

end
t1 = toc(t1) ;

filename2 = 'test2.csv';
M = zeros(1,N) ;
t2 = tic ;
fid = fopen(filename2,'w') ;
for a=1:N
   for b=1:N
      M(1,b)=rand;
   end
   fprintf(fid, [repmat(' %f ', 1, N) '\n'], M') ;

end
fclose(fid) ;
t2 = toc(t2) ;

fprintf('time taken using dlmwrite:%f\n',t1)
fprintf('time taken using fprintf:%f\n',t2)
</code>```

Body:
I want to do this because otherwise I run out of memory to save the values in a matrix, as the dimensions of the matrix increases.

For example,

for a=1:10000
   for b=1:10000
      M(a,b)=rand;
   end
end

Here, the system runs out of memory as it can't store a 10000x10000 matrix.

So, I want to keep writing the (a,b)'th value inside the for loops into the (a,b)'th cell of a csv file (or an xls file, whatever). How do I do that?

I want something like this:

for a=1:10000
   for b=1:10000
      xlswrite1('file.xls',a,b,rand); % better if I can get a solution with csvwrite, as I prefer CSVs to work with
   end
end

But this obviously doesn't work. The error it gives is:

Error using evalin
Undefined function or variable 'Excel'.

Error in xlswrite1 (line 2)
Excel=evalin('caller','Excel');

Then when I add the following lines according to this article,

Excel = actxserver ('Excel.Application');
File='datafile.xls';
if ~exist(File,'file')
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);

it gives this error:

Error using xlswrite1 (line 82)
Range argument must a string of Excel A1 notation.

Can anyone please suggest a simple solution? I can't find any from my online search so far.

Body:
I suggest using fprintf:

N = 100 ;
M = zeros(1,N) ;
filename1 = 'test1.csv';
t1 = tic ;
for a=1:N
   for b=1:N
      M(1,b)=rand;
   end
   dlmwrite(filename1,M,'-append')

end
t1 = toc(t1) ;

filename2 = 'test2.csv';
M = zeros(1,N) ;
t2 = tic ;
fid = fopen(filename2,'w') ;
for a=1:N
   for b=1:N
      M(1,b)=rand;
   end
   fprintf(fid, [repmat(' %f ', 1, N) '\n'], M') ;

end
fclose(fid) ;
t2 = toc(t2) ;

fprintf('time taken using dlmwrite:%f\n',t1)
fprintf('time taken using fprintf:%f\n',t2)


问:
Cascade Delete doesn't work right when deleting intermediate entity
I have 3 entities: Grandpa, Father and Child with the expected relationships
Grandpa has many Fathers and Fathers has many Children

```<code>@Entity
@Table(name = "Grandpa")
public class Grandpa {
     @Id
     @GeneratedValue(generator = "increment")
     @GenericGenerator(name = "increment", strategy = "increment")
     @Column(name = "id")
     private int id;

     @CreationTimestamp
     @Temporal(TemporalType.TIMESTAMP)
     @Column(name = "created_at")
     private Date createdAt;

     @UpdateTimestamp
     @Temporal(TemporalType.TIMESTAMP)
     @Column(name = "updated_at")
     private Date updatedAt;

     @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "grandpa")
     private Set<Father> children = new HashSet<Father>(0);

     ....
}

@Entity
@Table(name = "Father")
public class Father {
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id")
    private int id;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @OneToOne(cascade = {CascadeType.ALL})
    private Grandpa grandpa;

    @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "father")
    private Set<Child> children = new HashSet<Child>(0);

    ....
}

@Entity
@Table(name = "Child")
public class Child {
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id")
    private int id;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @OneToOne(cascade = {CascadeType.ALL})
    private Father father;
}
</code>```

when I delete grandpa, all his fathers and children get deleted as well, but when I delete father, his children stay in the database

What am I missing?

答:
found the problem...

when implementing deletion of Grandpa I used the session.delete(object)
when implementing deletion of Father I used pure sql...

Body:
I have 3 entities: Grandpa, Father and Child with the expected relationships
Grandpa has many Fathers and Fathers has many Children

@Entity
@Table(name = "Grandpa")
public class Grandpa {
     @Id
     @GeneratedValue(generator = "increment")
     @GenericGenerator(name = "increment", strategy = "increment")
     @Column(name = "id")
     private int id;

     @CreationTimestamp
     @Temporal(TemporalType.TIMESTAMP)
     @Column(name = "created_at")
     private Date createdAt;

     @UpdateTimestamp
     @Temporal(TemporalType.TIMESTAMP)
     @Column(name = "updated_at")
     private Date updatedAt;

     @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "grandpa")
     private Set<Father> children = new HashSet<Father>(0);

     ....
}

@Entity
@Table(name = "Father")
public class Father {
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id")
    private int id;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @OneToOne(cascade = {CascadeType.ALL})
    private Grandpa grandpa;

    @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "father")
    private Set<Child> children = new HashSet<Child>(0);

    ....
}

@Entity
@Table(name = "Child")
public class Child {
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id")
    private int id;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @OneToOne(cascade = {CascadeType.ALL})
    private Father father;
}

when I delete grandpa, all his fathers and children get deleted as well, but when I delete father, his children stay in the database

What am I missing?


问:
Check specific row word count in text file based on starting row values
I have text file having content like this below format:

```<code>0001EPP000000084906875   00000   0001
0002EPP000000084906875   00016   0002
0003EPP000000084906875

............

0001EPP000000084967647   00001  0002
0002EPP000000077676678   00016  0002
0003EPP000000084777770
</code>```

I need to loop through all the rows, find the row starting with 0001 and 0002 need to get the corresponding row word count for the same (0001, 0002) with the count, I will do further calculations ...
For this, I have done this:

```<code>string filename = string.Empty;
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
foreach(var file in TXTFiles)
{
    filename = file.Name;
}

var reader = new StreamReader(filename);

foreach(string item in File.ReadAllLines(filename))
{
    // Here I need to check the file content
}
</code>```

Please, could anyone help on this? How to identify the row content and get the word count, if row content matches starting criteria?

答:
There are a couple of things that you can change that should get you where you want to be.

First, you can get rid of the StreamReader line, since File.ReadAllLines is all we need to get the contents.

Second, we should put the code that processes the file inside the foreach (var file ... loop. Otherwise, we're only processing the last file.

Third, you should replace file.Name (which is just the filename) with file.FullName (which includes the full path and file name). Otherwise, you will likely get a FileNotFoundException unless you happen to be searching in the current directory.

And finally, when reading the file, we can use StartsWith to check if the line starts with the text you're looking for, and when we find the line we want, we can use string.Split to break it on the space character into an array. Then it's just a matter of reading the parts you care about from the line.

The code would then look something like this:

```<code>var path = @"c:\public\temp";
DirectoryInfo dir = new DirectoryInfo(path);

foreach (var file in dir.GetFiles("*.txt"))
{
    foreach (var line in File.ReadAllLines(file.FullName))
    {
        if (line.StartsWith("0001") || line.StartsWith("0002"))
        {
            var lineParts = line.Split(new[] { ' ' },
                StringSplitOptions.RemoveEmptyEntries);

            // This is assuming that the word count is in the column (which has index 2)
            if (lineParts.Length > 2)
            {
                var wordCount = lineParts[2];
                Console.WriteLine($"Found data in file {file.Name}:");
                Console.WriteLine($" - Line starts with {lineParts[0].Substring(0, 4)}");
                Console.WriteLine($" - Has word count of {wordCount}");
            }
        }

    }
}
</code>```

Output

Body:
I have text file having content like this below format:

0001EPP000000084906875   00000   0001
0002EPP000000084906875   00016   0002
0003EPP000000084906875

............

0001EPP000000084967647   00001  0002
0002EPP000000077676678   00016  0002
0003EPP000000084777770

I need to loop through all the rows, find the row starting with 0001 and 0002 need to get the corresponding row word count for the same (0001, 0002) with the count, I will do further calculations ...
For this, I have done this:

string filename = string.Empty;
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
foreach(var file in TXTFiles)
{
    filename = file.Name;
}

var reader = new StreamReader(filename);

foreach(string item in File.ReadAllLines(filename))
{
    // Here I need to check the file content
}

Please, could anyone help on this? How to identify the row content and get the word count, if row content matches starting criteria?

Body:
There are a couple of things that you can change that should get you where you want to be.

First, you can get rid of the StreamReader line, since File.ReadAllLines is all we need to get the contents.

Second, we should put the code that processes the file inside the foreach (var file ... loop. Otherwise, we're only processing the last file.

Third, you should replace file.Name (which is just the filename) with file.FullName (which includes the full path and file name). Otherwise, you will likely get a FileNotFoundException unless you happen to be searching in the current directory.

And finally, when reading the file, we can use StartsWith to check if the line starts with the text you're looking for, and when we find the line we want, we can use string.Split to break it on the space character into an array. Then it's just a matter of reading the parts you care about from the line.

The code would then look something like this:

var path = @"c:\public\temp";
DirectoryInfo dir = new DirectoryInfo(path);

foreach (var file in dir.GetFiles("*.txt"))
{
    foreach (var line in File.ReadAllLines(file.FullName))
    {
        if (line.StartsWith("0001") || line.StartsWith("0002"))
        {
            var lineParts = line.Split(new[] { ' ' },
                StringSplitOptions.RemoveEmptyEntries);

            // This is assuming that the word count is in the column (which has index 2)
            if (lineParts.Length > 2)
            {
                var wordCount = lineParts[2];
                Console.WriteLine($"Found data in file {file.Name}:");
                Console.WriteLine($" - Line starts with {lineParts[0].Substring(0, 4)}");
                Console.WriteLine($" - Has word count of {wordCount}");
            }
        }

    }
}

Output


问:
Nodejs req.body shows empty from Android Volley
Android Code:

```<code>private void registerUser(){
        final String username = "subrata";
        final String password = "banerjee";
        final String email = "test_email";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
</code>```

I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.

答:
```<code>private void registerUser(){
       JSONObject jsonBodyObj = new JSONObject();
        try{
            jsonBodyObj.put("mAtt", "+1");
            jsonBodyObj.put("mDatum","+2");
            jsonBodyObj.put("mRID","+3");
            jsonBodyObj.put("mVon","+4");
        }catch (JSONException e){
            e.printStackTrace();
        }
        final String requestBody = jsonBodyObj.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                headers.put("User-agent", "My useragent");
                return headers;
            }
            @Override
            public byte[] getBody() {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                            requestBody, "utf-8");
                    return null;
                }
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
</code>```

Body:
Android Code:

private void registerUser(){
        final String username = "subrata";
        final String password = "banerjee";
        final String email = "test_email";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.


问:
Send uploaded Image in Express
Have an Express application that uploads an image using Multer. What I would like to be able to do is serve that image. The challenge though is when the file is uploaded it does not save the file extension which is by designed from what I've read for security purposes. What I need to be able to do is add the correct extensions to the corresponding mime type.

Technology

Express: 4.15.0

Multer: 1.3.0

mmmagic: 0.4.5

File Structure

```<code>root
  server.js
  /uploads
    /images
      ad58c400e67362118ac1b11f6c4b6c44
      ...
  /routes
    drinks.routes.js
    uploads.routes.js
</code>```

Running this all through Postman. Have form elements name, tagline, image. If I upload "IMG_111.jpg" That image will get uploaded through Multer, validated that it's an image type, and placed in /images/uploads with a new name, default behavior for Multer to create uniqueness. The problem is I have the filename but it is not saved with an extension.

drinks.routes.js

```<code>var upload = multer({
  dest: 'uploads/images',
  fileFilter: function (req, file, callback) {
    console.log('running upload file filter');
      var fileType = file.mimetype;
      if(fileType !== 'image/png' && fileType !== 'image/jpeg' && fileType !== 'image/gif' && fileType !== 'image/jpg') {
          return callback(new Error('Only images are allowed'))
      }
      callback(null, true)
  },
}).single('image');

router.route('/').post(passport.authenticate('jwt', { session: false }), upload, function(req, res, next){
var drink = req.body;
var drinkImage = req.file;
console.log('DRINK IMAGE', drinkImage);

Drink.createDrink(drink, drinkImage, function(err, drink, drinkImage){
  console.log('creating drink');
  if(err){
    res.send(err);
  }
    res.json(drink)
  });
});
</code>```

So I can upload a file, validate the file, save the file with a unique name and no extension. Where I'm have difficulties is then checking the mime type of the requested image, attaching an extension and sending that back in a response.

My original thought is to create a route with the image name requested, use mmmagic to detect the mime type, add the extension and serve that file. But, all attempts at this have failed.

uploads.routes.js

```<code>var express = require('express');
var router = express.Router();
var path = require('path');

var mmm = require('mmmagic');
var Magic = mmm.Magic;
var magic = new Magic(mmm.MAGIC_MIME_TYPE);

router.use(function(req, res, next){
  next();
});

router.route('/images/:filename')
  .get(function(req,res){
    var fileName = req.params.filename;
    var constructFile = function(res){
      magic.detectFile(__dirname + '/../uploads/images/' + fileName, function(err, result) {
        if (err) throw err;
        console.log(result);
        if (result == 'image/jpeg'){
      // return res.sendFile(__dirname + '/../uploads/images/' + fileName + '.jpg');
      res.send(express.static(path.join(__dirname, '/../uploads/images'), {index: false, extensions:['jpg']}));
    }
  });
}

constructFile(res);
  })

module.exports = router;
</code>```

Tried following this SO Which lead me to express.static. But can't figure out at this point if I'm on the right track and just missing something or if I should be looking at this from a different angle.

答:
It's not the cleanest implementation but it does work. Took the advice off the Multer #170 issue.

uploads.routes.js

```<code>router.route('/images/:filename')
  .get(function(req,res){
    var fileName = req.params.filename;
    function getFileType(file, done){
      console.log('GETTING FILE TYPE');
      magic.detectFile(__dirname + '/../uploads/images/' + fileName, function(err, result) {
        if (err) return done(err);

        res.setHeader('Content-Type', result)
        fs.createReadStream(path.join(__dirname + '/../uploads/images/', req.params.filename)).pipe(res)
    });
  }
  getFileType();
})
</code>```

The key part that was missing was the:

```<code>res.setHeader('Content-Type', result)
fs.createReadStream(path.join(__dirname + '/../uploads/images/', req.params.filename)).pipe(res)
</code>```

So now can upload a file, validate the mime type, store as a unique name, and finally call the file name, get the check the mime type, set the content-type to the mime type and deliver to the client.

Title: Send uploaded Image in Express

Body:
Have an Express application that uploads an image using Multer. What I would like to be able to do is serve that image. The challenge though is when the file is uploaded it does not save the file extension which is by designed from what I've read for security purposes. What I need to be able to do is add the correct extensions to the corresponding mime type.

Technology

Express: 4.15.0

Multer: 1.3.0

mmmagic: 0.4.5

File Structure

root
  server.js
  /uploads
    /images
      ad58c400e67362118ac1b11f6c4b6c44
      ...
  /routes
    drinks.routes.js
    uploads.routes.js

Running this all through Postman. Have form elements name, tagline, image. If I upload "IMG_111.jpg" That image will get uploaded through Multer, validated that it's an image type, and placed in /images/uploads with a new name, default behavior for Multer to create uniqueness. The problem is I have the filename but it is not saved with an extension.

drinks.routes.js

var upload = multer({
  dest: 'uploads/images',
  fileFilter: function (req, file, callback) {
    console.log('running upload file filter');
      var fileType = file.mimetype;
      if(fileType !== 'image/png' && fileType !== 'image/jpeg' && fileType !== 'image/gif' && fileType !== 'image/jpg') {
          return callback(new Error('Only images are allowed'))
      }
      callback(null, true)
  },
}).single('image');

router.route('/').post(passport.authenticate('jwt', { session: false }), upload, function(req, res, next){
var drink = req.body;
var drinkImage = req.file;
console.log('DRINK IMAGE', drinkImage);

Drink.createDrink(drink, drinkImage, function(err, drink, drinkImage){
  console.log('creating drink');
  if(err){
    res.send(err);
  }
    res.json(drink)
  });
});

So I can upload a file, validate the file, save the file with a unique name and no extension. Where I'm have difficulties is then checking the mime type of the requested image, attaching an extension and sending that back in a response.

My original thought is to create a route with the image name requested, use mmmagic to detect the mime type, add the extension and serve that file. But, all attempts at this have failed.

uploads.routes.js

var express = require('express');
var router = express.Router();
var path = require('path');

var mmm = require('mmmagic');
var Magic = mmm.Magic;
var magic = new Magic(mmm.MAGIC_MIME_TYPE);

router.use(function(req, res, next){
  next();
});

router.route('/images/:filename')
  .get(function(req,res){
    var fileName = req.params.filename;
    var constructFile = function(res){
      magic.detectFile(__dirname + '/../uploads/images/' + fileName, function(err, result) {
        if (err) throw err;
        console.log(result);
        if (result == 'image/jpeg'){
      // return res.sendFile(__dirname + '/../uploads/images/' + fileName + '.jpg');
      res.send(express.static(path.join(__dirname, '/../uploads/images'), {index: false, extensions:['jpg']}));
    }
  });
}

constructFile(res);
  })

module.exports = router;

Tried following this SO Which lead me to express.static. But can't figure out at this point if I'm on the right track and just missing something or if I should be looking at this from a different angle.

Body:
It's not the cleanest implementation but it does work. Took the advice off the Multer #170 issue.

uploads.routes.js

router.route('/images/:filename')
  .get(function(req,res){
    var fileName = req.params.filename;
    function getFileType(file, done){
      console.log('GETTING FILE TYPE');
      magic.detectFile(__dirname + '/../uploads/images/' + fileName, function(err, result) {
        if (err) return done(err);

        res.setHeader('Content-Type', result)
        fs.createReadStream(path.join(__dirname + '/../uploads/images/', req.params.filename)).pipe(res)
    });
  }
  getFileType();
})

The key part that was missing was the:

res.setHeader('Content-Type', result)
fs.createReadStream(path.join(__dirname + '/../uploads/images/', req.params.filename)).pipe(res)

So now can upload a file, validate the mime type, store as a unique name, and finally call the file name, get the check the mime type, set the content-type to the mime type and deliver to the client.


问:
Autowired class from the jar file outside the classes
How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.

SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

code:

```<code>package com.path.controller;
import org.quartz.Scheduler;

@Controller
public class MyController{

   @Autowired
   Scheduler scheduler;
}
</code>```

This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,

<context:component-scan base-package="com.path" />

答:
I'm  guessing you haven't defined your scheduler  bean. You need to first define the bean in order to inject into your controller.

In your applicationcontext.xml first define a bean with type Scheduler.
You might need something like  below.  Be sure to check  out  the  quartz  documentation to  check which scheduler  you need and how to instantiate  it.

```<code><bean id="schedulerFactory"
    class="org.quartz.StdSchedulerFactory" />

<bean id="scheduler" class="org.quartz.Scheduler"  factory-bean="schedulerFactory" factory-method="getDefaultScheduler" />
</code>```

Body:
How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.

SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

code:

package com.path.controller;
import org.quartz.Scheduler;

@Controller
public class MyController{

   @Autowired
   Scheduler scheduler;
}

This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,

<context:component-scan base-package="com.path" />

Body:
I'm  guessing you haven't defined your scheduler  bean. You need to first define the bean in order to inject into your controller.

In your applicationcontext.xml first define a bean with type Scheduler.
You might need something like  below.  Be sure to check  out  the  quartz  documentation to  check which scheduler  you need and how to instantiate  it.

<bean id="schedulerFactory"
    class="org.quartz.StdSchedulerFactory" />

<bean id="scheduler" class="org.quartz.Scheduler"  factory-bean="schedulerFactory" factory-method="getDefaultScheduler" />


问:
Track the launch of a third-party application
Is it possible to track the launch of a third-party application on the device? Maybe the android sends a broadcast when the applications are launched.

UPDATE

```<code>public class ServiceAppControl extends IntentService {

private boolean serviceStarted = true;

public ServiceAppControl() {
    super("ServiceAppControl");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    while (serviceStarted){
        String appIsForeground = isAppOnForeground(getBaseContext());
        Log.d(AppGlobal.LOG_TAG, "Запущено приложение " + appIsForeground);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

private String isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    String appIsForeground = "";
    if (appProcesses == null) {
        return appIsForeground;
    }
    final String packageName = context.getPackageName();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            appIsForeground = appProcess.processName;
            return appIsForeground;
        }
    }
    return appIsForeground;
}
</code>```

}

答:
First, answer your question, Is it possible to track the launch of a third-party application on the device? - YES

Check this link, I explained briefly.

Note:
We should be aware of few things before doing few things

Running a while loop or timer continuously and getting the recent app
will drain a lot of battery(All the AppLocker will do same to get the current opening app) but we
should be smart enough and we should run the loop only when the
screen ON, when screen OFF we should stop that timer or whatever.

From Android "O" some restriction in running the service in
background, so better put your service as Foreground service

Done!!!.

Body:
Is it possible to track the launch of a third-party application on the device? Maybe the android sends a broadcast when the applications are launched.

UPDATE

public class ServiceAppControl extends IntentService {

private boolean serviceStarted = true;

public ServiceAppControl() {
    super("ServiceAppControl");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    while (serviceStarted){
        String appIsForeground = isAppOnForeground(getBaseContext());
        Log.d(AppGlobal.LOG_TAG, "Запущено приложение " + appIsForeground);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

private String isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    String appIsForeground = "";
    if (appProcesses == null) {
        return appIsForeground;
    }
    final String packageName = context.getPackageName();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            appIsForeground = appProcess.processName;
            return appIsForeground;
        }
    }
    return appIsForeground;
}

}


问:
Command to copy a line from text and create a new text file
Please suggest me a command that will copy a line from all the text files and create one file with all the lines in it.

I am on a Linux machine where a particular directory has around 11000 files in it and each file has 3 or 4 lines of data.

What I wanted to do is to combine all data into one file which I can refer.... let's say 11000*3 = 3000 lines. I want to copy all 3000 lines in one single file line by line.

These are the few txt files and directories and even the directories has a list of txt files

```<code>Jan 2007 abc.txt
Jan 2007 siele.txt
Jan 2007 regel.txt
Jan 2007 sne.txt
Jan 2007 marshwlo.txt
Jan 2007 ziplist.txt
Jan 2007 listider.txt
Jan 2007 kindle.txt
Jan 2007 list.txt
Jan 2007 Codelevel
Jan 2007 Ziplevel
</code>```

答:
```<code>find . -name \*.txt -type f | xargs -r cat > /tmp/output_file.txt
</code>```

Explained:

find . -name \*.txt -type f search recursive from . directory for any *.txt file

xargs -r cat run command cat foundFile1.txt foundFile2.txt ...

> /tmp/output_file.txt redirect output to file /tmp/output_file.txt

Body:
Please suggest me a command that will copy a line from all the text files and create one file with all the lines in it.

I am on a Linux machine where a particular directory has around 11000 files in it and each file has 3 or 4 lines of data.

What I wanted to do is to combine all data into one file which I can refer.... let's say 11000*3 = 3000 lines. I want to copy all 3000 lines in one single file line by line.

These are the few txt files and directories and even the directories has a list of txt files

Jan 2007 abc.txt
Jan 2007 siele.txt
Jan 2007 regel.txt
Jan 2007 sne.txt
Jan 2007 marshwlo.txt
Jan 2007 ziplist.txt
Jan 2007 listider.txt
Jan 2007 kindle.txt
Jan 2007 list.txt
Jan 2007 Codelevel
Jan 2007 Ziplevel

Body:
find . -name \*.txt -type f | xargs -r cat > /tmp/output_file.txt

Explained:

find . -name \*.txt -type f search recursive from . directory for any *.txt file

xargs -r cat run command cat foundFile1.txt foundFile2.txt ...

> /tmp/output_file.txt redirect output to file /tmp/output_file.txt


答:
That's because you are using a single state for all the comments.

```<code><button onClick = {() => this.changeIsReply(secondData.key)} > Reply </button>

{this.state.isReply && this.state.clickedComment == {secondData.key} ? <SetComment id={secondData.key} /> : null}
</code>```

and change your changeIsReply() to:

```<code>changeIsReply(clickedId) {
    this.setState({
        isReply: !this.state.isReply,
        clickedComment: clickedId
    });
}
</code>```

See if this works. Don't forget to add the new state to your constructor.

Title: How to modify only one element in a react .map function?

Body:
I'm a little new to react and was a little lost with what to do here. I'm loading data from firebase and rendering the props of that object using a .map function to list all the 'comments' on a page, which works fine. I also want to call a component that would allow the user to reply an individual comment (i.e. one specific element in the map), but as expected by this code, when the reply button is clicked it displays the called component under every element of the map, which isn't desirable. Is there anyway I could call the component for just one element of the map in this case?

changeIsReply() {
  this.setState(
    {isReply: !this.state.isReply,}
  );
}

  render() {

  return (

    {Object.values(this.props.commentInfo).map((data) =>
      data.map((secondData, i) =>

{secondData.text}

{secondData.category}

{secondData.organization}

            <button> UpButton </button>

            <button> DownButton </button>
            <button onClick = {this.changeIsReply} > Reply </button>
            {this.state.isReply ? <SetComment id={secondData.key} /> : null}

      )
    )}

  )
}

Body:
That's because you are using a single state for all the comments.

<button onClick = {() => this.changeIsReply(secondData.key)} > Reply </button>

{this.state.isReply && this.state.clickedComment == {secondData.key} ? <SetComment id={secondData.key} /> : null}

and change your changeIsReply() to:

changeIsReply(clickedId) {
    this.setState({
        isReply: !this.state.isReply,
        clickedComment: clickedId
    });
}

See if this works. Don't forget to add the new state to your constructor.


答:
You can echo it with php like:

```<code><?php echo $product->product_id ?>
</code>```

and in blade syntax like:

```<code>{{$product->product_id}}
</code>```

and in your case it should be like:

```<code>'url' => [ '/cart/add/'. $product->product_id ]
</code>```

only concatenation is required here

Title: How can print Laravel variable with echo

Body:
<?php echo Form::open(['method' => 'POST', 'url' => ['/cart/add/'. "{{$product->product_id }}"]] )?>
<?php echo Form::button('Agregar al Carro', ['class' => 'btn-u btn-u-sea-shop btn-u-lg', 'type' => 'submit']) ?>
<?php echo Form::close()  ?>

I need to print the variable $product in a template.

Body:
You can echo it with php like:

<?php echo $product->product_id ?>

and in blade syntax like:

{{$product->product_id}}

and in your case it should be like:

'url' => [ '/cart/add/'. $product->product_id ]

only concatenation is required here


问:
Spring boot sample: Unable to start embedded container error
I am new to spring, so i downloaded jar from spring intializr for maven-web java 1.8 demo. I extracted and imported it to STS to run the main() file and I get below exception. Can some one tell me what's solution for this?

Solutions I tried from web but didn't work:
- Tried adding Hibernate-validator dependency to pom
- Tried adding spring-boot-starter-tomcat dependency to pom

STACK TRACE:

```<code>2017-01-26 12:19:32.587  INFO 3816 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2e4b8173: startup date [Thu Jan 26 12:19:32 EST 2017]; root of context hierarchy
2017-01-26 12:19:36.442  WARN 3816 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.http.encoding-org.springframework.boot.autoconfigure.web.HttpEncodingProperties': Initialization of bean failed; nested exception is javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
2017-01-26 12:19:36.454 ERROR 3816 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

The Bean Validation API is on the classpath but no implementation could be found

Action:

Add an implementation, such as Hibernate Validator, to the classpath
</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.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Application file:

```<code>package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

答:
I met same issue and resolved it by delete these two folders under .m2

com\fasterxml --> delete it will resolve TypeResovler issue.

org\springframework  --> delete it will resolve lack of validator
issue.

then the program works.

Body:
I am new to spring, so i downloaded jar from spring intializr for maven-web java 1.8 demo. I extracted and imported it to STS to run the main() file and I get below exception. Can some one tell me what's solution for this?

Solutions I tried from web but didn't work:
- Tried adding Hibernate-validator dependency to pom
- Tried adding spring-boot-starter-tomcat dependency to pom

STACK TRACE:

2017-01-26 12:19:32.587  INFO 3816 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2e4b8173: startup date [Thu Jan 26 12:19:32 EST 2017]; root of context hierarchy
2017-01-26 12:19:36.442  WARN 3816 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.http.encoding-org.springframework.boot.autoconfigure.web.HttpEncodingProperties': Initialization of bean failed; nested exception is javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
2017-01-26 12:19:36.454 ERROR 3816 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

The Bean Validation API is on the classpath but no implementation could be found

Action:

Add an implementation, such as Hibernate Validator, to the classpath

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.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Application file:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}


问:
How to compare two csv files using Robot Framework
I would like to compare difference between two csv files using robot framework .Test case should fail if there is difference and pass if there is no difference.I have tried DiffLibrary in Robot framework but is returning pass status when records are not sorted. Can someone guide me how this can be achieved or if there is any alternative way to do this.

My first.csv file is having data like below

```<code>Benchmark Name,Policy Name,No of Rules,Policy Measurement SLO,Policy Remediation SLO,No of Rules Compliant in MSLO,No of Rules Non-Compliant in RSLO,No of Rules Non-Compliant OUT RSLO
CIS Red Hat Enterprise Linux 6 Benchmark v1.0.0,PCI,281,1 MONTHS,1 MONTHS,150,130
CIS Red Hat Enterprise Linux 7 Benchmark v1.2.0,PCI,281,5 MONTHS,1 MONTHS,150,137
CIS Red Hat Enterprise Linux 7 Benchmark v1.5.0,PCI,281,1 MONTHS,1 MONTHS,150,135
</code>```

And my second.csv file is having data like below

```<code>Benchmark Name,Policy Name,No of Rules,Policy Measurement SLO,Policy Remediation SLO,No of Rules Compliant in MSLO,No of Rules Non-Compliant in RSLO,No of Rules Non-Compliant OUT RSLO
CIS Red Hat Enterprise Linux 7 Benchmark v1.2.0,PCI,281,5 MONTHS,1 MONTHS,150,137
CIS Red Hat Enterprise Linux 6 Benchmark v1.0.0,PCI,281,1 MONTHS,1 MONTHS,150,130
CIS Red Hat Enterprise Linux 7 Benchmark v1.5.0,PCI,281,1 MONTHS,1 MONTHS,150,135
</code>```

Robot code is below

```<code>*** Settings ***
Library  DiffLibrary
Library  OperatingSystem

*** Test Cases ***

Diffing two files one being different
    Run Keyword And Expect Error  differences*  Diff Files  first.csv  second.csv
</code>```

答:
This answer worked for me ,even if data is sorted .It will give the result as pass if there is no mismatch and fail if data mismatches.

csv_difference.py

```<code>import sys
     def csv_diff(file_f,file_g):
        #file_f = sys.argv[1]
        #file_g = sys.argv[2]
        set_f = set()
        set_g = set()
        with open(file_f) as f:
            line = f.readline().strip()
            while line:
                set_f.add(line)
                line = f.readline().strip()
        with open(file_g) as g:
            line = g.readline().strip()
            while line:
                set_g.add(line)
                line = g.readline().strip()
        diff = set_f - set_g

        # print set_f
        # print set_g
        # print diff
        if diff:
            #print "Data mismatch between the files"
            return False
        else:
            #print " Data Matches "
            return True
</code>```

csv-difference.robot

```<code>*** Settings ***
    Library     OperatingSystem
    Library      csv_difference.py

    *** Test Cases ***
    CSV file comparison
         ${output}=   Run keyword  csv diff   first.csv   second.csv
        Should Be True  '${output}' == 'True'
</code>```

Body:
I would like to compare difference between two csv files using robot framework .Test case should fail if there is difference and pass if there is no difference.I have tried DiffLibrary in Robot framework but is returning pass status when records are not sorted. Can someone guide me how this can be achieved or if there is any alternative way to do this.

My first.csv file is having data like below

Benchmark Name,Policy Name,No of Rules,Policy Measurement SLO,Policy Remediation SLO,No of Rules Compliant in MSLO,No of Rules Non-Compliant in RSLO,No of Rules Non-Compliant OUT RSLO
CIS Red Hat Enterprise Linux 6 Benchmark v1.0.0,PCI,281,1 MONTHS,1 MONTHS,150,130
CIS Red Hat Enterprise Linux 7 Benchmark v1.2.0,PCI,281,5 MONTHS,1 MONTHS,150,137
CIS Red Hat Enterprise Linux 7 Benchmark v1.5.0,PCI,281,1 MONTHS,1 MONTHS,150,135

And my second.csv file is having data like below

Benchmark Name,Policy Name,No of Rules,Policy Measurement SLO,Policy Remediation SLO,No of Rules Compliant in MSLO,No of Rules Non-Compliant in RSLO,No of Rules Non-Compliant OUT RSLO
CIS Red Hat Enterprise Linux 7 Benchmark v1.2.0,PCI,281,5 MONTHS,1 MONTHS,150,137
CIS Red Hat Enterprise Linux 6 Benchmark v1.0.0,PCI,281,1 MONTHS,1 MONTHS,150,130
CIS Red Hat Enterprise Linux 7 Benchmark v1.5.0,PCI,281,1 MONTHS,1 MONTHS,150,135

Robot code is below

*** Settings ***
Library  DiffLibrary
Library  OperatingSystem

*** Test Cases ***

Diffing two files one being different
    Run Keyword And Expect Error  differences*  Diff Files  first.csv  second.csv

Body:
This answer worked for me ,even if data is sorted .It will give the result as pass if there is no mismatch and fail if data mismatches.

csv_difference.py

import sys
     def csv_diff(file_f,file_g):
        #file_f = sys.argv[1]
        #file_g = sys.argv[2]
        set_f = set()
        set_g = set()
        with open(file_f) as f:
            line = f.readline().strip()
            while line:
                set_f.add(line)
                line = f.readline().strip()
        with open(file_g) as g:
            line = g.readline().strip()
            while line:
                set_g.add(line)
                line = g.readline().strip()
        diff = set_f - set_g

        # print set_f
        # print set_g
        # print diff
        if diff:
            #print "Data mismatch between the files"
            return False
        else:
            #print " Data Matches "
            return True

csv-difference.robot

*** Settings ***
    Library     OperatingSystem
    Library      csv_difference.py

    *** Test Cases ***
    CSV file comparison
         ${output}=   Run keyword  csv diff   first.csv   second.csv
        Should Be True  '${output}' == 'True'


问:
c++ parse int from string

Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

```<code>string s = "10";
int i = s....?
</code>```

Thanks!

答:
There is no "right way". If you want a universal (but suboptimal) solution you can use a boost::lexical cast.

A common solution for C++ is to use std::ostream and  << operator. You can use a stringstream and stringstream::str() method for conversion to string.

If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like C++ String Toolkit Library

Best Regards,

Marcin

Title: c++ parse int from string

Body:
Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10";
int i = s....?

Thanks!


问:
C++ vector std::bad_alloc error in a program
I was trying to sort a vector having user defined data type having two values, on the basis of one. But i get the error of bad_alloc. this is the code :

```<code>#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct s{
int value;
int weight;
};

bool comp(s a , s b){
return a.value>b.value;
}

int main(){
vector <s> p;
s temp;
int n;
cin>>n;
while(n>=1){
    cin>>temp.value;
    cin>>temp.weight;
    p.push_back(temp);
}
sort(p.begin(), p.end(), comp);
vector <s> :: iterator it;
for(it = p.begin(); it != p.end();it++){
    *it = temp;
    cout<<temp.value<<endl;
}

}
</code>```

on running :

terminate called after throwing an instance of 'std::bad_alloc'
    what():  std::bad_alloc

can anyone help?

答:
If the user enters a value of 1 or higher for n, the loop never ends, filling the vector until it uses up all available memory. You are not decrementing n on each loop iteration so the loop eventually breaks:

```<code>while (n >= 1) {
    cin >> temp.value;
    cin >> temp.weight;
    p.push_back(temp);
    --n; // <-- add this
}
</code>```

In this situation, a for loop would be more appropriate than a while loop:

```<code>for (int i = 0; i < n; ++i) {
    cin >> temp.value;
    cin >> temp.weight;
    p.push_back(temp);
}
</code>```

I would go as far as getting rid of the manual loop altogether by defining a custom operator>> for struct s and then use std::copy_n() with std::istream_iterator and std::back_inserter:

```<code>#include <iostream>
#include <algorithm>
#include <iterator>

istream& operator>>(istream &in, s &out) {
    in >> out.value;
    in >> out.weight;
    return in;
}

int main() {
    ...
    int n;
    cin >> n;
    copy_n(istream_iterator<s>(cin), n, back_inserter(p));
    ...
}
</code>```

Any way you fill the vector, your comp function should take its input parameters by reference:

```<code>bool comp(s &a, s &b) {
    return a.value > b.value;
}
</code>```

Also, your output loop is not using the iterator correctly. You need to get rid of the *it = assignment and just output the referenced value as-is:

```<code>for(it = p.begin(); it != p.end(); ++it) {
    //*it = temp; // <- get rid of this
    cout << it->value << endl;
}
</code>```

Body:
I was trying to sort a vector having user defined data type having two values, on the basis of one. But i get the error of bad_alloc. this is the code :

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct s{
int value;
int weight;
};

bool comp(s a , s b){
return a.value>b.value;
}

int main(){
vector <s> p;
s temp;
int n;
cin>>n;
while(n>=1){
    cin>>temp.value;
    cin>>temp.weight;
    p.push_back(temp);
}
sort(p.begin(), p.end(), comp);
vector <s> :: iterator it;
for(it = p.begin(); it != p.end();it++){
    *it = temp;
    cout<<temp.value<<endl;
}

}

on running :

terminate called after throwing an instance of 'std::bad_alloc'
    what():  std::bad_alloc

can anyone help?

Body:
If the user enters a value of 1 or higher for n, the loop never ends, filling the vector until it uses up all available memory. You are not decrementing n on each loop iteration so the loop eventually breaks:

while (n >= 1) {
    cin >> temp.value;
    cin >> temp.weight;
    p.push_back(temp);
    --n; // <-- add this
}

In this situation, a for loop would be more appropriate than a while loop:

for (int i = 0; i < n; ++i) {
    cin >> temp.value;
    cin >> temp.weight;
    p.push_back(temp);
}

I would go as far as getting rid of the manual loop altogether by defining a custom operator>> for struct s and then use std::copy_n() with std::istream_iterator and std::back_inserter:

#include <iostream>
#include <algorithm>
#include <iterator>

istream& operator>>(istream &in, s &out) {
    in >> out.value;
    in >> out.weight;
    return in;
}

int main() {
    ...
    int n;
    cin >> n;
    copy_n(istream_iterator<s>(cin), n, back_inserter(p));
    ...
}

Any way you fill the vector, your comp function should take its input parameters by reference:

bool comp(s &a, s &b) {
    return a.value > b.value;
}

Also, your output loop is not using the iterator correctly. You need to get rid of the *it = assignment and just output the referenced value as-is:

for(it = p.begin(); it != p.end(); ++it) {
    //*it = temp; // <- get rid of this
    cout << it->value << endl;
}