问:
Reactjs POST request through axios
Hi i am trying reactjs POST request through axios but getting error, I went through all docs but error is not solved.

Here is my error:

Uncaught (in promise) Error: Request failed with status code 400
    at createError (eval at  (bundle.js:4621), :15:15)
    at settle (eval at  (bundle.js:4615), :18:12)
    at XMLHttpRequest.handleLoad (eval at  (bundle.js:4609), :77:7)

Here is my Reactjs code:

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

axios('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>
     <div style={style}>
     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />
     <br/>
     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />
     <br/>
     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />
     <br/>

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />
     <br/>
     <br/>
     <input type="submit" />

     </div>
         </form>

   );
 }

}
</code>```

答:
Checking axios api the correct way of making POST request is: </p>

```<code>const payload = {
  id: 111,
  studentName: 'param',
  age: 24,
  emailId: 2
}

axios({
  method: 'post',
  url: '/user/12345',
  data: payload, // you are sending body instead
  headers: {
   // 'Authorization': `bearer ${token}`,
  'Content-Type': 'application/json'
  },
})
</code>```

Title: Reactjs POST request through axios

Body:
Hi i am trying reactjs POST request through axios but getting error, I went through all docs but error is not solved.

Here is my error:

Uncaught (in promise) Error: Request failed with status code 400
    at createError (eval at  (bundle.js:4621), :15:15)
    at settle (eval at  (bundle.js:4615), :18:12)
    at XMLHttpRequest.handleLoad (eval at  (bundle.js:4609), :77:7)

Here is my Reactjs code:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

axios('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>

     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />

     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />

     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />

     <input type="submit" />

         </form>

   );
 }

}

Body:
Checking axios api the correct way of making POST request is:

const payload = {
  id: 111,
  studentName: 'param',
  age: 24,
  emailId: 2
}

axios({
  method: 'post',
  url: '/user/12345',
  data: payload, // you are sending body instead
  headers: {
   // 'Authorization': `bearer ${token}`,
  'Content-Type': 'application/json'
  },
})


来源: stackexchange

问:
How to fetch data from discord
I would like to know how can I fetch data from discord specifically Number of people in a channel. for example, squad #14 has 3 out of 4 people. I want to fetch that number and display it somewhere in a site. How would I do that?

Regards.

答:
Discord doesn't provide an official way of getting members in a voice channel from the REST API as far as I can tell. To achieve this you will likely need to run a full-blown bot and invite it to your guild. For Java I recommend the JDA library.

public class ReadyListener implements EventListener
{
    public static void main(String[] args)
            throws LoginException, RateLimitedException, InterruptedException
    {
        // Note: It is important to register your ReadyListener before building
        JDA jda = new JDABuilder(AccountType.BOT)
            .setToken("token")
            .addEventListener(new ReadyListener())
            .buildBlocking();
    }

    @Override
    public void onEvent(Event event)
    {
        if (event instanceof ReadyEvent)
        {
            System.out.println("API is ready!");

            // Get a specific voice channel
            event.getJda().getVoiceChannelById("12341234");
        }
    }
}
```

Recommended reading:

https://github.com/DV8FromTheWorld/JDA/wiki/3)-Getting-Started

https://discordapp.com/developers/docs/intro

You will probably want to look at the VoiceChannel class in the javadocs.

ContentLicense: CC BY-SA 3.0

Title: How to fetch data from discord

Body:
Discord doesn't provide an official way of getting members in a voice channel from the REST API as far as I can tell. To achieve this you will likely need to run a full-blown bot and invite it to your guild. For Java I recommend the JDA library.

public class ReadyListener implements EventListener
{
    public static void main(String[] args)
            throws LoginException, RateLimitedException, InterruptedException
    {
        // Note: It is important to register your ReadyListener before building
        JDA jda = new JDABuilder(AccountType.BOT)
            .setToken("token")
            .addEventListener(new ReadyListener())
            .buildBlocking();
    }

    @Override
    public void onEvent(Event event)
    {
        if (event instanceof ReadyEvent)
        {
            System.out.println("API is ready!");

            // Get a specific voice channel
            event.getJda().getVoiceChannelById("12341234");
        }
    }
}

Recommended reading:

https://github.com/DV8FromTheWorld/JDA/wiki/3)-Getting-Started

https://discordapp.com/developers/docs/intro

You will probably want to look at the VoiceChannel class in the javadocs.


问:
"Evaluate" doesn't work as a javascript function name in Mozilla firefox and google-chrome
I wrote a simple html file with just a javascript function. It worked in IE but not in frefox and chrome. The code was: </p>

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
<script type="text/javascript">
function evaluate()
{
alert("Hello World!");
}
</script>
</head>
<body>

<form >
<table id="tbl">
 <tr align="right">
  <td><input  id="__JAVA_Evaluate" type="button" value="evaluate!" onclick="evaluate()"/>
  </td>
 </tr>
</table>
</form>
</body>
</html>
</code>```

<p>After a while I understood that it was not possible to define a function with the name evaluate() in the Firefox and chrome.
And it is enough to rename the function. I wonder that is other function name which are reserved in Firefox and chrome and how we could be aware about this reserved keys? </p>

答:
Here is the reference for this function:

https://developer.mozilla.org/en/DOM/document.evaluate

ContentLicense: CC BY-SA 2.5

Body:
I wrote a simple html file with just a javascript function. It worked in IE but not in frefox and chrome. The code was:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>test</title>

<form >

  <input  id="__JAVA_Evaluate" type="button" value="evaluate!" onclick="evaluate()"/>

</form>

After a while I understood that it was not possible to define a function with the name evaluate() in the Firefox and chrome.
And it is enough to rename the function. I wonder that is other function name which are reserved in Firefox and chrome and how we could be aware about this reserved keys?


问:
Elastic search query syntax
I am trying to retrieve documents based on the following query:

```<code>POST _search
{
    "size": 1,
    "filter": {
        "bool": {
            "must": [
               {
                   "range":{
                        "myfield": {
                            "from": "yyyy-mm-ddT00:00:00Z",
                            "to": "yyyy-mm-ddT00:00:00Z"
                        }
                    }
               },
                {"term": {"myfield1.myfield2" : "myvalue"}}
            ]
        }
    }
}
</code>```

which doesnot return any result. There might be a problem with my syntax. I'd appreciate if anyone can help.

here is the structure of the document:

```<code>"_source": {
    "myfield": "yyyy-mm-ddT00:00:00",
    "myfield1": {
        "myfield2": "myvalue"
    }
}
</code>```

答:
The field of the term query is not correct.

Instead of this:

```<code>{"term": {"myfield.myfield1.myfield2" : "myvalue"}}
</code>```

Try this:

```<code>{"term": {"myfield1.myfield2" : "myvalue"}}
</code>```

Title: Elastic search query syntax

Body:
I am trying to retrieve documents based on the following query:

POST _search
{
    "size": 1,
    "filter": {
        "bool": {
            "must": [
               {
                   "range":{
                        "myfield": {
                            "from": "yyyy-mm-ddT00:00:00Z",
                            "to": "yyyy-mm-ddT00:00:00Z"
                        }
                    }
               },
                {"term": {"myfield1.myfield2" : "myvalue"}}
            ]
        }
    }
}

which doesnot return any result. There might be a problem with my syntax. I'd appreciate if anyone can help.

here is the structure of the document:

"_source": {
    "myfield": "yyyy-mm-ddT00:00:00",
    "myfield1": {
        "myfield2": "myvalue"
    }
}

Body:
The field of the term query is not correct.

Instead of this:

{"term": {"myfield.myfield1.myfield2" : "myvalue"}}

Try this:

{"term": {"myfield1.myfield2" : "myvalue"}}


问:
Using Parameters httpClient and generated Url in request in Angular 4
Iam using httpGet to access Lumen web api server with 4 parameters in angular 4, this is my web api url : http://sismonev.api/member/2017/8, they have 2 parameter year and month and member key. in my angular4 component bellow my code :

```<code> let params = new HttpParams();
    params = params.append('tahun', '2017');
    params = params.append('bulan', '5');

   this.http.get<JuResponse>(environment.url + '/member', {params: params})
              .subscribe(data => {
                        for (var i = 0; i < data.length; i++) {
                        let pd=+data[i].jumlah; // comvert to number
                          this.pieD.push(pd);
                          this.pieChartLabels.push(data[i].jenis_bu);
                      }
                      this.pieChartData=this.pieD;
                      console.log(this.pieChartData);
                  },
                  err => {
                      console.log("Error occured.")
                  });
</code>```

this not working, because angular generated like this :

```<code>http://sismonev.api/member?year=2017&month=8
</code>```

Lumen web api give the error like this :

```<code>NotFoundHttpException in RoutesRequests.php line 596:
</code>```

Could anyone give me explanation? how to generate url to access web api with this http://sismonev.api/member/2017/8 format.

thank you

答:
Parameters added with params are added as query parameters.

```<code>const url = "member";
const year = 2017;
const month = 8;
this.http.get<JuResponse>(environment.url + `/${member}/${year}/${month}`)
</code>```

Also check template literals.

Body:
Iam using httpGet to access Lumen web api server with 4 parameters in angular 4, this is my web api url : http://sismonev.api/member/2017/8, they have 2 parameter year and month and member key. in my angular4 component bellow my code :

 let params = new HttpParams();
    params = params.append('tahun', '2017');
    params = params.append('bulan', '5');

   this.http.get<JuResponse>(environment.url + '/member', {params: params})
              .subscribe(data => {
                        for (var i = 0; i < data.length; i++) {
                        let pd=+data[i].jumlah; // comvert to number
                          this.pieD.push(pd);
                          this.pieChartLabels.push(data[i].jenis_bu);
                      }
                      this.pieChartData=this.pieD;
                      console.log(this.pieChartData);
                  },
                  err => {
                      console.log("Error occured.")
                  });

this not working, because angular generated like this :

http://sismonev.api/member?year=2017&month=8

Lumen web api give the error like this :

NotFoundHttpException in RoutesRequests.php line 596:

Could anyone give me explanation? how to generate url to access web api with this http://sismonev.api/member/2017/8 format.

thank you

Body:
Parameters added with params are added as query parameters.

const url = "member";
const year = 2017;
const month = 8;
this.http.get<JuResponse>(environment.url + `/${member}/${year}/${month}`)

Also check template literals.


问:
Spring Security redirect to previous page after successful registering on secuser and auto login
I have used spring security plugin in my Grails 2.4.5 application. I have authentication before user makes online payment. If user is not logged in, Spring Security asks for login before payment, and if user is not having account then he is made to register and made to auto login. During this I need previous URL. How to get previous url after registering and auto login in Grails.</p>

答:
You can auto redirect to previous page with parameters after successful registration and login, following is the controller code to achieve that,  </p>

```<code>      println "previous url:"+request.getHeader('referer')
      redirect(uri: request.getHeader('referer') )
</code>```

Body:
You can auto redirect to previous page with parameters after successful registration and login, following is the controller code to achieve that,

      println "previous url:"+request.getHeader('referer')
      redirect(uri: request.getHeader('referer') )


问:
Why not add classes to window or global in a namespaced variable?
I am using webpack to transpile/bundle/etc my js files. Im using the import/export syntax ( as opposed to the CommonJS way of require and export.module ). This means i need to import each class and all subclasses of it however many times if i need to use them in the context of a specific script.

The question:

Even though classes arent natively supported in js, why do we need to import them all the time? Wouldnt it be easier if ( and im only speaking for classes ) they were available to all scopes?

EDIT: To avoid polluting the global scope one could do something like global.myLibs and be done with that issue. I personally prefix my classes with something unique but this method would serve even those that dont i suppose.

For example:

window.myClasses could serve as a container for all my classes. I come from an iOS background where all the classes in a main "bundle", in java i think that would be a "package" are available to everyone. Re-importing the class itself doesnt seem like it serves any purpose.

See here:
Why do i need to import modules everytime in webpack bundle?

and here: Bundling js files with webpack class undefined

答:
Adding things in the global scope can lead you to naming conflicts. What if you created a class named Node, add it to global scope by doing window.Node = Node ? You lose the reference to the browser's global Node object.

You can argue that you will never use names that are already used for global objects. But now, what if in a year or so, a new object is added to the spec with the same name as one of yours, and you want to use it alongside your own object ? You have to make a choice, or rename your own object. This is not future proof.

Importing the same module in every module that uses it is a best practice. Because by doing it, you never pollute the global scope. Don't be afraid that it imports the code of this module n times in your final bundle. Webpack imports it only one time, then uses a reference to the module everytime you are importing it.

See these resources :

JavaScript Modules: A Beginner’s Guide by Preethi Kasireddy on Medium

Eloquent Javascript Modules chapter


问:
How to Import a Class From Android Source While Developing an Android Application
I want to use a java class from android/frameworks/base/.... How can I import the class to my project in Eclipse? </p>

答:
Just use the import statements as you do when you import every other package.

For example if you want to use the AndroidHttpClient, then the following import will do it:

```<code>import android.net.http.*;
</code>```

Body:
Just use the import statements as you do when you import every other package.

For example if you want to use the AndroidHttpClient, then the following import will do it:

import android.net.http.*;

OwnerDisplayName: anon


问:
string to date conversion returns NaN
I'm using a jquery datetime picker plugin and have three textboxes viz., startdate, enddate, difference. plugin works perfectly, startdate string (dd/MM/yyyy HH:mm) format gets converted correctly but enddate string doesn't get converted to Date object and it returns NaN. can anyone help  me?
here's my code:-

```<code><script type="text/javascript">
        $(document).ready(function () {
            $('#<%= txtEndDate.ClientID %>').bootstrapMaterialDatePicker
            ({
                weekStart: 0, format: 'DD/MM/YYYY HH:mm', shortTime: true
            });
            $('#<%= txtStartDate.ClientID %>').bootstrapMaterialDatePicker
            ({
                weekStart: 0, format: 'DD/MM/YYYY HH:mm', shortTime: true
            }).on('change', function (e, date) {
                $('#<%= txtEndDate.ClientID %>').bootstrapMaterialDatePicker('setMinDate', date);
            });
            $('.mb').change(function () {
                var start = $('#<%= txtStartDate.ClientID %>').val();
                alert('start:-'+start);
                var end1 = $('#<%= txtEndDate.ClientID %>').val();
                alert('end:-'+end1);

                if (start != "" && end1 != "") {
                    var eDate = Date.parse(end1);
                    var sDate = Date.parse(start);

                    alert(sDate);
                    alert(eDate);// gives NaN
                    var diff = Math.abs(eDate - sDate);
                    alert(diff);
                    // get total seconds between the times
                    var delta = diff / 1000;

                    // calculate (and subtract) whole days
                    var days = Math.floor(delta / 86400);
                    delta -= days * 86400;

                    // calculate (and subtract) whole hours
                    var hours = Math.floor(delta / 3600) % 24;
                    delta -= hours * 3600;

                    // calculate (and subtract) whole minutes
                    var minutes = Math.floor(delta / 60) % 60;
                    delta -= minutes * 60;

                    // what's left is seconds
                    var seconds = delta % 60;

                    $('#<%= txtDifference.ClientID %>').val(parseInt(days) + ":" + parseInt(hours) + ":" + parseInt(minutes) + ":" + parseInt(seconds));
                }
            })
        });
    </script>
</code>```

alert('start:-'+start); gives start:-12/11/2017 20:52alert('end:-'+end1); gives end:-13/11/2017 20:54
alert(sDate); gives 1513005720000
but alert(eDate); gives NaN

答:
Date.parse() has some quirky support across browsers. Like some strings parsed on Chrome returns NaN in FF.

So, I suggest writing a utility function that composes your date from the string format you are using.

Here is an regex based snippet to extract the dd, mm and yyyy from the string and compose it to a Date object.

```<code>function getTimeFromString (formattedString) {
    var a = formattedString.match(/(\d{2})\/(\d{2})\/(\d{4})\s(\d{2}):(\d{2})/)
    var d = new Date()
    d.setDate(a[1]), d.setMonth[a[2] - 1], d.setYear(a[3]), d.setHours(a[4]), d.setMinutes(a[5])
    return d.getTime()
}
</code>```

And, use getTimeFromString to do your calculations. Hope this helps.

Title: string to date conversion returns NaN

Body:
I'm using a jquery datetime picker plugin and have three textboxes viz., startdate, enddate, difference. plugin works perfectly, startdate string (dd/MM/yyyy HH:mm) format gets converted correctly but enddate string doesn't get converted to Date object and it returns NaN. can anyone help  me?
here's my code:-

alert('start:-'+start); gives start:-12/11/2017 20:52alert('end:-'+end1); gives end:-13/11/2017 20:54
alert(sDate); gives 1513005720000
but alert(eDate); gives NaN

Body:
Date.parse() has some quirky support across browsers. Like some strings parsed on Chrome returns NaN in FF.

So, I suggest writing a utility function that composes your date from the string format you are using.

Here is an regex based snippet to extract the dd, mm and yyyy from the string and compose it to a Date object.

function getTimeFromString (formattedString) {
    var a = formattedString.match(/(\d{2})\/(\d{2})\/(\d{4})\s(\d{2}):(\d{2})/)
    var d = new Date()
    d.setDate(a[1]), d.setMonth[a[2] - 1], d.setYear(a[3]), d.setHours(a[4]), d.setMinutes(a[5])
    return d.getTime()
}

And, use getTimeFromString to do your calculations. Hope this helps.


问:
jQuery show hide parent item on click by class
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

```<code><div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item -->

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});
</code>```

答:
Try Floating to the closest top parent div and then use find.

```<code>$(this).closest('.list-item').find(".metas").toggle();
</code>```

// add some data...

var x = "";

for(var i = 0; i < 5; i++){
  x += "
\

\

img
\

Question goes here....?
\

\

Answer goes here....
\
    hide meta \

\

\

 META INFO HERE
\

\
";
}

$("#contents").append(x);
// ----------------------------------

$('.list-content .meta-info-btn').click(function() {
  $(this).closest('.list-item').find(".metas").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  margin: 5px;
}
.meta-info-btn:hover {
  cursor: pointer;
}
.meta-info-btn {
  background: #CCC;
  border: 1px solid #999;
  padding: 2px;
  margin: 5px;
}

.list-item {
  margin-bottom: 10px;
  border: 1px solid black;
  padding: 5px;
}</code>```

```

Body:
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <?php echo get_icon( $update[ $i ] ) ?>

<?php echo $questions[ $i ] ?>

<?php echo $ans[ $i ] ?>

            keyboard_arrow_down

commented 1 hour ago in Plugins by
            gurjyot

            arrow_upward +1245
            remove_red_eye 50.2k

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});

Body:
Try Floating to the closest top parent div and then use find.

$(this).closest('.list-item').find(".metas").toggle();

// add some data...

var x = "";

for(var i = 0; i < 5; i++){
  x += "<div class='list-item'>\
 <div class='list-content'>\
  <div class='list-updates'><a href='#'>img</a></div>\
  <div class='item-title'><a href='#'>Question goes here....?</a></div>\
  <div class='ans-box'>\
    <div class='ans-count'>Answer goes here....</div>\
    <span><i class='material-icons meta-info-btn'>hide meta </i></span>\
  </div>\
 </div>\
  <div class='metas'> META INFO HERE </div>\
</div>\
";
}

$("#contents").append(x);
// ----------------------------------

$('.list-content .meta-info-btn').click(function() {
  $(this).closest('.list-item').find(".metas").toggle();
});

div {
  margin: 5px;
}
.meta-info-btn:hover {
  cursor: pointer;
}
.meta-info-btn {
  background: #CCC;
  border: 1px solid #999;
  padding: 2px;
  margin: 5px;
}

.list-item {
  margin-bottom: 10px;
  border: 1px solid black;
  padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="contents"></div>


问:
AnguarJS expression error on goland
I am developing an AngularJS application on Goland.

Goland claims error on an expression {{ count * times }} as below.

I am enabling AngularJS plugin on Goland as below.

Why {{count * times}} got error on Goland? How can I fix?

答:
As a workaround open Help | Edit Custom Properties and add go.disable.template.substitution=true there. Then restart the IDE.

Also, it makes sense to vote for and follow to the corresponding bug report.

Title: AnguarJS expression error on goland


问:
How to suppress dev.off() messages in knitr chunk options with markdown in R
I have a chunk of code I don't want to split up in my .rmd file that I'm knitting in RStudio.

My global options are:

```<code>{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, autodep = T, message = FALSE, warnings = FALSE, cache=TRUE, messages=FALSE)
</code>```

Even my chunk option is:

```<code>{r section025, message=FALSE, warning=FALSE}
code here
</code>```

And the PDF output shows the following in the middle of the page where I have saved an image out in my code:

```<code>## pdf
## 2
</code>```

I seem to have used all the suppression options, so I cannot figure out why this still appears. Thoughts appreciated.

答:
send the result of dev.off() to a garbage variable</p>

```<code>whatever <- dev.off()
</code>```

Body:
I have a chunk of code I don't want to split up in my .rmd file that I'm knitting in RStudio.

My global options are:

{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, autodep = T, message = FALSE, warnings = FALSE, cache=TRUE, messages=FALSE)

Even my chunk option is:

{r section025, message=FALSE, warning=FALSE}
code here

And the PDF output shows the following in the middle of the page where I have saved an image out in my code:

## pdf
## 2

I seem to have used all the suppression options, so I cannot figure out why this still appears. Thoughts appreciated.

Body:
send the result of dev.off() to a garbage variable

whatever <- dev.off()


问:
Draw Custom Line chart in Android
I want to draw this gradient line chart in Android

Custom line chart

Do you know how can I draw this line chart?

答:
Try out this library. This you can use as per your need.
MPAndroid Chart library... It support customisation.</p>

Title: Draw Custom Line chart in Android


问:
Algolia synonym search adding characters
Hi I have a problem on this page
https://www.hwl.dk/da/frontpage?q=sp%C3%A6kbr%C3%A6t&hPP=6

Where the italic text in the search result says things like spækbrætt8 and spækbrættn when I have a two way synonym set up for [spækbræt,skærebræt] and the original text in the search result is "skærebræt".

My question is this:
Why does algolia add t8 and tn and so on to the end of the result when using synonyms.

PS.
The æøå, ÆØÅ letters are native to Denmark by the way.

答: This was a bug in Algolia's API, which is now fixed (as of Friday, November 10th, 2017).</p>


答:
Interesting that global functions and properties are not listed in Mozilla's official reserved word list:

https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words

Absolutely don't use any variables or function names that are in either of the previous lists. As you found, there may be additional peculiarities per-browser.

Title: "Evaluate" doesn't work as a javascript function name in Mozilla firefox and google-chrome


问:
Why is this variable out of scope? (Haskell)
I'll get right to it (I removed a bunch of extraneous code, in case this looks a little funny -- trying to make this a MCVE):

```<code>import System.IO
import Control.Monad
import Data.IORef

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering

    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    x <- newIORef x0
    loop

loop :: IO ()
loop = do
    input_line <- getLine
    let the_dir = input_line :: String

    putStrLn x

    loop
</code>```

Just to test it I tried outputting x and it's saying it's out of scope. Why? How do I fix it so it is in scope? I need to access the variables but I also need to have them initialized before I enter the loop for the first time.

答:
You can make x a parameter.

```<code>import System.IO
import Control.Monad
import Data.IORef

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering

    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    x <- newIORef x0
    loop x

loop :: Int -> IO ()
loop x = do
    input_line <- getLine
    let the_dir = input_line :: String

    putStrLn $ show x

    loop
</code>```

Or simply use forever.

```<code>import Control.Monad

...

    x <- newIORef x0
    forever $ do
        input_line <- getLine
        let the_dir = input_line :: String

        putStrLn $ show x
</code>```

Body:
I'll get right to it (I removed a bunch of extraneous code, in case this looks a little funny -- trying to make this a MCVE):

import System.IO
import Control.Monad
import Data.IORef

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering

    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    x <- newIORef x0
    loop

loop :: IO ()
loop = do
    input_line <- getLine
    let the_dir = input_line :: String

    putStrLn x

    loop

Just to test it I tried outputting x and it's saying it's out of scope. Why? How do I fix it so it is in scope? I need to access the variables but I also need to have them initialized before I enter the loop for the first time.

Body:
You can make x a parameter.

import System.IO
import Control.Monad
import Data.IORef

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering

    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    x <- newIORef x0
    loop x

loop :: Int -> IO ()
loop x = do
    input_line <- getLine
    let the_dir = input_line :: String

    putStrLn $ show x

    loop

Or simply use forever.

import Control.Monad

...

    x <- newIORef x0
    forever $ do
        input_line <- getLine
        let the_dir = input_line :: String

        putStrLn $ show x


问:
Reading input file into array, sorting it, then outputting it to a file
I'm very new to programming and java but I have an assignment where I'm have to create a program that opens and reads an input text file that has 12
integer numbers written in it, reads the numbers of the text file into an integer array that I create, passes the array as a parameter to a method that sorts the array from low to high, then writes these sorted array numbers to an output file. The output file should also display the average of all the integers numbers, computed using a loop, and placed at the end of the sorted list of integers.

Below is what I have so far. I can't seem to figure out how to properly get the array sorted and sent back to the main function. I'm also unclear how to get and output the average. If anyone can help I'd greatly appreciate it.
Thank you in advance.

```<code>import java.util.Scanner;
import java.util.Arrays;

public class NumberSorter {

    public static void main(String[] args) throws Exception {
        double sum = 0;
        double avg = 0;
        double total = 0;
        int i = 0,
        number = 0;
        int[] data_array = new int[12];
        java.io.File file = new java.io.File("numbers.txt");
        Scanner input = new Scanner(file);

        while(input.hasNext()){
           data_array[i] = input.nextInt();
           sortArray(data_array);
           avg = sum/total;
           java.io.PrintWriter output = new java.io.PrintWriter("dataout.txt");
           output.close();
        }
    }

    public static void sortArray(int[] data_array)
    {
        Arrays.sort(data_array);
    }
}
</code>```

答:
Your main problem with reading into your data_array is that you just read into position 0 each time as you never increment the value of i in your while loop. So each time, you overwrite the first element of the array with the next value in your text file.

This can simply be solved by adding i++; below data_array[i] = input.nextInt();

Then, I would recommend doing the output and sorting outside of this loop, the whole separation of concerns idea (Note: ideally all done with different methods or classes depending on the problem, but I will just leave it in the main method here for example purposes).

So therefore, it's better to move the sortArray call outside of the while loop, as currently this will sort the array, then you try to add the next int to the next position, but as the array is in a different order now (probably), it will not add it where you think it does.

Another problem you are encountering is, that you aren't writing anything to the dataout file.

There are many ways to write to a file, but this is just one example.

```<code>java.io.FileWriter fr = new java.io.FileWriter("dataout.txt");
        BufferedWriter br = new BufferedWriter(fr);
        try (PrintWriter output = new PrintWriter(br)) {
            for (int j = 0; j < data_array.length; j++) {
                System.out.println(data_array[j]);
                output.write(data_array[j] + "\r\n");
            }
        }
</code>```

Then you can calculate your average, and just append it to the end of the file.

But first, you need to calculate the sum of all the numbers in the array.

So, instead of creating another loop, you should just add it into your earlier while loop, adding the value with each iteration.

```<code>sum += data_array[i];
</code>```

As you're using an array (i.e. fixed length), you could use the array.length() to get the value for your total variable, or else just add total++; into the while loop.

Then your avg = sum / total; will work.

Full code:

```<code>public class NumberSorter {

    public static void main(String[] args) throws Exception {
        double sum = 0;
        double avg = 0;
        double total = 0;
        int i = 0;
        int[] data_array = new int[12];
        java.io.File file = new java.io.File("numbers.txt");
        Scanner input = new Scanner(file);

        while (input.hasNext()) {
            data_array[i] = input.nextInt();
            //add to the sum variable to get the total value of all the numbers
            sum += data_array[i];
            total++;
            //increment the position of 'i' each time
            i++;
        }
        //only sort the array after you have all the elements
        sortArray(data_array);

        //gets the average of all elements of the array
        avg = sum / total;

        java.io.FileWriter fr = new java.io.FileWriter("dataout.txt");
        BufferedWriter br = new BufferedWriter(fr);
        try (PrintWriter output = new PrintWriter(br)) {
            for (int j = 0; j < data_array.length; j++) {
                //write each element plus a new line
                output.write(data_array[j] + "\r\n");
            }
            //write the average (to two decimal places - plus it doesn't allow
            //you to write doubles directly anyway) to the file
            output.write(String.format("%.2f", avg));
            output.close();
        }
    }

    public static void sortArray(int[] data_array) {
        Arrays.sort(data_array);
    }
}
</code>```

Body:
I'm very new to programming and java but I have an assignment where I'm have to create a program that opens and reads an input text file that has 12
integer numbers written in it, reads the numbers of the text file into an integer array that I create, passes the array as a parameter to a method that sorts the array from low to high, then writes these sorted array numbers to an output file. The output file should also display the average of all the integers numbers, computed using a loop, and placed at the end of the sorted list of integers.

Below is what I have so far. I can't seem to figure out how to properly get the array sorted and sent back to the main function. I'm also unclear how to get and output the average. If anyone can help I'd greatly appreciate it.
Thank you in advance.

import java.util.Scanner;
import java.util.Arrays;

public class NumberSorter {

    public static void main(String[] args) throws Exception {
        double sum = 0;
        double avg = 0;
        double total = 0;
        int i = 0,
        number = 0;
        int[] data_array = new int[12];
        java.io.File file = new java.io.File("numbers.txt");
        Scanner input = new Scanner(file);

        while(input.hasNext()){
           data_array[i] = input.nextInt();
           sortArray(data_array);
           avg = sum/total;
           java.io.PrintWriter output = new java.io.PrintWriter("dataout.txt");
           output.close();
        }
    }

    public static void sortArray(int[] data_array)
    {
        Arrays.sort(data_array);
    }
}

Body:
Your main problem with reading into your data_array is that you just read into position 0 each time as you never increment the value of i in your while loop. So each time, you overwrite the first element of the array with the next value in your text file.

This can simply be solved by adding i++; below data_array[i] = input.nextInt();

Then, I would recommend doing the output and sorting outside of this loop, the whole separation of concerns idea (Note: ideally all done with different methods or classes depending on the problem, but I will just leave it in the main method here for example purposes).

So therefore, it's better to move the sortArray call outside of the while loop, as currently this will sort the array, then you try to add the next int to the next position, but as the array is in a different order now (probably), it will not add it where you think it does.

Another problem you are encountering is, that you aren't writing anything to the dataout file.

There are many ways to write to a file, but this is just one example.

java.io.FileWriter fr = new java.io.FileWriter("dataout.txt");
        BufferedWriter br = new BufferedWriter(fr);
        try (PrintWriter output = new PrintWriter(br)) {
            for (int j = 0; j < data_array.length; j++) {
                System.out.println(data_array[j]);
                output.write(data_array[j] + "\r\n");
            }
        }

Then you can calculate your average, and just append it to the end of the file.

But first, you need to calculate the sum of all the numbers in the array.

So, instead of creating another loop, you should just add it into your earlier while loop, adding the value with each iteration.

sum += data_array[i];

As you're using an array (i.e. fixed length), you could use the array.length() to get the value for your total variable, or else just add total++; into the while loop.

Then your avg = sum / total; will work.

Full code:

public class NumberSorter {

    public static void main(String[] args) throws Exception {
        double sum = 0;
        double avg = 0;
        double total = 0;
        int i = 0;
        int[] data_array = new int[12];
        java.io.File file = new java.io.File("numbers.txt");
        Scanner input = new Scanner(file);

        while (input.hasNext()) {
            data_array[i] = input.nextInt();
            //add to the sum variable to get the total value of all the numbers
            sum += data_array[i];
            total++;
            //increment the position of 'i' each time
            i++;
        }
        //only sort the array after you have all the elements
        sortArray(data_array);

        //gets the average of all elements of the array
        avg = sum / total;

        java.io.FileWriter fr = new java.io.FileWriter("dataout.txt");
        BufferedWriter br = new BufferedWriter(fr);
        try (PrintWriter output = new PrintWriter(br)) {
            for (int j = 0; j < data_array.length; j++) {
                //write each element plus a new line
                output.write(data_array[j] + "\r\n");
            }
            //write the average (to two decimal places - plus it doesn't allow
            //you to write doubles directly anyway) to the file
            output.write(String.format("%.2f", avg));
            output.close();
        }
    }

    public static void sortArray(int[] data_array) {
        Arrays.sort(data_array);
    }
}


问:
Java Recursion.. need help understanding the solution of the recursive case
Write a method writeChars that accepts an integer parameter n and that prints out n characters as follows. The middle character of the output should always be an asterisk ("*"). If you are asked to write out an even number of characters, then there will be two asterisks in the middle ("**"). Before the asterisk(s) you should write out less-than characters ("<"). After the asterisk(s) you should write out greater-than characters (">").

I've managed to solve the problem but dont quite understand one statement:

```<code>public void writeChars(int n) {
    if ( n < 1 ) {
        throw new IllegalArgumentException();
    }

    if( n == 1 ){
        System.out.print("*");
        return;
    }

    if ( n == 2 ) {
        System.out.print("**");
        return;
    }

    System.out.print("<");
    writeChars(n-2);
    System.out.print(">");
}
</code>```

why is the recursive case:

```<code>writeChars(n-2);
</code>```

n-2? instead of n-1?

答:
For every recursion call the code is printing exactly two outputs. Hence for every iteration the number should be decreased by two.
If you write n-1 then the number of characters its printing would become double. Hence we have to write, n-2
One print statement before the recursion statement and one after.

Body:
Write a method writeChars that accepts an integer parameter n and that prints out n characters as follows. The middle character of the output should always be an asterisk ("*"). If you are asked to write out an even number of characters, then there will be two asterisks in the middle ("**"). Before the asterisk(s) you should write out less-than characters ("<"). After the asterisk(s) you should write out greater-than characters (">").

I've managed to solve the problem but dont quite understand one statement:

public void writeChars(int n) {
    if ( n < 1 ) {
        throw new IllegalArgumentException();
    }

    if( n == 1 ){
        System.out.print("*");
        return;
    }

    if ( n == 2 ) {
        System.out.print("**");
        return;
    }

    System.out.print("<");
    writeChars(n-2);
    System.out.print(">");
}

why is the recursive case:

writeChars(n-2);

n-2? instead of n-1?


问:
OS X Masonry view animation without effect

[macOS | OS X] Masonry view animation without effect

[✔] I have looked at the Documentation

[✔] I have filled out this issue template.

Issue Info

Platform: os x

Platform Version: 10.12.6

Masonry Version: 1.1.0

Issue Description

I'm using masonry autolayout in os x application project, I find out move animation in the view without effect. That is to say the view direct move to target location and no animation process.

My code is as follows:

```<code>[NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) {
    [context setDuration:0.5];
    context.allowsImplicitAnimation = YES;
    [_playlistView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_right).with.offset(-kPlaylistBuoyBtnW-kPlaylistMainViewW);
    }];
} completionHandler:^{
    debugMethod();
}];
</code>```

How to implement? It is best to use the sample code.

Appreciate if any suggestion or idea.

答:
First, declare an property in the view's interface.

```<code>@property (nonatomic, strong) MASConstraint *leftConstraint;
</code>```

Secondly, use this property to do animation.

```<code>[NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) {
    [context setDuration:kPlaylistPopAnimationTimes];
    context.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    _playlistView.leftConstraint.animator.offset(-kPlaylistBuoyBtnW-kPlaylistMainViewW);
} completionHandler:^{
    [_playlistView updateBuoyBtnState:state];
}];
</code>```

Finally, other direction of animation is the same.

Body:
[macOS | OS X] Masonry view animation without effect

[✔] I have looked at the Documentation

[✔] I have filled out this issue template.

Issue Info

Platform: os x

Platform Version: 10.12.6

Masonry Version: 1.1.0

Issue Description

I'm using masonry autolayout in os x application project, I find out move animation in the view without effect. That is to say the view direct move to target location and no animation process.

My code is as follows:

[NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) {
    [context setDuration:0.5];
    context.allowsImplicitAnimation = YES;
    [_playlistView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_right).with.offset(-kPlaylistBuoyBtnW-kPlaylistMainViewW);
    }];
} completionHandler:^{
    debugMethod();
}];

How to implement? It is best to use the sample code.

Appreciate if any suggestion or idea.

Body:
First, declare an property in the view's interface.

@property (nonatomic, strong) MASConstraint *leftConstraint;

Secondly, use this property to do animation.

[NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) {
    [context setDuration:kPlaylistPopAnimationTimes];
    context.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    _playlistView.leftConstraint.animator.offset(-kPlaylistBuoyBtnW-kPlaylistMainViewW);
} completionHandler:^{
    [_playlistView updateBuoyBtnState:state];
}];

Finally, other direction of animation is the same.


问:
Subproject does not upload to bitbucket
I have a Symfony project (used as backend) that was linked with a repository on Bitbucket, in this project I installed a subproject angular 2 named frontend (theme angular downloaded from Github), when I execute git push origin master the frontend folder does not upload to bitbucket.

答:
Are you sure you add all files (folder etc.)? Did you try git add . command ?

When you use git add . it looks at the working tree and adds all those paths to the staged changes.

Title: Subproject does not upload to bitbucket


问:
convert string arrayList to Integer ArrayList
I have Model class ModelWeeklyGuarantee That  want to convert string arrayList to integer arrayList

Example [5,7,9] string arrayList, to IntegerArrayList [5,7,8] at index 0.

```<code>public static ArrayList<Integer> listOfGuarantees= new ArrayList<Integer>();
 @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    ModelWeeklyGuarantee ModelGuarantee = GauranteeList.get(position);

    JSONArray jsonArray = ModelGuarantee.getWeeklyDataList();
    Log.d("getWeeklyDataList",""+jsonArray);
    for(int i = 0, count = jsonArray.length(); i< count; i++)
    {
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            //Integer abc= Integer.valueOf(jsonObject.toString());
            listOfGuarantees.add( Integer.valueOf(jsonObject.toString()));
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("guaranteevalues",""+listOfGuarantees);
    }
</code>```

getWeeklyDataList: ["5","7","9"]

getWeeklyDataList: ["10","11","12"]

guaranteevalues=[]

org.json.JSONException: Value 5 at 0 of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:100)

答:
You cannot hold string to json object.

Replace this line

```<code>JSONObject jsonObject = jsonArray.getJSONObject(i);
listOfGuarantees.add( Integer.valueOf(jsonObject.toString()));
</code>```

with

```<code>String obj = jsonArray.getString(i);
listOfGuarantees.add( Integer.valueOf(obj));
</code>```

Or Simply use

```<code>listOfGuarantees.add(Integer.valueOf(jsonArray.getString(i)));
</code>```

EDIT/UPDATED

```<code>ArrayList<int[]> listOfGuarantees= new ArrayList<int[]>();
int[] values;
JSONArray jsonArray = ModelGuarantee.getWeeklyDataList();
Log.d("getWeeklyDataList",""+jsonArray);
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
    values = new int[] { count };
    try
    {
        String str = jsonArray.getString(i);
        values[i] = Integer.valueOf(str);
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("guaranteevalues",""+listOfGuarantees);
}
 listOfGuarantees.add(values);
</code>```

Hope it helps!

Body:
I have Model class ModelWeeklyGuarantee That  want to convert string arrayList to integer arrayList

Example [5,7,9] string arrayList, to IntegerArrayList [5,7,8] at index 0.

public static ArrayList<Integer> listOfGuarantees= new ArrayList<Integer>();
 @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    ModelWeeklyGuarantee ModelGuarantee = GauranteeList.get(position);

    JSONArray jsonArray = ModelGuarantee.getWeeklyDataList();
    Log.d("getWeeklyDataList",""+jsonArray);
    for(int i = 0, count = jsonArray.length(); i< count; i++)
    {
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            //Integer abc= Integer.valueOf(jsonObject.toString());
            listOfGuarantees.add( Integer.valueOf(jsonObject.toString()));
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("guaranteevalues",""+listOfGuarantees);
    }

getWeeklyDataList: ["5","7","9"]

getWeeklyDataList: ["10","11","12"]

guaranteevalues=[]

org.json.JSONException: Value 5 at 0 of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:100)

Body:
You cannot hold string to json object.

Replace this line

JSONObject jsonObject = jsonArray.getJSONObject(i);
listOfGuarantees.add( Integer.valueOf(jsonObject.toString()));

with

String obj = jsonArray.getString(i);
listOfGuarantees.add( Integer.valueOf(obj));

Or Simply use

listOfGuarantees.add(Integer.valueOf(jsonArray.getString(i)));

EDIT/UPDATED

ArrayList<int[]> listOfGuarantees= new ArrayList<int[]>();
int[] values;
JSONArray jsonArray = ModelGuarantee.getWeeklyDataList();
Log.d("getWeeklyDataList",""+jsonArray);
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
    values = new int[] { count };
    try
    {
        String str = jsonArray.getString(i);
        values[i] = Integer.valueOf(str);
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("guaranteevalues",""+listOfGuarantees);
}
 listOfGuarantees.add(values);

Hope it helps!


问:
Add a navigation bar to a view without a navigation controller
I have a side menu that slides out to display a table view and from there I have segues that use the reveal view controller. The segue has to connect directly to the view controller; I can't use a navigation controller.

How do I add a navigation bar with a bar button item without a navigation controller?

答:
Swift 4 Version

```<code> let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
    navigationBar.barTintColor = UIColor.lightGray
    view.addSubview(navigationBar)

    let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: nil)
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: nil)

    let navigationItem = UINavigationItem(title: "Title")
    navigationItem.leftBarButtonItem = cancelButton
    navigationItem.rightBarButtonItem = doneButton

    navigationBar.items = [navigationItem]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Swift 4 Version

 let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
    navigationBar.barTintColor = UIColor.lightGray
    view.addSubview(navigationBar)

    let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: nil)
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: nil)

    let navigationItem = UINavigationItem(title: "Title")
    navigationItem.leftBarButtonItem = cancelButton
    navigationItem.rightBarButtonItem = doneButton

    navigationBar.items = [navigationItem]


问:
look for match from a different array in ruby
I have a base array like this

```<code>base_array=[0,3,5]
</code>```

There is a

```<code>second_array=[4,5,6,0,5,4]
</code>```

What I want is create a new array from second_array but filter out the values missing in base_array

So new array will look like this

```<code>new_array=[5,0,5]
</code>```

How can I do this in ruby?
Thank you.

Body:
I have a base array like this

base_array=[0,3,5]

There is a

second_array=[4,5,6,0,5,4]

What I want is create a new array from second_array but filter out the values missing in base_array

So new array will look like this

new_array=[5,0,5]

How can I do this in ruby?
Thank you.

Body:
try this

new_array = second_array  - (second_array  - base_array )
[4,5,6,0,5,4] - ([4,5,6,0,5,4] - [0,3,5])
>> [5, 0, 5]


问:
CMake shared library in subdirectory
My problem is relatively simple to explain. I have a CMake project(using CLion) running mainly on Windows.

A main CMakeLists.txt project, linking 2 subdirectories

src/Library shared library

src/Executable executable linking Library

See the project structure below.

    # main CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.8)
project(TestTest)

set(CMAKE_CXX_STANDARD 11)

add_subdirectory(src/Library)
add_subdirectory(src/Executable)

# src/Library/CMakeLists.txt
add_subdirectory(include)
add_subdirectory(src)

add_library(TestLib SHARED ${TESTLIB_H_FILES} ${TESTLIB_SRC_FILES} )
target_include_directories(TestLib PUBLIC include)

#src/Executable/CMakeLists.txt

add_subdirectory(src)
add_executable(Executable ${EXECUTABLE_SRC_FILES})
target_link_libraries(Executable PUBLIC TestLib)
</code>```

My problem is that the executable can't find the shared library at runtime.

I tried to add link_directories( ${CMAKE_CURRENT_BINARY_DIR}/src/Library) but didn't work.

What am I missing?

Please note: I wouldn't like to copy the shared library next to the executable manually/automatically by CMake, since I believe I would loose the debugging "capability" of the shared library. I will be getting the following error message by the GDB: No source file named C:/Users/flatron/CLionProjects/TestTest/src/Library/src/library.cpp.

All suggestions are really welcome and appreciated,

Thank you for your help

答:
I suggest to use the following cmake command:

```<code>set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
</code>```

This will build all executables and shared libraries into the bin folder.
So there is no need to copy anything by hand.

Title: CMake shared library in subdirectory

Body:
My problem is relatively simple to explain. I have a CMake project(using CLion) running mainly on Windows.

A main CMakeLists.txt project, linking 2 subdirectories

src/Library shared library

src/Executable executable linking Library

See the project structure below.

    # main CMakeLists.txt

cmake_minimum_required(VERSION 3.8)
project(TestTest)

set(CMAKE_CXX_STANDARD 11)

add_subdirectory(src/Library)
add_subdirectory(src/Executable)

# src/Library/CMakeLists.txt
add_subdirectory(include)
add_subdirectory(src)

add_library(TestLib SHARED ${TESTLIB_H_FILES} ${TESTLIB_SRC_FILES} )
target_include_directories(TestLib PUBLIC include)

#src/Executable/CMakeLists.txt

add_subdirectory(src)
add_executable(Executable ${EXECUTABLE_SRC_FILES})
target_link_libraries(Executable PUBLIC TestLib)

My problem is that the executable can't find the shared library at runtime.

I tried to add link_directories( ${CMAKE_CURRENT_BINARY_DIR}/src/Library) but didn't work.

What am I missing?

Please note: I wouldn't like to copy the shared library next to the executable manually/automatically by CMake, since I believe I would loose the debugging "capability" of the shared library. I will be getting the following error message by the GDB: No source file named C:/Users/flatron/CLionProjects/TestTest/src/Library/src/library.cpp.

All suggestions are really welcome and appreciated,

Thank you for your help

Body:
I suggest to use the following cmake command:

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

This will build all executables and shared libraries into the bin folder.
So there is no need to copy anything by hand.


问:
How to validate Mono when using Spring Reactive
We are evaluating Spring 5 for a project, and not sure how best to validate Mono parameters. Traditionally we had been using MethodValidationPostProcessor to validate our method parameters as below:

```<code>@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public void signup(@Valid UserCommand userCommand) {

    ...
}
</code>```

We would then handle the exception in a ControllerAdvice or ErrorController, and pass a suitable 4xx response to the client.

But when I change the parameter to Mono, as below, it no more seems to work.

```<code>@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {

    ...
}
</code>```

As I understand Spring Reactive, probably it's actually not supposed to work. So, what would be Spring 5 best practices for validating Monos and Fluxes, and then sending a suitable error response?

答:
Quick not before answering that question, the void return type of your method is quite unusual in a reactive application. Looking at this, it seems this method should perform actual work asynchronously but the method returns a synchronous type. I've changed that as a Mono<Void> in my answer.

As stated in the reference documentation, Spring WebFlux does support validation.

But best practices differ here, because method parameters can be reactive types. You can't have the validation result if the method parameter hasn't been resolved yet.

So something like that won't really work:

```<code>// can't have the BindingResult synchronously,
// as the userCommand hasn't been resolved yet
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand, BindingResult result)

// while technically feasible, you'd have to resolve
// the userCommand first and then look at the validation result
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand, Mono<BindingResult> result)
</code>```

Something more idiomatic and easier to use with reactive operators:

```<code>public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {
    /*
     * a WebExchangeBindException will flow through the pipeline
     * in case of validation error.
     * you can use onErrorResume or other onError* operators
     * to map the given exception to a custom one
     */
    return userCommand.onErrorResume(t -> Mono.error(...)).then();
}
</code>```

Body:
We are evaluating Spring 5 for a project, and not sure how best to validate Mono parameters. Traditionally we had been using MethodValidationPostProcessor to validate our method parameters as below:

@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public void signup(@Valid UserCommand userCommand) {

    ...
}

We would then handle the exception in a ControllerAdvice or ErrorController, and pass a suitable 4xx response to the client.

But when I change the parameter to Mono, as below, it no more seems to work.

@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {

    ...
}

As I understand Spring Reactive, probably it's actually not supposed to work. So, what would be Spring 5 best practices for validating Monos and Fluxes, and then sending a suitable error response?

Body:
Quick not before answering that question, the void return type of your method is quite unusual in a reactive application. Looking at this, it seems this method should perform actual work asynchronously but the method returns a synchronous type. I've changed that as a Mono<Void> in my answer.

As stated in the reference documentation, Spring WebFlux does support validation.

But best practices differ here, because method parameters can be reactive types. You can't have the validation result if the method parameter hasn't been resolved yet.

So something like that won't really work:

// can't have the BindingResult synchronously,
// as the userCommand hasn't been resolved yet
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand, BindingResult result)

// while technically feasible, you'd have to resolve
// the userCommand first and then look at the validation result
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand, Mono<BindingResult> result)

Something more idiomatic and easier to use with reactive operators:

public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {
    /*
     * a WebExchangeBindException will flow through the pipeline
     * in case of validation error.
     * you can use onErrorResume or other onError* operators
     * to map the given exception to a custom one
     */
    return userCommand.onErrorResume(t -> Mono.error(...)).then();
}


问:
Calling or sending values from MainViewModel to other ViewModels mvvm mvvm light
We are using mvvm light framework to build our application. In our ViewModel folder, we have number of Viewmodel like orderSupplyViewModel,HouseholdSupplyViewModel etc files as per the different functionality of the application. We have included all these viewModels in the MainViewModel by making the MainViewModel as partial class. So you can say we have one MainViewModel. Now we have completed 40% of the application and we need to separate the view Models as one partial class. So that we can call the different viewmodels from the mainviewModel. How to go about it? Following is the code realted to one viewmodel named - OrderSuppliesViewModel</p>

```<code>namespace ParentalHealthClient.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// </summary>
    public partial class MainViewModel : ViewModelBase
    {
        private List<UserMedicalSupplyBO> _selectedFavouriteMedicalItems;
        private List<HouseholdItemsBO> _selectedFavouriteHouseHoldItems;
        private List<OrderSuppliesBO> _selectedOrderItems;
        private HouseholdSuppliesDAO _dataAccessForOrder;

        /// <summary>
        /// Initializes a new instance of the OrderSuppliesViewModel class.
        /// </summary>
        public void OrderSuppliesViewModel()
        {

        }
</code>```

答:
You should NOT have a bunch of MainViewModel partial definitions.  You should create individual ViewModel classes for each type of ViewModel.

In Visual Studio, Solution Explorer, <Your Project>, right-click on [ViewModel] folder -> Add -> New Item... -> Mvvm Light ViewModel.  This should add a new ViewModel class which inherits ViewModelBase.

Body:
We are using mvvm light framework to build our application. In our ViewModel folder, we have number of Viewmodel like orderSupplyViewModel,HouseholdSupplyViewModel etc files as per the different functionality of the application. We have included all these viewModels in the MainViewModel by making the MainViewModel as partial class. So you can say we have one MainViewModel. Now we have completed 40% of the application and we need to separate the view Models as one partial class. So that we can call the different viewmodels from the mainviewModel. How to go about it? Following is the code realted to one viewmodel named - OrderSuppliesViewModel

namespace ParentalHealthClient.ViewModel
{
    ///
    /// This class contains properties that a View can data bind to.
    /// <para>
    ///
    public partial class MainViewModel : ViewModelBase
    {
        private List<UserMedicalSupplyBO> _selectedFavouriteMedicalItems;
        private List<HouseholdItemsBO> _selectedFavouriteHouseHoldItems;
        private List<OrderSuppliesBO> _selectedOrderItems;
        private HouseholdSuppliesDAO _dataAccessForOrder;

        ///
        /// Initializes a new instance of the OrderSuppliesViewModel class.
        ///
        public void OrderSuppliesViewModel()
        {

        }


问:
Do list except with two list of different classes instances
I want to compare two list with objects of two different classes. These are the classes:

```<code>namespace AngularWebApplication.Models
{
    public class AggregationLevelConfigurationPresentation
    {
        public byte AggregationLevelConfigurationId { get; set; }
        public int ProductionOrderId { get; set; }
        public string Name { get; set; }
        [ ... ]
    }
}

public class AggregationLevelConfiguration : IEquatable<AggregationLevelConfiguration>
{
    public byte AggregationLevelConfigurationId { get; set; }
    public int ProductionOrderId { get; set; }
    public string Name { get; set; }
    [ ... ]
}
</code>```

I want to get the elements in presentations list that are not in currentLevels:

List presentations;
List currentLevels;

```<code>List<Models.AggregationLevelConfigurationPresentation> newLevels =
    presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .ToList();
</code>```

But I get the following error when I do the Except:

```<code>Error   CS0029  Cannot implicitly convert type
'System.Collections.Generic.List<<anonymous type: byte AggregationLevelConfigurationId, int ProductionOrderId>>' to
'System.Collections.Generic.List<AngularWebApplication.Models.AggregationLevelConfigurationPresentation>'
</code>```

I think the problem is in the new { l.AggregationLevelConfigurationId, l.ProductionOrderId } but I don't know how to do the Except with list of objects from different classes.

I need the objects in presentations list that they aren't in currentLevels using AggregationLevelConfigurationId and ProductionOrderId as primary key.

答:
Your Execept-query selects anonymous types, so ToList doesn't create a  List<AggregationLevelConfigurationPresentation>. You have to create instances of this class:

```<code>List<AggregationLevelConfigurationPresentation> newLevels = presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .Select(x => new AggregationLevelConfigurationPresentation
        {
            AggregationLevelConfigurationId = x.AggregationLevelConfigurationId,
            ProductionOrderId = x.ProductionOrderId
         })
        .ToList();
</code>```

I need the objects in presentations list that they aren't in
  currentLevels using AggregationLevelConfigurationId and
  ProductionOrderId as primary key.

Then you could use Join:

```<code>var except = presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }));

var newLevels = from x in except
                join p in presentations
                on x equals new { p.AggregationLevelConfigurationId, p.ProductionOrderId }
                select p;
List<AggregationLevelConfigurationPresentation> newLevelList = newLevels.ToList();
</code>```

Body:
I want to compare two list with objects of two different classes. These are the classes:

namespace AngularWebApplication.Models
{
    public class AggregationLevelConfigurationPresentation
    {
        public byte AggregationLevelConfigurationId { get; set; }
        public int ProductionOrderId { get; set; }
        public string Name { get; set; }
        [ ... ]
    }
}

public class AggregationLevelConfiguration : IEquatable<AggregationLevelConfiguration>
{
    public byte AggregationLevelConfigurationId { get; set; }
    public int ProductionOrderId { get; set; }
    public string Name { get; set; }
    [ ... ]
}

I want to get the elements in presentations list that are not in currentLevels:

List presentations;
List currentLevels;

List<Models.AggregationLevelConfigurationPresentation> newLevels =
    presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .ToList();

But I get the following error when I do the Except:

Error   CS0029  Cannot implicitly convert type
'System.Collections.Generic.List<<anonymous type: byte AggregationLevelConfigurationId, int ProductionOrderId>>' to
'System.Collections.Generic.List<AngularWebApplication.Models.AggregationLevelConfigurationPresentation>'

I think the problem is in the new { l.AggregationLevelConfigurationId, l.ProductionOrderId } but I don't know how to do the Except with list of objects from different classes.

I need the objects in presentations list that they aren't in currentLevels using AggregationLevelConfigurationId and ProductionOrderId as primary key.

Body:
Your Execept-query selects anonymous types, so ToList doesn't create a  List<AggregationLevelConfigurationPresentation>. You have to create instances of this class:

List<AggregationLevelConfigurationPresentation> newLevels = presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .Select(x => new AggregationLevelConfigurationPresentation
        {
            AggregationLevelConfigurationId = x.AggregationLevelConfigurationId,
            ProductionOrderId = x.ProductionOrderId
         })
        .ToList();

I need the objects in presentations list that they aren't in
  currentLevels using AggregationLevelConfigurationId and
  ProductionOrderId as primary key.

Then you could use Join:

var except = presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }));

var newLevels = from x in except
                join p in presentations
                on x equals new { p.AggregationLevelConfigurationId, p.ProductionOrderId }
                select p;
List<AggregationLevelConfigurationPresentation> newLevelList = newLevels.ToList();


问:
Azure Notification Hub losing the subscribe when app is reinstalled
I have a problem with Azure Notification Hub.

When my app is started in first time, the notifications working correctly, but when did a rebuild the app by Visual Studio, the notifications stop working and the Android Services with IntentFilters do not are called.

For the notifications works again, I need to uninstall the App in Android and run by Visual Studio again.

Have someone some idea about that problem?

My worry is: if I send the app to GooglePlay, the notifications would continue working after a update?

If someone know how to call the service to get the new InstallationId, always that the app to be started I will know how I can resolve the problem.

Can someone help me?

I did follow that tutorial:
https://www.youtube.com/watch?v=le2lDY22xwM&t=3312s

答:
if I send the app to GooglePlay, the notifications would continue working after a update?

There is no need to worry about that, referring to this document, when you use Azure Notification Hub, it's using Android GCM to send the push notificcation. You could see my answer about Android using Firebase Cloud Messaging not receiving message.

As the Official document said :

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.

Explanation about Token :

An ID issued by the GCM connection servers to the client app that allows it to receive messages.

When you did a rebuild the app by Visual Studio your token is changed, but it didn't trigger the  OnTokenRefresh method, so at this time the Token in your application is invalid. That's why your application cannot receiving message.

For more information, you could refer to Sending Push Notifications from Azure Mobile Apps and Implement the Firebase Instance ID Service.

When your app get a update, it will trigger the  OnTokenRefresh method automatically, so your application can still receive the message.


问:
How do objects turn into arrays?
Example：

```<code>obj={"name":"111","age":"1111"}
</code>```

become

```<code>["name":"111","age":"111"]
</code>```

How do you do it? I don't know what to do

答:
Although, I would just use Object Syntax, you may want to see this:

var what = [];
what['really'] = "That's crazy!";
what['yes'] = 'Awesome';
what['number'] = 10;
console.log(what instanceof Array);
for(var i in what){
  console.log(i+' =', what[i]);
}```

I saw crazy code like this in a book I bought. Note that the length property is not automatically defined with this Syntax, hence the for in loop. It looks, unlike regular Objects, like index order is preserved.

Title: How do objects turn into arrays?

Body:
Example：

obj={"name":"111","age":"1111"}

become

["name":"111","age":"111"]

How do you do it? I don't know what to do

Body:
Although, I would just use Object Syntax, you may want to see this:

var what = [];
what['really'] = "That's crazy!";
what['yes'] = 'Awesome';
what['number'] = 10;
console.log(what instanceof Array);
for(var i in what){
  console.log(i+' =', what[i]);
}

I saw crazy code like this in a book I bought. Note that the length property is not automatically defined with this Syntax, hence the for in loop. It looks, unlike regular Objects, like index order is preserved.


问:
Why can't I store a value and a reference to that value in the same struct?
I have a value and I want to store that value and a reference to
something inside that value in my own type:

```<code>struct Thing {
    count: u32,
}

struct Combined<'a>(Thing, &'a u32);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing { count: 42 };

    Combined(thing, &thing.count)
}
</code>```

Sometimes, I have a value and I want to store that value and a reference to
that value in the same structure:

```<code>struct Combined<'a>(Thing, &'a Thing);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing::new();

    Combined(thing, &thing)
}
</code>```

Sometimes, I'm not even taking a reference of the value and I get the
same error:

```<code>struct Combined<'a>(Parent, Child<'a>);

fn make_combined<'a>() -> Combined<'a> {
    let parent = Parent::new();
    let child = parent.child();

    Combined(parent, child)
}
</code>```

In each of these cases, I get an error that one of the values "does
not live long enough". What does this error mean?

答:
A slightly different issue which causes very similar compiler messages is object lifetime dependency, rather than storing an explicit reference. An example of that is the ssh2 library. When developing something bigger than a test project, it is tempting to try to put the Session and Channel obtained from that session alongside each other into a struct, hiding the implementation details from the user. However, note that the Channel definition has the 'sess lifetime in its type annotation, while Session doesn't.

This causes similar compiler errors related to lifetimes.

One way to solve it in a very simple way is to declare the Session outside in the caller, and then for annotate the reference within the struct with a lifetime, similar to the answer in this Rust User's Forum post talking about the same issue while encapsulating SFTP. This will not look elegant and may not always apply - because now you have two entities to deal with, rather than one that you wanted!

Turns out the rental crate or the owning_ref crate from the other answer are the solutions for this issue too. Let's consider the owning_ref, which has the special object for this exact purpose:
OwningHandle. To avoid the underlying object moving, we allocate it on the heap using a Box, which gives us the following possible solution:

```<code>use ssh2::{Channel, Error, Session};
use std::net::TcpStream;

use owning_ref::OwningHandle;

struct DeviceSSHConnection {
    tcp: TcpStream,
    channel: OwningHandle<Box<Session>, Box<Channel<'static>>>,
}

impl DeviceSSHConnection {
    fn new(targ: &str, c_user: &str, c_pass: &str) -> Self {
        use std::net::TcpStream;
        let mut session = Session::new().unwrap();
        let mut tcp = TcpStream::connect(targ).unwrap();

        session.handshake(&tcp).unwrap();
        session.set_timeout(5000);
        session.userauth_password(c_user, c_pass).unwrap();

        let mut sess = Box::new(session);
        let mut oref = OwningHandle::new_with_fn(
            sess,
            unsafe { |x| Box::new((*x).channel_session().unwrap()) },
        );

        oref.shell().unwrap();
        let ret = DeviceSSHConnection {
            tcp: tcp,
            channel: oref,
        };
        ret
    }
}
</code>```

The result of this code is that we can not use the Session anymore, but it is stored alongside with the Channel which we will be using. Because the OwningHandle object dereferences to Box, which dereferences to Channel, when storing it in a struct, we name it as such. NOTE: This is just my understanding. I have a suspicion this may not be correct, since it appears to be quite close to discussion of OwningHandle unsafety.

One curious detail here is that the Session logically has a similar relationship with TcpStream as Channel has to Session, yet its ownership is not taken and there are no type annotations around doing so. Instead, it is up to the user to take care of this, as the documentation of handshake method says:

This session does not take ownership of the socket provided, it is
  recommended to ensure that the socket persists the lifetime of this
  session to ensure that communication is correctly performed.

It is also highly recommended that the stream provided is not used
  concurrently elsewhere for the duration of this session as it may
  interfere with the protocol.

So with the TcpStream usage, is completely up to the programmer to ensure the correctness of the code. With the OwningHandle, the attention to where the "dangerous magic" happens is drawn using the unsafe {} block.

A further and a more high-level discussion of this issue is in this Rust User's Forum thread - which includes a different example and its solution using the rental crate, which does not contain unsafe blocks.

Body:
I have a value and I want to store that value and a reference to
something inside that value in my own type:

struct Thing {
    count: u32,
}

struct Combined<'a>(Thing, &'a u32);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing { count: 42 };

    Combined(thing, &thing.count)
}

Sometimes, I have a value and I want to store that value and a reference to
that value in the same structure:

struct Combined<'a>(Thing, &'a Thing);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing::new();

    Combined(thing, &thing)
}

Sometimes, I'm not even taking a reference of the value and I get the
same error:

struct Combined<'a>(Parent, Child<'a>);

fn make_combined<'a>() -> Combined<'a> {
    let parent = Parent::new();
    let child = parent.child();

    Combined(parent, child)
}

In each of these cases, I get an error that one of the values "does
not live long enough". What does this error mean?

Body:
A slightly different issue which causes very similar compiler messages is object lifetime dependency, rather than storing an explicit reference. An example of that is the ssh2 library. When developing something bigger than a test project, it is tempting to try to put the Session and Channel obtained from that session alongside each other into a struct, hiding the implementation details from the user. However, note that the Channel definition has the 'sess lifetime in its type annotation, while Session doesn't.

This causes similar compiler errors related to lifetimes.

One way to solve it in a very simple way is to declare the Session outside in the caller, and then for annotate the reference within the struct with a lifetime, similar to the answer in this Rust User's Forum post talking about the same issue while encapsulating SFTP. This will not look elegant and may not always apply - because now you have two entities to deal with, rather than one that you wanted!

Turns out the rental crate or the owning_ref crate from the other answer are the solutions for this issue too. Let's consider the owning_ref, which has the special object for this exact purpose:
OwningHandle. To avoid the underlying object moving, we allocate it on the heap using a Box, which gives us the following possible solution:

use ssh2::{Channel, Error, Session};
use std::net::TcpStream;

use owning_ref::OwningHandle;

struct DeviceSSHConnection {
    tcp: TcpStream,
    channel: OwningHandle<Box<Session>, Box<Channel<'static>>>,
}

impl DeviceSSHConnection {
    fn new(targ: &str, c_user: &str, c_pass: &str) -> Self {
        use std::net::TcpStream;
        let mut session = Session::new().unwrap();
        let mut tcp = TcpStream::connect(targ).unwrap();

        session.handshake(&tcp).unwrap();
        session.set_timeout(5000);
        session.userauth_password(c_user, c_pass).unwrap();

        let mut sess = Box::new(session);
        let mut oref = OwningHandle::new_with_fn(
            sess,
            unsafe { |x| Box::new((*x).channel_session().unwrap()) },
        );

        oref.shell().unwrap();
        let ret = DeviceSSHConnection {
            tcp: tcp,
            channel: oref,
        };
        ret
    }
}

The result of this code is that we can not use the Session anymore, but it is stored alongside with the Channel which we will be using. Because the OwningHandle object dereferences to Box, which dereferences to Channel, when storing it in a struct, we name it as such. NOTE: This is just my understanding. I have a suspicion this may not be correct, since it appears to be quite close to discussion of OwningHandle unsafety.

One curious detail here is that the Session logically has a similar relationship with TcpStream as Channel has to Session, yet its ownership is not taken and there are no type annotations around doing so. Instead, it is up to the user to take care of this, as the documentation of handshake method says:

This session does not take ownership of the socket provided, it is
  recommended to ensure that the socket persists the lifetime of this
  session to ensure that communication is correctly performed.

It is also highly recommended that the stream provided is not used
  concurrently elsewhere for the duration of this session as it may
  interfere with the protocol.

So with the TcpStream usage, is completely up to the programmer to ensure the correctness of the code. With the OwningHandle, the attention to where the "dangerous magic" happens is drawn using the unsafe {} block.

A further and a more high-level discussion of this issue is in this Rust User's Forum thread - which includes a different example and its solution using the rental crate, which does not contain unsafe blocks.


问:
Why should I NOT use the /optimize switch to compile my C# code?
In Visual Studio 2008 there is an option "Optimize Code" that probably corresponds to the /optimize option. It is never enabled, not even when in "Release" mode.

Why should I not want this option to be enabled at all times?

答: It is on per default for release builds (perhaps you changed the settings for Release builds?). Turn it off to make debugging easier. For release code, turn it on. </p>

OwnerDisplayName: boris callens

OwnerDisplayName: Brian Rasmussen

LastEditorDisplayName: Brian Rasmussen


问:
How to hg unshelve without merge
Is there a way I can force hg unshelve without causing any merge conflicts?  Just overwrite the old files with the shelved state?

答:
Simply use

```<code>hg unshelve --tool :other
</code>```

Using the internal merge tool :other will instruct Mercurial to always prefer the shelved version to local changes. See hg help mergetools for more information on the various internal merge tools.

Title: How to hg unshelve without merge

Body:
Simply use

hg unshelve --tool :other

Using the internal merge tool :other will instruct Mercurial to always prefer the shelved version to local changes. See hg help mergetools for more information on the various internal merge tools.


问:
Spark Dataframe loosing data to s3
I have a spark dataframe thats has the cleansed data. I have a total of 512 records in the data frame.
Before I write to the S3, I am repartitioning to a single file since my total number of records are low and I want to keep the number of partitions less.

```<code>val t =tripAttributesDF.repartition(1)
t.write.mode("overwrite").format("csv")
.save("s3://<Bucket>/Trips_Detail_Table/csv/valid_trips_csv")
</code>```

The DataFrame count shows correctly as follows
       scala> t.count()
       res32: Long = 512

But when I open the CSV file I have only 34 rows. Not 512 as I expected.

I looked hard in all posts, and no one seems to have encountered this issue.
I am using Spark 2.2

Please help if anyone knows the answer

Thanks

答: Okay. I am going to answer my own question. This was entirely my fault. I am enforcing a schema on the file, and one of the fields that I need in my final DF is of type Double. I was enforcing an IntegerType and it looks like Spark 2.2 simply truncated the data. There were no errors. When I tried on Spark 2.11, I was able to debug.</p>

Title: Spark Dataframe loosing data to s3

Body:
I have a spark dataframe thats has the cleansed data. I have a total of 512 records in the data frame.
Before I write to the S3, I am repartitioning to a single file since my total number of records are low and I want to keep the number of partitions less.

val t =tripAttributesDF.repartition(1)
t.write.mode("overwrite").format("csv")
.save("s3://<Bucket>/Trips_Detail_Table/csv/valid_trips_csv")

The DataFrame count shows correctly as follows
       scala> t.count()
       res32: Long = 512

But when I open the CSV file I have only 34 rows. Not 512 as I expected.

I looked hard in all posts, and no one seems to have encountered this issue.
I am using Spark 2.2

Please help if anyone knows the answer

Thanks


问:
Xamarin Forms: How to do multiple pages within multiple pages (nested)?
I've been searching for an answer to this for months.  I have an app that will go from a login page (mainpage) to a 6-button menu page (menupage).  Each of the 6 items on the menu page will then go to a 3 or 4 menu item page of it's own.  I know that you are only supposed to put content pages as children of a navigation page, so I think that's out as a possible solution for the initial menupage.  Can you nest tabbed pages (although that style is not what I'm looking for)?

All of the examples I've found online seem to address only one main page and a sub-page kind of hierarchy (parent - child).  I'm looking for something that will support 3 levels and maybe even more (parent - child - grandchild, etc.).

Am I over-complicating this?  Any advice on this would be welcomed.

答:
If i understand you question correctly you could just use a master-detail page with 6 items, each of items being a tabbed page with sub-pages.

If the question was "how to include sub-pages into a page using a custom method", then take a look at: https://github.com/twintechs/TwinTechsFormsLib when you build the sample they have a custom page container for nesting pages insidem the only limitation is child pages can't be navigation ones.


问:
Bulk select using Spring
Is there a way to do a bulk select for below query using Spring alone?

E.g.

```<code>select * from university where name='x' and age=y and gender='z'
</code>```

Where x,y and z come from list such as :

```<code> [[x1, y1, z1],[x2, y2, z2],[x3, y3, z3]..]
</code>```

答:
If you want to retrieve it using spring, you will have to create 3 lists of name, age and genders as follows.

```<code>    nameList = [x1,x2,x3,...]
    ageList = [y1,y2,y3,...]
    genderList = [z1,z2,z3]
</code>```

You can then write the code as below

```<code>    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate = ...

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("nameList", nameList);
    params.put("ageList", ageList);
    params.put("genderList", genderList);
    String sql = "select * from university where name IN (:nameList) and age IN (:ageList) and gender IN (:genderList)";
    jdbcTemplate.queryForList(sql, params, <yourRowMapper>);
</code>```

Title: Bulk select using Spring

Body:
Is there a way to do a bulk select for below query using Spring alone?

E.g.

select * from university where name='x' and age=y and gender='z'

Where x,y and z come from list such as :

 [[x1, y1, z1],[x2, y2, z2],[x3, y3, z3]..]

Body:
If you want to retrieve it using spring, you will have to create 3 lists of name, age and genders as follows.

    nameList = [x1,x2,x3,...]
    ageList = [y1,y2,y3,...]
    genderList = [z1,z2,z3]

You can then write the code as below

    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate = ...

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("nameList", nameList);
    params.put("ageList", ageList);
    params.put("genderList", genderList);
    String sql = "select * from university where name IN (:nameList) and age IN (:ageList) and gender IN (:genderList)";
    jdbcTemplate.queryForList(sql, params, <yourRowMapper>);


问:
Code Coverage for .NET Core 2.0 projects in Visual Studio 2017
Version: 15.4.1 - Visual Studio Enterprise 2017

I created a simple .NET Core 2.0 library project and added a UnitTest Project to it. When I run Test -> Analyze Code Coverage -> All tests. Code Coverage Results only report the code coverage for the unit test project.

I already configured the project according to Working with Code Coverage. This is my .csproj:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>

    <IsPackable>false</IsPackable>

    <!-- Required in both test/product projects. This is a temporary workaround for https://github.com/Microsoft/vstest/issues/800 -->
    <DebugType>Full</DebugType>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
    <PackageReference Include="MSTest.TestFramework" Version="1.2.0" />

    <!-- Required. Include this reference for coverage -->
    <PackageReference Include="Microsoft.CodeCoverage" Version="1.0.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" />
  </ItemGroup>

</Project>
</code>```

Update:
I added the same code in the solution as .NET 4.6.2 projects and ran Code Coverage again. It covers the class library just as you would expect:

So my Visual Studio is correctly configured to run Code Coverage. At least for .NET 4.6.2. I also tried it in a fresh VS installation and in VSTS.

I created a repo with my sample code. Can anyone else reproduce this?

答:
There is a workaround that I didn't fully understand.

You have to add <DebugType>Full</DebugType> to all the projects that you need to cover. Not the unit test itself.

Body:
Version: 15.4.1 - Visual Studio Enterprise 2017

I created a simple .NET Core 2.0 library project and added a UnitTest Project to it. When I run Test -> Analyze Code Coverage -> All tests. Code Coverage Results only report the code coverage for the unit test project.

I already configured the project according to Working with Code Coverage. This is my .csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>

    <IsPackable>false</IsPackable>

    <DebugType>Full</DebugType>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
    <PackageReference Include="MSTest.TestFramework" Version="1.2.0" />

    <PackageReference Include="Microsoft.CodeCoverage" Version="1.0.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" />
  </ItemGroup>

</Project>

Update:
I added the same code in the solution as .NET 4.6.2 projects and ran Code Coverage again. It covers the class library just as you would expect:

So my Visual Studio is correctly configured to run Code Coverage. At least for .NET 4.6.2. I also tried it in a fresh VS installation and in VSTS.

I created a repo with my sample code. Can anyone else reproduce this?


问:
SQL Server compression
When inserting into a compressed table, will the data be compressed into the log file or will it be compressed when the checkpoint runs and the data is written to the data files? </p>

答:
When row compression is used, data rows have no more FixedVar regular row format, but CD(column descriptor) format.

So when you insert a row into a table that has row compression enabled, the row is formatted (in memory!) in this new CD format, and in this format it will be written to disk.

When you apply page compression, the things are different. Page compression is not applied on every row insertion:

SQL Server stores the data in page-compressed format only when the
  page  is full and compression leads to significant space savings. When
  a page is full, SQL Server performs compression and evaluates if the
  newly compressed page can store either five more rows or 25 percent
  more rows than before the compression. If that is the case, then page
  compression is retained and SQL Server stores the data in
  page-compressed format. Otherwise, the page compression is discarded
  and data is stored in row-compressed format.

Another thing to note:

Neither  transaction log   records for data modifications nor the
  version store in  tempdb  supports page compression. SQL Server needs
  to decompress the page and remove anchor and dictionary records every
  time a row needs to be placed in the version store or written to the
  transaction log.

The last thing to consider:

Page compression consists of three different  stages. First, SQL
  Server performs row compression on the rows.

So as soon as you apply any type of compression, the rows are stored in CD format, and they are in this format in memory (prior to be written to log/data files)

Title: SQL Server compression