问:
CSS/Bootstrap: Align Font-Awesome icons in right-bottom corner of sidebar
I have a problem with aligning icons inside the sidebar. I want to have a few social icons in right-bottom corner of a sidebar.I tried using margins but it looks horrible and ugly.

Here's an example in JSBin (please resize the window to at least 1000px).

html, body, .container-fluid, .row {
  height: 100%;
}

body {
  background-color: #F2F0F1;
}

.sidebar {
  background-color: tomato;
}

@media (min-width: 992px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    z-index: 1000;
    display: block;
    background-color: tomato;
    box-shadow: 0 0 25px rgba(0, 0, 0, 0.5);
  }
}

ul li {
  margin: 0 auto;
  line-height: 50px;
  list-style: none;
  text-align: right;
  margin-right: 20px;
}

ul li a {
  color: rgba(255, 255, 255, 0.5);
  text-decoration: none;
}

a:hover {
  text-decoration: none;
  background-color: rgba(0, 0, 0, 0.4);
  padding: 4px;
  color: tomato;
}

.hi {
  margin-right: 20px;
  text-align: right;
  color: rgba(0, 0, 0, 0.4);
}

.content {
  padding: 2% 4% 2% 4%;
  color: rgba(0, 0, 0, 0.4);
  background-color: #F2F0F1;
}

#fixedbutton {
  position: fixed;
  top: 0px;
  right: 0px;
}

.sidebar-bottom-wrap {
  position: absolute;
  bottom: 60px;
  right: 40px;
  max-width: 200px;
}

.icons-sidebar-unit {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  vertical-align: baseline;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>PRZEMO PORTFOLIO</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <!-- SIDEBAR -->
    <div class="container">
      <div class="row">
        <div class="col-md-3 sidebar"><div class="foto">
          <img src="pic.png" class=" img-responsive img-circle " alt="pic">
        </div>
        <h3 class="hi">Hi! I am <strong>Mike</strong> ,a front-end developer.</h2>

        <!-- MENU -->
        <ul>
          <li>ABOUT</li>
          <li>PROJECTS</li>
          <li>CONTACT</li>
        </ul>

        <!-- footer ICONS -->
        <footer>
          <!--Social icons-->
          <div class="social-icons-sidebar">

              <i class="fa fa-twitter-square"></i>

              <i class="fa fa-facebook-square"></i>

              <i class="fa fa-google-plus-square"></i>

              <i class="fa fa-youtube-square"></i>

          </div>

          <div class="copyright">
      Copyright © 2017. Designed by
      wwwS.
     </div><!--End copyright-->

          <!--
          <i class="fa fa-linkedin A " aria-hidden="true"></i>
          <i class="fa fa-github" aria-hidden="true"></i>
          <i class="fa  fa-envelope-o" aria-hidden="true"></i>
          -->
          </div>
      </footer>

      <!-- MAIN -->
        <div class="col-md-9 col-md-offset-3 content">
          <h2 id="about">ABOUT ME</h2>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea.
          <div class="container-fluid">
            <h2 id="projects">RECENT PROJECTS</h2>
              <div class="row">
                <div class="col-md-9">
                  <div class="col-xs 12 col-sm-6  col-sm-6 col-md-6   ">
                    <img src="1.png" alt="" class="img-responsive img-thumbnail">
                  </div>
                  <div class="col-xs 12 col-sm-6  col-sm-6 col-md-6  ">
                    <img src="2.png" alt="" class="img-responsive img-thumbnail">
                  </div>
                  <div class="col-xs 12 col-sm-6  col-sm-6 col-md-6  ">
                    <img src="3.png" alt="" class="img-responsive img-thumbnail">
                  </div>
                  <div class="col-xs 12 col-sm-6  col-sm-6 col-md-6   ">
                    <img src="4.png" alt="" class="img-responsive img-thumbnail">
                  </div>
                </div>
              </div>
            </div>
            <br>
             SKILLZ:<br>
             HTML 5 - PRO <br>
             CSS 3 - PRO <br>
             JS - NOOB <br>
             JQUERY - NOOB<br>
             SASS - MAD <br>
             GRUNT - GOD
             <hr>
             <h2 id="contact">CONTACT</h2>
             <form class="form-horizontal">
              <fieldset>
                <!-- Form Name -->
                <!-- Text input-->
                <div class="form-group">
                  <label class="col-md-12 control-label" for=""></label>
                  <div class="col-md-12">
                    <input id="" name="" type="text" placeholder="name" class="form-control input-md">
                  </div>
                </div>

                <!-- Text input-->
                <div class="form-group">
                  <label class="col-md-12 control-label" for=""></label>
                  <div class="col-md-12">
                    <input id="" name="" type="text" placeholder="email" class="form-control input-md">
                  </div>
                </div>

                <!-- Textarea -->
                <div class="form-group">
                  <label class="col-md-12 control-label" for=""></label>
                  <div class="col-md-12">
                    <textarea class="form-control" id="" name="">message</textarea>
                  </div>
                </div>

                <!-- Button -->
                <div class="form-group">
                  <label class="col-md-12 control-label" for="singlebutton"></label>
                  <div class="col-md-12">
                    <button id="singlebutton" name="singlebutton" class="btn btn-default">send message</button>
                  </div>
                </div>
              </fieldset>
            </form>

            <img src="qrcode1.png" class="img-responsive center-block" alt="">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod temp eu fuglorem Lorem ipsuat nulla pariatur. Exceeu fugiat it in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui r sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

           Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
          </div>
        </div>
      </div>
    </div>
    </div>
  </body>
</html></code>```

答:
To align your icons to the right, try:

```<code>.icons-sidebar-unit {
    float: right;
}
</code>```

Also, while looking at your code, I noticed you had a height / width set to 30px on your icon units.  If this was to increase the size of the icons themselves, try:

```<code>.icons-sidebar-unit {
    font-size: 30px;
}
</code>```

A lot of people get confused on this one because it seems like icons should be styled like images, but they are actually styled as fonts.

Body:
I have a problem with aligning icons inside the sidebar. I want to have a few social icons in right-bottom corner of a sidebar.I tried using margins but it looks horrible and ugly.

Here's an example in JSBin (please resize the window to at least 1000px).

html, body, .container-fluid, .row {
  height: 100%;
}

body {
  background-color: #F2F0F1;
}

.sidebar {
  background-color: tomato;
}

@media (min-width: 992px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    z-index: 1000;
    display: block;
    background-color: tomato;
    box-shadow: 0 0 25px rgba(0, 0, 0, 0.5);
  }
}

ul li {
  margin: 0 auto;
  line-height: 50px;
  list-style: none;
  text-align: right;
  margin-right: 20px;
}

ul li a {
  color: rgba(255, 255, 255, 0.5);
  text-decoration: none;
}

a:hover {
  text-decoration: none;
  background-color: rgba(0, 0, 0, 0.4);
  padding: 4px;
  color: tomato;
}

.hi {
  margin-right: 20px;
  text-align: right;
  color: rgba(0, 0, 0, 0.4);
}

.content {
  padding: 2% 4% 2% 4%;
  color: rgba(0, 0, 0, 0.4);
  background-color: #F2F0F1;
}

#fixedbutton {
  position: fixed;
  top: 0px;
  right: 0px;
}

.sidebar-bottom-wrap {
  position: absolute;
  bottom: 60px;
  right: 40px;
  max-width: 200px;
}

.icons-sidebar-unit {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  vertical-align: baseline;

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>PRZEMO PORTFOLIO</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

Hi! I am Mike ,a front-end developer.

ABOUT

PROJECTS

CONTACT

      Copyright © 2017. Designed by
      wwwS.

ABOUT ME

          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea.

RECENT PROJECTS

             SKILLZ:

             HTML 5 - PRO

             CSS 3 - PRO

             JS - NOOB

             JQUERY - NOOB

             SASS - MAD

             GRUNT - GOD

CONTACT

             <form class="form-horizontal">
              <fieldset>

                    <input id="" name="" type="text" placeholder="name" class="form-control input-md">

                    <input id="" name="" type="text" placeholder="email" class="form-control input-md">

                    <textarea class="form-control" id="" name="">message</textarea>

                    <button id="singlebutton" name="singlebutton" class="btn btn-default">send message</button>

              </fieldset>
            </form>

            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod temp eu fuglorem Lorem ipsuat nulla pariatur. Exceeu fugiat it in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui r sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

           Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Body:
To align your icons to the right, try:

.icons-sidebar-unit {
    float: right;
}

Also, while looking at your code, I noticed you had a height / width set to 30px on your icon units.  If this was to increase the size of the icons themselves, try:

.icons-sidebar-unit {
    font-size: 30px;
}

A lot of people get confused on this one because it seems like icons should be styled like images, but they are actually styled as fonts.


来源: stackexchange

问:
Merge dataframe on closest date
I have some data for some experiments indexed by a subject ID and a date.  I'd like to join the data together, but the subjects may undergo experiments on different days.  Here is an example of what I mean.  Shown below are the results from two different experiments

```<code>SubjectID  Date        ScoreA
1          2016-09-20      10
1          2016-09-21      12
1          2016-12-01      11

SubjectID  Date        ScoreB
1          2016-09-20      1
1          2016-09-24      5
1          2016-11-28      3
1          2016-12-11      9
</code>```

I would like to join the rows to the closest available date.  So ideally, my desired output is

```<code>SubjectID   Date1         Date2        ScoreA ScoreB
1            2016-09-20    2016-09-20    10      1
1            2016-09-21    2016-09-24    12      5
1            2016-12-01    2016-11-28    11      3
</code>```

Note "closest date" is closest in absolute value.  How can I achieve something like this?

答:
I don't know if there is a way to do what you want with default pandas functionality, but it's straightforward to do it with a custom aggregation function:

```<code>def pick_closest(g):
    closest_date_loc = (g.Date1 - g.Date2).abs().argmin()
    return g.loc[closest_date_loc, ['ScoreA','Date2','ScoreB']]

merged = df1.merge(df2, on='SubjectID', suffixes=['1', '2'])
df3  = merged.groupby(['SubjectID','Date1'], as_index=False).apply(pick_closest).reset_index()
df3

   SubjectID      Date1  ScoreA      Date2  ScoreB
0          1 2016-09-20      10 2016-09-20       1
1          1 2016-09-21      12 2016-09-20       1
2          1 2016-12-01      11 2016-11-28       3
</code>```

In this code snippet, the two frames are initially merged on SubjectID, generating all possible combinations of Date1 and Date2. Then the pick_closest function selects the row with the smallest date difference between Date1 and Date2 for each SubjectID/Date1 group.

ContentLicense: CC BY-SA 3.0

Title: Merge dataframe on closest date

Body:
I have some data for some experiments indexed by a subject ID and a date.  I'd like to join the data together, but the subjects may undergo experiments on different days.  Here is an example of what I mean.  Shown below are the results from two different experiments

SubjectID  Date        ScoreA
1          2016-09-20      10
1          2016-09-21      12
1          2016-12-01      11

SubjectID  Date        ScoreB
1          2016-09-20      1
1          2016-09-24      5
1          2016-11-28      3
1          2016-12-11      9

I would like to join the rows to the closest available date.  So ideally, my desired output is

SubjectID   Date1         Date2        ScoreA ScoreB
1            2016-09-20    2016-09-20    10      1
1            2016-09-21    2016-09-24    12      5
1            2016-12-01    2016-11-28    11      3

Note "closest date" is closest in absolute value.  How can I achieve something like this?

Body:
I don't know if there is a way to do what you want with default pandas functionality, but it's straightforward to do it with a custom aggregation function:

def pick_closest(g):
    closest_date_loc = (g.Date1 - g.Date2).abs().argmin()
    return g.loc[closest_date_loc, ['ScoreA','Date2','ScoreB']]

merged = df1.merge(df2, on='SubjectID', suffixes=['1', '2'])
df3  = merged.groupby(['SubjectID','Date1'], as_index=False).apply(pick_closest).reset_index()
df3

   SubjectID      Date1  ScoreA      Date2  ScoreB
0          1 2016-09-20      10 2016-09-20       1
1          1 2016-09-21      12 2016-09-20       1
2          1 2016-12-01      11 2016-11-28       3

In this code snippet, the two frames are initially merged on SubjectID, generating all possible combinations of Date1 and Date2. Then the pick_closest function selects the row with the smallest date difference between Date1 and Date2 for each SubjectID/Date1 group.


问:
Configurate RouterLink in a botton
I'm practicing Angular 2, and configured a button with a password entered and a correct one to redirect to a second page. I configured the routing but I do not know how to do it so that it is validated and then redirected.

What I currently have configured in the following but I can not click the button and I would like to redirect to the second page.

答:
Why are you having both routerLink and click on the same button. you can instead move the routerLink to the code as

```<code>validarpass(pass:number) {
    .....
    this.router.navigate(['/component-one']);
}
</code>```

Inject the Router to your constructor as below

```<code>constructor(private router:Router){
...}
</code>```

Title: Configurate RouterLink in a botton

Body:
Why are you having both routerLink and click on the same button. you can instead move the routerLink to the code as

validarpass(pass:number) {
    .....
    this.router.navigate(['/component-one']);
}

Inject the Router to your constructor as below

constructor(private router:Router){
...}


问:
How implement Chart.js in Angular 2?
I am using the latest version of Angular 2, V4.0.0 and I want to use graphs from the Chart.js library in my project without many complications.

How can I implement Chart.js in my angular project that does not give me problems in the final production?

答:
You can implement Chart.js in a simple way with the following instructions:

1. Create a new project with angular-cli, skip if you already have one created

```<code>ng new example-chartjs
</code>```

2. Install Chart.js in your project

```<code>npm install chart.js --save
</code>```

3. Import Chart into its component

```<code>import Chart from 'chart.js';
</code>```

4. Use Chart in your view and component

In your view:

```<code><canvas id="myChart" width="400" height="400"></canvas>
</code>```

In your component:

```<code>ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}
</code>```

The component should look similar to the following

```<code>import { Component, OnInit } from '@angular/core';
import Chart from 'chart.js';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}
</code>```

Another alternative to use is to include the library from the file ".angular-cli.json"

1. Include in the scripts the library

```<code>"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]
</code>```

2. Declare a variable of type "any" in the controller

```<code>declare var Chart:any;
</code>```

3. Use Chart in your view and component

In your view:

```<code><canvas id="myChart" width="400" height="400"></canvas>
</code>```

In your component:

```<code>ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}
</code>```

The component should look similar to the following

```<code>import { Component, OnInit } from '@angular/core';

declare var Chart:any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}
</code>```

Title: How implement Chart.js in Angular 2?

Body:
You can implement Chart.js in a simple way with the following instructions:

1. Create a new project with angular-cli, skip if you already have one created

ng new example-chartjs

2. Install Chart.js in your project

npm install chart.js --save

3. Import Chart into its component

import Chart from 'chart.js';

4. Use Chart in your view and component

In your view:

<canvas id="myChart" width="400" height="400"></canvas>

In your component:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

The component should look similar to the following

import { Component, OnInit } from '@angular/core';
import Chart from 'chart.js';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}

Another alternative to use is to include the library from the file ".angular-cli.json"

1. Include in the scripts the library

"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]

2. Declare a variable of type "any" in the controller

declare var Chart:any;

3. Use Chart in your view and component

In your view:

<canvas id="myChart" width="400" height="400"></canvas>

In your component:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

The component should look similar to the following

import { Component, OnInit } from '@angular/core';

declare var Chart:any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}


答:
The easiest way is probably to absolutely position them .social-icons-sidebar { position: absolute; bottom: 0; right: 0; } https://jsbin.com/petixugodu/1/edit?html,css,output

You could also use flexbox. Make the sidebar a column flex container, set the footer to flex-grow: 1 so that it extends to the bottom of the sidebar, put the social icons at the bottom by using margin-top: auto and order: 1 then align them to the right with text-align: right or align-self: flex-end https://jsbin.com/tukiqonase/edit?html,css,output

Title: CSS/Bootstrap: Align Font-Awesome icons in right-bottom corner of sidebar


问:
Remove whitespace after first line using SED
I am trying to edit a file with sed, my goal is to remove the white-space between the numbers but preserve it after the first word (eg Water 1983 02 13, - 1984 02 1, turns into Water,19840213,1984021)
Here is my current command:

```<code>awk '{print $10,$4,$2,$3,$5,$8,$6,$7}' czodiac | sed 's/Feb/02/g;s/Jan/02/g;s/–//g;s/ //g;s/,$//g'
</code>```

output so far: Water19830213,1984021

Body:
I am trying to edit a file with sed, my goal is to remove the white-space between the numbers but preserve it after the first word (eg Water 1983 02 13, - 1984 02 1, turns into Water,19840213,1984021)
Here is my current command:

awk '{print $10,$4,$2,$3,$5,$8,$6,$7}' czodiac | sed 's/Feb/02/g;s/Jan/02/g;s/–//g;s/ //g;s/,$//g'

output so far: Water19830213,1984021

Body: sed 'h; s/[^ ]*//; s/ //g; x; s/ .*/ /; G'


问:
jQuery: How to get first value and last value on input text
I have no idea how to get last value on input text. I already get the first value, when input type is empty did not get value. Here's my code:

HTML

```<code><input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
</code>```

JS/jQuery

```<code>$(document).ready(function(){
    var $set = $('.date');
    var len = $set.length;
    $set.each(function(index, element) {
        if (index === 0) {
            alert (this.value);
        }
    });
});
</code>```

答:
You can reverse your loop and start from the last.</p>

```<code>var $set = $('.date');
var len = $set.length;
var firstVal = $($set[0]).val();
var lastVal = null;
for (var i = len - 1; i > 0; i--){
  if ($($set[i]).val()){
    lastVal = $($set[i]).val();
    break;
  }
}
</code>```

Body:
I have no idea how to get last value on input text. I already get the first value, when input type is empty did not get value. Here's my code:

HTML

<input type="text" name="date[]" class="date" id="date" value="6/17">

<input type="text" name="date[]" class="date" id="date" value="6/18">

<input type="text" name="date[]" class="date" id="date" value="6/18">

<input type="text" name="date[]" class="date" id="date" value="6/19">

<input type="text" name="date[]" class="date" id="date" value="6/19">

<input type="text" name="date[]" class="date" id="date" value="">

<input type="text" name="date[]" class="date" id="date" value="">

JS/jQuery

$(document).ready(function(){
    var $set = $('.date');
    var len = $set.length;
    $set.each(function(index, element) {
        if (index === 0) {
            alert (this.value);
        }
    });
});

Body:
You can reverse your loop and start from the last.

var $set = $('.date');
var len = $set.length;
var firstVal = $($set[0]).val();
var lastVal = null;
for (var i = len - 1; i > 0; i--){
  if ($($set[i]).val()){
    lastVal = $($set[i]).val();
    break;
  }
}


问:
Kotlin Coroutines the right way in Android
I'm trying to update a list inside the adapter using async, I can see there is too much boilerplate.

Is it the right way to use Kotlin Coroutines?

can this be optimized more?

```<code>fun loadListOfMediaInAsync() = async(CommonPool) {
        try {
            //Long running task
            adapter.listOfMediaItems.addAll(resources.getAllTracks())
            runOnUiThread {
                adapter.notifyDataSetChanged()
                progress.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {progress.dismiss()}
        } catch (o: OutOfMemoryError) {
            o.printStackTrace()
            runOnUiThread {progress.dismiss()}
        }
    }
</code>```

答:
After struggling with this question for days, I think the most simple and clear async-await pattern for Android activities using Kotlin is:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    //...
    loadDataAsync(); //"Fire-and-forget"
}

fun loadDataAsync() = async(UI) {
    try {
        //Turn on busy indicator.
        val job = async(CommonPool) {
           //We're on a background thread here.
           //Execute blocking calls, such as retrofit call.execute().body() + caching.
        }
        job.await();
        //We're back on the main thread here.
        //Update UI controls such as RecyclerView adapter data.
    }
    catch (e: Exception) {
    }
    finally {
        //Turn off busy indicator.
    }
}
</code>```

The only Gradle dependencies for coroutines are: kotlin-stdlib-jre7, kotlinx-coroutines-android.

Note: Use job.await() instead of job.join() because await() rethrows exceptions, but join() does not. If you use join() you will need to check job.isCompletedExceptionally after the job completes.

To start concurrent retrofit calls, you can do this:

```<code>val jobA = async(CommonPool) { /* Blocking call A */ };
val jobB = async(CommonPool) { /* Blocking call B */ };
jobA.await();
jobB.await();
</code>```

Or:

```<code>val jobs = arrayListOf<Deferred<Unit>>();
jobs += async(CommonPool) { /* Blocking call A */ };
jobs += async(CommonPool) { /* Blocking call B */ };
jobs.forEach { it.await(); };
</code>```

Body:
I'm trying to update a list inside the adapter using async, I can see there is too much boilerplate.

Is it the right way to use Kotlin Coroutines?

can this be optimized more?

fun loadListOfMediaInAsync() = async(CommonPool) {
        try {
            //Long running task
            adapter.listOfMediaItems.addAll(resources.getAllTracks())
            runOnUiThread {
                adapter.notifyDataSetChanged()
                progress.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {progress.dismiss()}
        } catch (o: OutOfMemoryError) {
            o.printStackTrace()
            runOnUiThread {progress.dismiss()}
        }
    }

Body:
After struggling with this question for days, I think the most simple and clear async-await pattern for Android activities using Kotlin is:

override fun onCreate(savedInstanceState: Bundle?) {
    //...
    loadDataAsync(); //"Fire-and-forget"
}

fun loadDataAsync() = async(UI) {
    try {
        //Turn on busy indicator.
        val job = async(CommonPool) {
           //We're on a background thread here.
           //Execute blocking calls, such as retrofit call.execute().body() + caching.
        }
        job.await();
        //We're back on the main thread here.
        //Update UI controls such as RecyclerView adapter data.
    }
    catch (e: Exception) {
    }
    finally {
        //Turn off busy indicator.
    }
}

The only Gradle dependencies for coroutines are: kotlin-stdlib-jre7, kotlinx-coroutines-android.

Note: Use job.await() instead of job.join() because await() rethrows exceptions, but join() does not. If you use join() you will need to check job.isCompletedExceptionally after the job completes.

To start concurrent retrofit calls, you can do this:

val jobA = async(CommonPool) { /* Blocking call A */ };
val jobB = async(CommonPool) { /* Blocking call B */ };
jobA.await();
jobB.await();

Or:

val jobs = arrayListOf<Deferred<Unit>>();
jobs += async(CommonPool) { /* Blocking call A */ };
jobs += async(CommonPool) { /* Blocking call B */ };
jobs.forEach { it.await(); };


问:
MYSQL Using a replace function to replace a part of a statement with a variable
I'm trying to figure out how to change DueDays by increasing 15 days for terms whose current DueDays is larger than 30 (I figured out that part). Then I need to change the details value to the same value as the Duedays is changed. For example, if DueDays of a term is changed from 30 to 45, then 'Net due 30 days' should change to 'Net due 45 days'.

```<code>ID  Details                DueDays
1   Net due 10 days          10
2   Net due 20 days          20
3   Net due 30 days          30
4   Net due 60 days          60
5   Net due 90 days          90
</code>```

So far this is what I came up with:

```<code>Update Terms
SET DueDays = DueDays + 15 AND SET Replace ( Details, '' ,
WHERE DueDays > 30;
</code>```

Thank you in advance

答:
Very strange requirement, storing the string along with the data.  But here is one method:</p>

```<code>UPDATE Terms
    SET DueDays = DueDays + 15,
        Details = REPLACE('Net due XX days', 'XX', DueDays + 15)
    WHERE DueDays > 90;
</code>```

Body:
I'm trying to figure out how to change DueDays by increasing 15 days for terms whose current DueDays is larger than 30 (I figured out that part). Then I need to change the details value to the same value as the Duedays is changed. For example, if DueDays of a term is changed from 30 to 45, then 'Net due 30 days' should change to 'Net due 45 days'.

ID  Details                DueDays
1   Net due 10 days          10
2   Net due 20 days          20
3   Net due 30 days          30
4   Net due 60 days          60
5   Net due 90 days          90

So far this is what I came up with:

Update Terms
SET DueDays = DueDays + 15 AND SET Replace ( Details, '' ,
WHERE DueDays > 30;

Thank you in advance

Body:
Very strange requirement, storing the string along with the data.  But here is one method:

UPDATE Terms
    SET DueDays = DueDays + 15,
        Details = REPLACE('Net due XX days', 'XX', DueDays + 15)
    WHERE DueDays > 90;


问:
Reduce Calls to Bing Translator Api
I have text in 5 Languages: English, German, Spanish, Italian and French. I have to translate text from other languages to english. The Language auto-detect function detects the language, but it costs as 1 call to the translator. Since i'm using the free tier, this isn't feasible. Is there any workaround?</p>

答: If you do not specify 'from' in your Translate request, Detect will be run automatically before the translation starts.</p>

Title: Reduce Calls to Bing Translator Api


问:
C# serialize private class member
```<code>class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

```<code>class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

OR (continue of fact #3) an attribute that goes on the class which would look like:

```<code>[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Now, what can I do to achieve it?

答: What serializer ate you currently using? Almost all should work with that. But public fields *is*a bad idea. XmlSerializer and JavaScriptSerializer will ignore private members. DataContractSerializer and protobuf-net can deal with private members. BinaryFormatter handles fields (public or private), but is not a good idea IMO for numerous reasons.

ContentLicense: CC BY-SA 2.5

Title: C# serialize private class member

Body:
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}

OR (continue of fact #3) an attribute that goes on the class which would look like:

[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Now, what can I do to achieve it?


问:
XML Parsing - Erlang
I want to parse XML strings to erlang list and then to JSON.

Example Input :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!--some message here-->
<start>
   <data>
      <number id="333">test message</number>
      <data>current date</data>
   </data>
   <mass>
      <client>35</client>
      <address>lattitude</address>
      <code>3454343</code>
      <foo tipo="casa">Some text message 2</foo>
      <product>TEST</product>
   </mass>
</start>
</code>```

Output should be:

```<code>{
  "start": {
    "data": {
      "number": {
        "@id": "333",
        "#text": "test message"
      },
      "data": "current date"
    },
    "mass": {
      "client": "35",
      "address": "lattitude",
      "code": "3454343",
      "foo": {
        "@tipo": "casa",
        "#text": "Some text message 2"
      },
      "product": "TEST"
    }
  }
}
</code>```

I am trying to use erlsom:simple_form(Xml).

and getting :

```<code>{ok,{"start",[],
     [{"data",[],
       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
      {"mass",[],
       [{"client",[],["35"]},
        {"address",[],["lattitude"]},
        {"code",[],["3454343"]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},
        {"product",[],["TEST"]}]}]},
    []}
</code>```

Now I want to delete these empty attrs. Is there any simple way to do this?
thanks in advance.

UPDATE: Make it work w/ solution from
Erlang xml to tuples and lists

BUT Getting

```<code>{"start",
 [{"data",
   [{"number","test message"},{"data","current date"}]},
  {"mass",
   [{"client","35"},
    {"address","lattitude"},
    {"code","3454343"},
    {"foo","Some text message 2"},
    {"product","TEST"}]}]}
</code>```

there is no [{"id","333"}] & [{"tipo","casa"}] lists :(

答:
i suggest to use jiffy for JSON and exml for XML.
jiffy and exml have native code which means they are so fast.

Clone and compile them.

before compiling them, you should install g++ and libexpat-dev

Example:

```<code>-module(test).
-export([convert/1]).
-include("exml/include/exml.hrl"). %% In my test

convert(XML) when erlang:is_binary(XML) ->
    {ok, XMLEl} = exml:parse(XML),
    jiffy:encode({[convert2(XMLEl)]}).

convert2(#xmlel{name = Name
              ,attrs = []
              ,children = [{xmlcdata, Data}]}) ->
    {Name, Data};
convert2(#xmlel{name = Name
              ,attrs = Attrs
              ,children = Children}) ->
    {Name,  {convert_attrs(Attrs) ++ convert_children(Children)}}.

convert_attrs(Attrs) ->
    convert_attrs(Attrs,[]).

convert_attrs([Attr|Attrs1], Attrs2) ->
    convert_attrs(Attrs1, [convert_attr(Attr)|Attrs2]);
convert_attrs([], Attrs2) ->
    lists:reverse(Attrs2).

convert_attr({Attr, Value}) ->
    {<<$@, Attr/binary>>, Value}.

convert_children(Children) ->
    convert_children(Children, []).

convert_children([Child|Children1], Children2) ->
    convert_children(Children1, [convert_child(Child)|Children2]);
convert_children([], Children2) ->
    lists:reverse(Children2).

convert_child({xmlcdata, Data}) ->
    {<<"#text">>, Data};
convert_child(#xmlel{}=XMLEl) ->
    convert2(XMLEl).
</code>```

In the shell:

```<code>p@jahanbakhsh ~/Projects/test $ ls
exml                      jiffy                   test.erl

p@jahanbakhsh ~/Projects/test $ erl -pa jiffy/ebin exml/ebin
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> c(test).
{ok,test}
2> XML = <<"<start><data><number id=\"333\">test message</number><data>current date</data></data><mass><client>35</client><address>lattitude</address><code>3454343</code><foo tipo=\"casa\">Some text message 2</foo><product>TEST</product></mass></start>">>.
<<"<start><data><number id=\"333\">test message</number><data>current date</data></data><mass><client>35</client><address"...>>

3> test:convert(XML).
<<"{\"start\":{\"data\":{\"number\":{\"@id\":\"333\",\"#text\":\"test message\"},\"data\":\"current date\"},\"mass\":{\"client\":\"35\",\"addres"...>>

4> io:format("~s~n", [test:convert(XML)]).
{"start":{"data":{"number":{"@id":"333","#text":"test message"},"data":"current date"},"mass":{"client":"35","address":"lattitude","code":"3454343","foo":{"@tipo":"casa","#text":"Some text message 2"},"product":"TEST"}}}
ok
5>
</code>```

Title: XML Parsing - Erlang

Body:
I want to parse XML strings to erlang list and then to JSON.

Example Input :

<?xml version="1.0" encoding="UTF-8"?>

<start>
   <data>
      <number id="333">test message</number>
      <data>current date</data>
   </data>
   <mass>
      <client>35</client>
      <address>lattitude</address>
      3454343
      <foo tipo="casa">Some text message 2</foo>
      <product>TEST</product>
   </mass>
</start>

Output should be:

{
  "start": {
    "data": {
      "number": {
        "@id": "333",
        "#text": "test message"
      },
      "data": "current date"
    },
    "mass": {
      "client": "35",
      "address": "lattitude",
      "code": "3454343",
      "foo": {
        "@tipo": "casa",
        "#text": "Some text message 2"
      },
      "product": "TEST"
    }
  }
}

I am trying to use erlsom:simple_form(Xml).

and getting :

{ok,{"start",[],
     [{"data",[],
       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
      {"mass",[],
       [{"client",[],["35"]},
        {"address",[],["lattitude"]},
        {"code",[],["3454343"]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},
        {"product",[],["TEST"]}]}]},
    []}

Now I want to delete these empty attrs. Is there any simple way to do this?
thanks in advance.

UPDATE: Make it work w/ solution from
Erlang xml to tuples and lists

BUT Getting

{"start",
 [{"data",
   [{"number","test message"},{"data","current date"}]},
  {"mass",
   [{"client","35"},
    {"address","lattitude"},
    {"code","3454343"},
    {"foo","Some text message 2"},
    {"product","TEST"}]}]}

there is no [{"id","333"}] & [{"tipo","casa"}] lists :(

Body:
i suggest to use jiffy for JSON and exml for XML.
jiffy and exml have native code which means they are so fast.

Clone and compile them.

before compiling them, you should install g++ and libexpat-dev

Example:

-module(test).
-export([convert/1]).
-include("exml/include/exml.hrl"). %% In my test

convert(XML) when erlang:is_binary(XML) ->
    {ok, XMLEl} = exml:parse(XML),
    jiffy:encode({[convert2(XMLEl)]}).

convert2(#xmlel{name = Name
              ,attrs = []
              ,children = [{xmlcdata, Data}]}) ->
    {Name, Data};
convert2(#xmlel{name = Name
              ,attrs = Attrs
              ,children = Children}) ->
    {Name,  {convert_attrs(Attrs) ++ convert_children(Children)}}.

convert_attrs(Attrs) ->
    convert_attrs(Attrs,[]).

convert_attrs([Attr|Attrs1], Attrs2) ->
    convert_attrs(Attrs1, [convert_attr(Attr)|Attrs2]);
convert_attrs([], Attrs2) ->
    lists:reverse(Attrs2).

convert_attr({Attr, Value}) ->
    {<<$@, Attr/binary>>, Value}.

convert_children(Children) ->
    convert_children(Children, []).

convert_children([Child|Children1], Children2) ->
    convert_children(Children1, [convert_child(Child)|Children2]);
convert_children([], Children2) ->
    lists:reverse(Children2).

convert_child({xmlcdata, Data}) ->
    {<<"#text">>, Data};
convert_child(#xmlel{}=XMLEl) ->
    convert2(XMLEl).

In the shell:

p@jahanbakhsh ~/Projects/test $ ls
exml                      jiffy                   test.erl

p@jahanbakhsh ~/Projects/test $ erl -pa jiffy/ebin exml/ebin
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> c(test).
{ok,test}
2> XML = <<"<start><data><number id=\"333\">test message</number><data>current date</data></data><mass><client>35</client><address>lattitude</address><code>3454343</code><foo tipo=\"casa\">Some text message 2</foo><product>TEST</product></mass></start>">>.
<<"<start><data><number id=\"333\">test message</number><data>current date</data></data><mass><client>35</client><address"...>>

3> test:convert(XML).
<<"{\"start\":{\"data\":{\"number\":{\"@id\":\"333\",\"#text\":\"test message\"},\"data\":\"current date\"},\"mass\":{\"client\":\"35\",\"addres"...>>

4> io:format("~s~n", [test:convert(XML)]).
{"start":{"data":{"number":{"@id":"333","#text":"test message"},"data":"current date"},"mass":{"client":"35","address":"lattitude","code":"3454343","foo":{"@tipo":"casa","#text":"Some text message 2"},"product":"TEST"}}}
ok
5>


问:
Error in my code: The constructor Scanner() is undefined. Syntax error, insert "( )" to complete Expression
I'm running Eclipse.

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

public class Input {

    public static void main(String[] args) {

        Scanner input = new Scanner; // Creates scanner object

        System.out.println("Enter a line of text: "); // Outputs the prompt

        String Line = input.nextLine(); //wait for user to enter line of text

        System.out.println("You entered: " + Line); //Tells user what they entered
    }
}
</code>```

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

      The constructor Scanner() is undefined

      Syntax error, insert "( )" to complete Expression

at Input.main(Input.java:7)

答:
You can't call a constructor without (), and you need a thing to read from. Change

```<code>Scanner input = new Scanner;
</code>```

to

```<code>Scanner input = new Scanner(System.in);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm running Eclipse.

import java.util.Scanner;

public class Input {

    public static void main(String[] args) {

        Scanner input = new Scanner; // Creates scanner object

        System.out.println("Enter a line of text: "); // Outputs the prompt

        String Line = input.nextLine(); //wait for user to enter line of text

        System.out.println("You entered: " + Line); //Tells user what they entered
    }
}

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

      The constructor Scanner() is undefined

      Syntax error, insert "( )" to complete Expression

at Input.main(Input.java:7)

Body:
You can't call a constructor without (), and you need a thing to read from. Change

Scanner input = new Scanner;

to

Scanner input = new Scanner(System.in);


问:
PepJs/pointer-event polyfill not working on iOs safari
I'm trying to setup pointer events cross-browser. Now, most browser support it already, but safari on iOs doesn't. So I'm trying to polyfill this with pep-js without much success. Here is my test-code:

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.pep/0.4.0/jquery.pep.min.js"></script>
  <meta charset="utf-8">

    <style>
     .pixel {position: absolute;background: black;width: 2px;height:2px;}
     #canvas {margin: 20px;background: white;border: 1px solid black;height: 200px;}
    </style>
</head>

<body>
    <div id="canvas" touch-action="none"></div>
    <script>
      function draw(where) {
          var div = document.createElement('div');
          div.classList.add('pixel');
          div.setAttribute('style', 'left:'+where.pageX + 'px;top:'+where.pageY+'px');
          document.querySelector('#canvas').appendChild(div);
      }

      document.querySelector('#canvas')
         .addEventListener('pointermove', function(event) {
             draw(event);
         });
    </script>
</body>
</html>
</code>```

or an other one I've created on jsffidle

On the desktop it works like a charm, but safari on iOS it doesn't. Any suggestion what I'm doing wrong?

答:
It looks like you are using the wrong library.

You use jquery.pep.js but probably want PEP. It's an unfortunate clash in naming.

Body:
I'm trying to setup pointer events cross-browser. Now, most browser support it already, but safari on iOs doesn't. So I'm trying to polyfill this with pep-js without much success. Here is my test-code:

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width">

  <meta charset="utf-8">

or an other one I've created on jsffidle

On the desktop it works like a charm, but safari on iOS it doesn't. Any suggestion what I'm doing wrong?


问:
Strange pass by reference issue in a simple program
I am implementing Sudoku solver and using 2D vector and passing it around using reference but still, when at the end of the main I try to print the 2D vector it prints the initial 2D vector.

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

using namespace std;

void display(vector<vector<int>>& _board) {
    for (auto row: _board) {
        for (auto col: row) {
            cout << col << "  ";
            }
        cout << endl;
        }
}

bool isBoardSolved(vector<vector<int>>& _board) {
    for (auto row: _board) {
        for (auto col: row) { //style[1] of 2D vector traversal
            if (col == 0) {
                return false;
            }
        }
    }
    return true;
}

map<int, int> findOptions(vector<vector<int>>& _board, int _row, int _col) {
    map<int, int> options;
    int x, y;
    for (int digit = 1; digit < 10; ++digit) {
        options[digit] = 0; //state 0 means available as options
    }
    //col in a row
    for (y = 0; y < 9; ++y) {
        if (_board[_row][y] != 0) {
            options[_board[_row][y]] = 1;
        }
    }
    //row in a col
    for (x = 0; x < 9; ++x) {
        if (_board[x][_col] != 0) {
            options[_board[x][_col]] = 1;
        }
    }
    //in a rectangular 3*3 matrix
    if (_row <= 2)
        x = 0;
    else if (_row > 2 && _row <= 5)
        x = 3;
    else
        x = 6;
    if (_col <= 2)
        y = 0;
    else if (_col > 2 && _col <= 5)
        y = 3;
    else
        y = 6;

    for (int i = x; i < x + 3; ++i) {
        for (int j = y; j < y + 3; ++j) {
            if (_board[i][j] != 0) {
                options[_board[i][j]] = 1;
            }
        }
    }
    return options;

}

void solveBoard(vector<vector<int>>& _board) {
    int row = 0;
    int col = 0;
    bool flag = false;
    if (isBoardSolved(_board)) {
//        cout << "Solved Sudoku Board" << endl;
//        display(_board); //gives correct answer when I print it here
        return;
    }
    else {
        for (int x = 0; x < 9; ++x) { //not using the style[1] because I need explicit index of empty slot
            flag = false;
            for (int y = 0; y < 9; ++y) {
                if (_board[x][y] == 0) {
                    row = x;
                    col = y;
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
    }

    auto options = findOptions(_board, row, col);
    for (auto digit: options) {
        if (digit.second != 1) {
            _board[row][col] = digit.first;
            solveBoard(_board);
        }
    }
    _board[row][col] = 0;
}

int main(int argc, char *argv[]) {
    vector<vector<int>> board(9, vector<int>(9, 0));

    board[0][3] = 3;
    board[0][6] = 2;
    board[2][1] = 7;
    board[2][2] = 8;
    board[2][3] = 0;
    board[2][4] = 6;
    board[2][6] = 3;
    board[2][7] = 4;
    board[3][1] = 4;
    board[3][2] = 2;
    board[3][3] = 5;
    board[3][4] = 1;
    board[4][0] = 1;
    board[4][1] = 0;
    board[4][2] = 6;
    board[4][6] = 4;
    board[4][7] = 0;
    board[4][8] = 9;
    board[5][4] = 8;
    board[5][5] = 6;
    board[5][6] = 1;
    board[5][7] = 5;
    board[6][1] = 3;
    board[6][2] = 5;
    board[6][4] = 9;
    board[6][6] = 7;
    board[6][7] = 6;
    board[7][3] = 7;
    board[8][2] = 9;
    board[8][5] = 5;

    cout << "Given Sudoku Board" << endl;
    display(board);
    solveBoard(board);
    cout << "Solved Sudoku Board" << endl;
    display(board); //gives unchanged answer when i print it here
}
</code>```

What is wrong I am doing and how to correct it.

When I try this :

```<code>void change(vector<vector<int>>& _b){
    _b[0][1] = 99;
}
int main(){

    vector<vector<int>> b(1, vector<int>(9, 1));
    cout<<b[0][1]<<endl;
    change(b);
    cout<<b[0][1];
    return 0;
}
</code>```

This displays the changed value for 2D vecor b.

答:
You are not exiting the recursion call stack correctly in solveBoard(). Note the new bool function signature for solveBoard() being returned to signal up the invocation chain to exit early.  Also note the three different return points now depending on where you are.</p>

```<code>bool solveBoard(vector<vector<int>>& _board) {
    int row = 0;
    int col = 0;
    bool flag;
    if (isBoardSolved(_board)) {
//      cout << "Solved Sudoku Board" << endl;
//      display(_board); //gives correct answer when I print it here
        return true;
    }
    else {
        for (int x = 0; x < 9; ++x) { //not using the style[1] because I need explicit index of empty slot
            flag = false;
            for (int y = 0; y < 9; ++y) {
                if (_board[x][y] == 0) {
                    row = x;
                    col = y;
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
    }

    auto options = findOptions(_board, row, col);
    for (auto digit : options) {
        if (digit.second != 1) {
            _board[row][col] = digit.first;
            if (solveBoard(_board))
                return true;
        }
    }
    _board[row][col] = 0;
    return false;
}
</code>```

Body:
I am implementing Sudoku solver and using 2D vector and passing it around using reference but still, when at the end of the main I try to print the 2D vector it prints the initial 2D vector.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void display(vector<vector<int>>& _board) {
    for (auto row: _board) {
        for (auto col: row) {
            cout << col << "  ";
            }
        cout << endl;
        }
}

bool isBoardSolved(vector<vector<int>>& _board) {
    for (auto row: _board) {
        for (auto col: row) { //style[1] of 2D vector traversal
            if (col == 0) {
                return false;
            }
        }
    }
    return true;
}

map<int, int> findOptions(vector<vector<int>>& _board, int _row, int _col) {
    map<int, int> options;
    int x, y;
    for (int digit = 1; digit < 10; ++digit) {
        options[digit] = 0; //state 0 means available as options
    }
    //col in a row
    for (y = 0; y < 9; ++y) {
        if (_board[_row][y] != 0) {
            options[_board[_row][y]] = 1;
        }
    }
    //row in a col
    for (x = 0; x < 9; ++x) {
        if (_board[x][_col] != 0) {
            options[_board[x][_col]] = 1;
        }
    }
    //in a rectangular 3*3 matrix
    if (_row <= 2)
        x = 0;
    else if (_row > 2 && _row <= 5)
        x = 3;
    else
        x = 6;
    if (_col <= 2)
        y = 0;
    else if (_col > 2 && _col <= 5)
        y = 3;
    else
        y = 6;

    for (int i = x; i < x + 3; ++i) {
        for (int j = y; j < y + 3; ++j) {
            if (_board[i][j] != 0) {
                options[_board[i][j]] = 1;
            }
        }
    }
    return options;

}

void solveBoard(vector<vector<int>>& _board) {
    int row = 0;
    int col = 0;
    bool flag = false;
    if (isBoardSolved(_board)) {
//        cout << "Solved Sudoku Board" << endl;
//        display(_board); //gives correct answer when I print it here
        return;
    }
    else {
        for (int x = 0; x < 9; ++x) { //not using the style[1] because I need explicit index of empty slot
            flag = false;
            for (int y = 0; y < 9; ++y) {
                if (_board[x][y] == 0) {
                    row = x;
                    col = y;
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
    }

    auto options = findOptions(_board, row, col);
    for (auto digit: options) {
        if (digit.second != 1) {
            _board[row][col] = digit.first;
            solveBoard(_board);
        }
    }
    _board[row][col] = 0;
}

int main(int argc, char *argv[]) {
    vector<vector<int>> board(9, vector<int>(9, 0));

    board[0][3] = 3;
    board[0][6] = 2;
    board[2][1] = 7;
    board[2][2] = 8;
    board[2][3] = 0;
    board[2][4] = 6;
    board[2][6] = 3;
    board[2][7] = 4;
    board[3][1] = 4;
    board[3][2] = 2;
    board[3][3] = 5;
    board[3][4] = 1;
    board[4][0] = 1;
    board[4][1] = 0;
    board[4][2] = 6;
    board[4][6] = 4;
    board[4][7] = 0;
    board[4][8] = 9;
    board[5][4] = 8;
    board[5][5] = 6;
    board[5][6] = 1;
    board[5][7] = 5;
    board[6][1] = 3;
    board[6][2] = 5;
    board[6][4] = 9;
    board[6][6] = 7;
    board[6][7] = 6;
    board[7][3] = 7;
    board[8][2] = 9;
    board[8][5] = 5;

    cout << "Given Sudoku Board" << endl;
    display(board);
    solveBoard(board);
    cout << "Solved Sudoku Board" << endl;
    display(board); //gives unchanged answer when i print it here
}

What is wrong I am doing and how to correct it.

When I try this :

void change(vector<vector<int>>& _b){
    _b[0][1] = 99;
}
int main(){

    vector<vector<int>> b(1, vector<int>(9, 1));
    cout<<b[0][1]<<endl;
    change(b);
    cout<<b[0][1];
    return 0;
}

This displays the changed value for 2D vecor b.

Body:
You are not exiting the recursion call stack correctly in solveBoard(). Note the new bool function signature for solveBoard() being returned to signal up the invocation chain to exit early.  Also note the three different return points now depending on where you are.

bool solveBoard(vector<vector<int>>& _board) {
    int row = 0;
    int col = 0;
    bool flag;
    if (isBoardSolved(_board)) {
//      cout << "Solved Sudoku Board" << endl;
//      display(_board); //gives correct answer when I print it here
        return true;
    }
    else {
        for (int x = 0; x < 9; ++x) { //not using the style[1] because I need explicit index of empty slot
            flag = false;
            for (int y = 0; y < 9; ++y) {
                if (_board[x][y] == 0) {
                    row = x;
                    col = y;
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
    }

    auto options = findOptions(_board, row, col);
    for (auto digit : options) {
        if (digit.second != 1) {
            _board[row][col] = digit.first;
            if (solveBoard(_board))
                return true;
        }
    }
    _board[row][col] = 0;
    return false;
}


问:
Correct way to get the Facebook Authentication Token with Firebase after Redirection
I'm using Firebase and logging in with Facebook. I would like to use the Facebook Authentication token that Firebase returns me to make some calls to the Graph API, but the only Firebase method I found in the documentation is getRedirectResult().

```<code>firebase.auth().getRedirectResult().then(function(result) {
  if (result.credential) {
    // This gives you a Facebook Access Token. You can use it to access the Facebook API.
    var token = result.credential.accessToken;
    // ...
  }
  // The signed-in user info.
  var user = result.user;
})
</code>```

Is there another Firebase method I can call after I have been redirected? Thank you!

答:
Firebase does not provide an API for that. You have to make the extra API call to Facebook to get that data using the Facebook Access Token (make sure the desired scopes were prompted when getting that access token).</p>

```<code>AJAX GET 'https://graph.facebook.com/me?access_token=' + result.credential.accessToken
</code>```

Body:
I'm using Firebase and logging in with Facebook. I would like to use the Facebook Authentication token that Firebase returns me to make some calls to the Graph API, but the only Firebase method I found in the documentation is getRedirectResult().

firebase.auth().getRedirectResult().then(function(result) {
  if (result.credential) {
    // This gives you a Facebook Access Token. You can use it to access the Facebook API.
    var token = result.credential.accessToken;
    // ...
  }
  // The signed-in user info.
  var user = result.user;
})

Is there another Firebase method I can call after I have been redirected? Thank you!

Body:
Firebase does not provide an API for that. You have to make the extra API call to Facebook to get that data using the Facebook Access Token (make sure the desired scopes were prompted when getting that access token).

AJAX GET 'https://graph.facebook.com/me?access_token=' + result.credential.accessToken


问:
In React, how do you add animations to deletion of a table row because the deletion action will change the app state immediately?
If we actually use a delete action to change the Redux app state to remove that row (say, just an item in array), then the app state will change immediately and the row immediately disappear on screen without any animation.

How do we add 1 animation, such as fade and shrink together, or 2 animations, such as first fade, and then shrink, for the deletion?

Some thoughts:

Is there any "middleware" (like redux-promise doing AJAX), so we can animate first, and the action will only be sent to the reducers after the animation(s)?

Or what if we add a function, doing 1 or 2 animations first, and then when the last promise resolved, then call the action creator?

any other possible method?

答: Check out ReactCSSTransitionGroup. You can define animations to apply to components when they enter or leave the DOM.</p>


问:
Why GattDeviceService.FromIdASync() fails to finish?
I'm developing a Windows 10 Universal Application to communicate with an embedded system via a HM-10 chip.

What I did try and other circumstances

The chip is set up, there is no problem connecting to it. From an iPhone application for these devices, I can due two-way messaging via Arduino Serial window, and the iPhone application.
My computer can also see it, and can connect to it from a sample application provided by Microsoft.

Before running, it is paired and connected in Bluetooth Settings. I also tried without pairing and connecting, but it was not discovered by DeviceInformation then.

The MainPage.xaml.cs

```<code>using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using System.Threading.Tasks;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    ///

    public sealed partial class MainPage : Page
    {

        public List<string> deviceList = new List<string>();
        public MainPage()
        {
            this.InitializeComponent();
            Debug.WriteLine("A");
            var taskDevices = getDevices();
            Task.WaitAll(taskDevices);
            Debug.WriteLine("B");

        }
        public async Task<List<string>> getDevices()
        {
            Debug.WriteLine("C");
            foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess), null))
            {
                Debug.WriteLine("D");
                Debug.WriteLine(di.Name);
                Debug.WriteLine(di.Id);
                Debug.WriteLine(di.IsEnabled);
                var bleDevice = await GattDeviceService.FromIdAsync(di.Id);
                Debug.WriteLine("E");
                // Add the dvice name into the list.
               // deviceList.Add(bleDevice.Name);
            }
            return deviceList;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
</code>```

I did my search and I realised the manifest needs an addition to have Bluetooth capability.

Package.appxmanifest

```<code><?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"  xmlns:m2="http://schemas.microsoft.com/appx/manifest/foundation/windows10" IgnorableNamespaces="uap mp">
  <Identity Name="acbf6f03-e62b-4d1e-8c25-9f649ca5af4c" Publisher="CN=Boomkin" Version="1.0.0.0" />
  <mp:PhoneIdentity PhoneProductId="acbf6f03-e62b-4d1e-8c25-9f649ca5af4c" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
  <Properties>
    <DisplayName>App1</DisplayName>
    <PublisherDisplayName>Boomkin</PublisherDisplayName>
    <Logo>Assets\StoreLogo.png</Logo>
  </Properties>
  <Dependencies>
    <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
  </Dependencies>
  <Resources>
    <Resource Language="x-generate" />
  </Resources>
  <Applications>
    <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="App1.App">
      <uap:VisualElements DisplayName="Histamine Control Panel" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="App1" BackgroundColor="transparent">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png">
        </uap:DefaultTile>
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
      </uap:VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <m2:DeviceCapability Name="bluetooth.genericAttributeProfile">
      <m2:Device Id="any">
        <m2:Function Type="serviceId:00001800-0000-1000-8000-00805f9b34fb"/>
      </m2:Device>
    </m2:DeviceCapability>
  </Capabilities>
</Package>
</code>```

I have tried many other versions, added and deleted internetclient and bluetooth capabilities, without any success. My current guess that the problem is around here.

The problem

As the question states the FromIdAsync part doesn't return anything. Not even null (as I saw in many other questions here), it just does not finish and the thread exists eventually.

Log

```<code>A
C
D
HIST
\\?\BTHLEDevice#{00001800-0000-1000-8000-00805f9b34fb}_f45eabaaf694#8&2782425b&13&0006#{6e3bb679-4372-40c8-9eaa-4509df260cd8}
True
</code>```

Then after waiting for a while

```<code>The thread 0x3c6c has exited with code 0 (0x0).
</code>```

Thank you and I really appreciate any help.

答:
Your problem is here:

```<code>Task.WaitAll(taskDevices);
</code>```

Blocking on asynchronous code causes a deadlock. The proper resolution is to use async all the way.

In your specific case, you need to (synchronously, immediately) create your view in a "loading" state - however you want that to look. Then, when the asynchronous code completes, update your view to a "loaded" state. See my MSDN article on async data binding for more information.

Body:
I'm developing a Windows 10 Universal Application to communicate with an embedded system via a HM-10 chip.

What I did try and other circumstances

The chip is set up, there is no problem connecting to it. From an iPhone application for these devices, I can due two-way messaging via Arduino Serial window, and the iPhone application.
My computer can also see it, and can connect to it from a sample application provided by Microsoft.

Before running, it is paired and connected in Bluetooth Settings. I also tried without pairing and connecting, but it was not discovered by DeviceInformation then.

The MainPage.xaml.cs

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using System.Threading.Tasks;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace App1
{
    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///
    ///

    public sealed partial class MainPage : Page
    {

        public List<string> deviceList = new List<string>();
        public MainPage()
        {
            this.InitializeComponent();
            Debug.WriteLine("A");
            var taskDevices = getDevices();
            Task.WaitAll(taskDevices);
            Debug.WriteLine("B");

        }
        public async Task<List<string>> getDevices()
        {
            Debug.WriteLine("C");
            foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess), null))
            {
                Debug.WriteLine("D");
                Debug.WriteLine(di.Name);
                Debug.WriteLine(di.Id);
                Debug.WriteLine(di.IsEnabled);
                var bleDevice = await GattDeviceService.FromIdAsync(di.Id);
                Debug.WriteLine("E");
                // Add the dvice name into the list.
               // deviceList.Add(bleDevice.Name);
            }
            return deviceList;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

I did my search and I realised the manifest needs an addition to have Bluetooth capability.

Package.appxmanifest

<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"  xmlns:m2="http://schemas.microsoft.com/appx/manifest/foundation/windows10" IgnorableNamespaces="uap mp">
  <Identity Name="acbf6f03-e62b-4d1e-8c25-9f649ca5af4c" Publisher="CN=Boomkin" Version="1.0.0.0" />
  <mp:PhoneIdentity PhoneProductId="acbf6f03-e62b-4d1e-8c25-9f649ca5af4c" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
  <Properties>
    <DisplayName>App1</DisplayName>
    <PublisherDisplayName>Boomkin</PublisherDisplayName>
    <Logo>Assets\StoreLogo.png</Logo>
  </Properties>
  <Dependencies>
    <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
  </Dependencies>
  <Resources>
    <Resource Language="x-generate" />
  </Resources>
  <Applications>
    <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="App1.App">
      <uap:VisualElements DisplayName="Histamine Control Panel" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="App1" BackgroundColor="transparent">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png">
        </uap:DefaultTile>
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
      </uap:VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <m2:DeviceCapability Name="bluetooth.genericAttributeProfile">
      <m2:Device Id="any">
        <m2:Function Type="serviceId:00001800-0000-1000-8000-00805f9b34fb"/>
      </m2:Device>
    </m2:DeviceCapability>
  </Capabilities>
</Package>

I have tried many other versions, added and deleted internetclient and bluetooth capabilities, without any success. My current guess that the problem is around here.

The problem

As the question states the FromIdAsync part doesn't return anything. Not even null (as I saw in many other questions here), it just does not finish and the thread exists eventually.

Log

A
C
D
HIST
\\?\BTHLEDevice#{00001800-0000-1000-8000-00805f9b34fb}_f45eabaaf694#8&2782425b&13&0006#{6e3bb679-4372-40c8-9eaa-4509df260cd8}
True

Then after waiting for a while

The thread 0x3c6c has exited with code 0 (0x0).

Thank you and I really appreciate any help.

Body:
Your problem is here:

Task.WaitAll(taskDevices);

Blocking on asynchronous code causes a deadlock. The proper resolution is to use async all the way.

In your specific case, you need to (synchronously, immediately) create your view in a "loading" state - however you want that to look. Then, when the asynchronous code completes, update your view to a "loaded" state. See my MSDN article on async data binding for more information.


答:
Okay so, First of all, a constructor call needs parentheses, even if there are no parameters (It is still a function call)

```<code>    Scanner scanner = new Scanner(); <<<
</code>```

And put "System.in" inside these! System.in is an input stream, meaning a way to get input, and thats what the Scanner needs to work!

```<code>    new Scanner(System.in);
</code>```

It should work now, bye!

Title: Error in my code: The constructor Scanner() is undefined. Syntax error, insert "( )" to complete Expression

Body:
Okay so, First of all, a constructor call needs parentheses, even if there are no parameters (It is still a function call)

    Scanner scanner = new Scanner(); <<<

And put "System.in" inside these! System.in is an input stream, meaning a way to get input, and thats what the Scanner needs to work!

    new Scanner(System.in);

It should work now, bye!


问:
Getting errors on Visual Studio 2015 Professional [ html-has-lang ]
I am using VS 2015 Professional and trying to create a MVC project but the bugs and warning on the solutions keep coming up:

I manually add the  but still red lines there! How can I fix this?

答:
Try Rebuild Solution.

I was having the same issue, and this seems to do the trick.


问:
How to store information from a file into variables?
This is a part of an assignment that I have been having some trouble on.From my googling, I think I have to split the array and I have gotten to the point where I am now.

The program reads over a text file and outputs the text in it to the console. It then asks the user to input a name relating to the text file.
It then reads the file over again and what is suppose to happen next is for the variable power to store a number from a text file based on their input.

When I run my code, the text file outputs and it asks for the input. Then nothing happens; what should happen is that my variable power should output the value in index 2 of my array named g which should be 10 based on my text file.

My text file is organized like this:

Giant

Power

10

I want my int power to store 10 and I think that would be in index 2.
and Character (variable) is what the name that they enter in when being asked, in this case, Giant.

Am a beginner to java and any help is appreciated.

Edit: for now this problem is solved, dont know if it works or not because as I 'fixed' this problem an ArrayIndexOutofBoundsException: 2 has occurred. Any ideas why?? This error is at line 46 which is int power = Integer.parseInt(g[2]);

```<code>while ((line = creatureRead.readLine()) != null)
{
  String[] g = line.split(" ");
  for (int index = 0; index < g.length; index++)
  {

    if (character.equals("Giant"))
    {
    int power = Integer.parseInt(g[2]);
    System.out.println(power);
    }
  }
      creatureRead.close();
}
}

catch (IOException e)
{
 e.printStackTrace();
}
</code>```

答:
I had the same question Read a text file line by line into strings, the solution was simple:

```<code>List<String> lst = Files.readAllLines(Paths.get("C:\\test.txt"));
</code>```

and you can access the values very similarly to the way you access array values:

```<code>lst.get(0); //Creature
lst.get(1); //Power
lst.get(2); //10
</code>```

Body:
This is a part of an assignment that I have been having some trouble on.From my googling, I think I have to split the array and I have gotten to the point where I am now.

The program reads over a text file and outputs the text in it to the console. It then asks the user to input a name relating to the text file.
It then reads the file over again and what is suppose to happen next is for the variable power to store a number from a text file based on their input.

When I run my code, the text file outputs and it asks for the input. Then nothing happens; what should happen is that my variable power should output the value in index 2 of my array named g which should be 10 based on my text file.

My text file is organized like this:

Giant

Power

10

I want my int power to store 10 and I think that would be in index 2.
and Character (variable) is what the name that they enter in when being asked, in this case, Giant.

Am a beginner to java and any help is appreciated.

Edit: for now this problem is solved, dont know if it works or not because as I 'fixed' this problem an ArrayIndexOutofBoundsException: 2 has occurred. Any ideas why?? This error is at line 46 which is int power = Integer.parseInt(g[2]);

while ((line = creatureRead.readLine()) != null)
{
  String[] g = line.split(" ");
  for (int index = 0; index < g.length; index++)
  {

    if (character.equals("Giant"))
    {
    int power = Integer.parseInt(g[2]);
    System.out.println(power);
    }
  }
      creatureRead.close();
}
}

catch (IOException e)
{
 e.printStackTrace();
}

Body:
I had the same question Read a text file line by line into strings, the solution was simple:

List<String> lst = Files.readAllLines(Paths.get("C:\\test.txt"));

and you can access the values very similarly to the way you access array values:

lst.get(0); //Creature
lst.get(1); //Power
lst.get(2); //10


问:
Google Maps - street view doesn't work
I would to create a game based on google maps api. I want to have two google maps, one with street view, one with world map (something like geoguessr game). My mini-map is okay but street view doesn't work.
How to fix street view?

{
function createMap() {
  const streetView = new google.maps.StreetViewPanorama(
    document.getElementById('game-map'), {
      position: {lat: 37.869, lng: -122.255},
      pov: {
        heading: 45,
        pitch: 0
      },
    disableDefaultUI: true,
    scrollwheel:  false
  });
};
function createMiniMap() {
  const miniMapPosition = {lat: 25, lng: 0};
  const miniMap = new google.maps.Map(document.getElementById('mini-map'), {
    zoom: 1,
    center: miniMapPosition,
    disableDefaultUI: true,
  });
}
createMiniMap();
createMap();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
.map-container {
  width: 100%;
  height: calc(100vh-50px);
  background: transparent;
  z-index: 2;
}
.mini-map-container {
  height: 35vh;
  width: 30%;
  position: absolute;
  top: 55%;
  left: 65%;
  overflow: hidden;
  border: 5px solid black;
  z-index: 3;
}
.page-header {
  height: 50px;
  background: rgba(0, 0, 0, 0.9);
}
.nav-list a {
  text-decoration: none;
  color: #ffffff;
}
.nav-list {
  display: flex;
  flex-direction: row;
  list-style: none;
  justify-content: flex-end;
}
.nav-list li {
  padding: 0.5em;
}</code>```

New Game

Highscores

Login

 ```

答:
Your div with id="game-map" doesn't have a size.

{
  function createMap() {
    const streetView = new google.maps.StreetViewPanorama(
      document.getElementById('game-map'), {
        position: {
          lat: 37.869,
          lng: -122.255
        },
        pov: {
          heading: 45,
          pitch: 0
        },
        disableDefaultUI: true,
        scrollwheel: false
      });
  };

  function createMiniMap() {
    const miniMapPosition = {
      lat: 25,
      lng: 0
    };
    const miniMap = new google.maps.Map(document.getElementById('mini-map'), {
      zoom: 1,
      center: miniMapPosition,
      disableDefaultUI: true,
    });
  }
  createMiniMap();
  createMap();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
  width: 100%;
}

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.map-container {
  width: 100%;
  height: 100%;
  background: transparent;
  z-index: 2;
}

.mini-map-container {
  height: 35vh;
  width: 30%;
  position: absolute;
  top: 55%;
  left: 65%;
  overflow: hidden;
  border: 5px solid black;
  z-index: 3;
}

.page-header {
  height: 50px;
  background: rgba(0, 0, 0, 0.9);
}

.nav-list a {
  text-decoration: none;
  color: #ffffff;
}

.nav-list {
  display: flex;
  flex-direction: row;
  list-style: none;
  justify-content: flex-end;
}

.nav-list li {
  padding: 0.5em;
}</code>```

New Game

Highscores

Login

```

Title: Google Maps - street view doesn't work

Body:
I would to create a game based on google maps api. I want to have two google maps, one with street view, one with world map (something like geoguessr game). My mini-map is okay but street view doesn't work.
How to fix street view?

{
function createMap() {
  const streetView = new google.maps.StreetViewPanorama(
    document.getElementById('game-map'), {
      position: {lat: 37.869, lng: -122.255},
      pov: {
        heading: 45,
        pitch: 0
      },
    disableDefaultUI: true,
    scrollwheel:  false
  });
};
function createMiniMap() {
  const miniMapPosition = {lat: 25, lng: 0};
  const miniMap = new google.maps.Map(document.getElementById('mini-map'), {
    zoom: 1,
    center: miniMapPosition,
    disableDefaultUI: true,
  });
}
createMiniMap();
createMap();
}

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
.map-container {
  width: 100%;
  height: calc(100vh-50px);
  background: transparent;
  z-index: 2;
}
.mini-map-container {
  height: 35vh;
  width: 30%;
  position: absolute;
  top: 55%;
  left: 65%;
  overflow: hidden;
  border: 5px solid black;
  z-index: 3;
}
.page-header {
  height: 50px;
  background: rgba(0, 0, 0, 0.9);
}
.nav-list a {
  text-decoration: none;
  color: #ffffff;
}
.nav-list {
  display: flex;
  flex-direction: row;
  list-style: none;
  justify-content: flex-end;
}
.nav-list li {
  padding: 0.5em;
}

New Game

Highscores

Login

Body:
Your div with id="game-map" doesn't have a size.

{
  function createMap() {
    const streetView = new google.maps.StreetViewPanorama(
      document.getElementById('game-map'), {
        position: {
          lat: 37.869,
          lng: -122.255
        },
        pov: {
          heading: 45,
          pitch: 0
        },
        disableDefaultUI: true,
        scrollwheel: false
      });
  };

  function createMiniMap() {
    const miniMapPosition = {
      lat: 25,
      lng: 0
    };
    const miniMap = new google.maps.Map(document.getElementById('mini-map'), {
      zoom: 1,
      center: miniMapPosition,
      disableDefaultUI: true,
    });
  }
  createMiniMap();
  createMap();
}

html,
body {
  height: 100%;
  width: 100%;
}

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.map-container {
  width: 100%;
  height: 100%;
  background: transparent;
  z-index: 2;
}

.mini-map-container {
  height: 35vh;
  width: 30%;
  position: absolute;
  top: 55%;
  left: 65%;
  overflow: hidden;
  border: 5px solid black;
  z-index: 3;
}

.page-header {
  height: 50px;
  background: rgba(0, 0, 0, 0.9);
}

.nav-list a {
  text-decoration: none;
  color: #ffffff;
}

.nav-list {
  display: flex;
  flex-direction: row;
  list-style: none;
  justify-content: flex-end;
}

.nav-list li {
  padding: 0.5em;
}

<header class="page-header">
  <nav class="header-nav">
    <ul class="nav-list">
      <li><a href="#">New Game</a></li>
      <li><a href="#">Highscores</a></li>
      <li><a href="#">Login</a></li>
    </ul>
  </nav>
</header>
<main style="height: 100%; width:100%;">
  <div class="map-container" id="game-map"></div>
  <div class="mini-map-container" id="mini-map"></div>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
</main>


问:
For statement ends twice?
Here is my code:

```<code>#include <iostream>

using namespace std;

int main() {
char xxx[100] = {};

cin >> xxx;

for (int i = (sizeof(xxx) / sizeof(*xxx)) - 1; i >= 0; i--) {

    if (xxx[i] != NULL) {

        cout << xxx[i];

    }

}

cout << endl << endl;
main();

return 0;

}
</code>```

The problem is that when I enter "John Smith" into xxx it will output:

```<code>nhoJ

htimS
</code>```

Why does the "cout << endl << endl" happen in place of space?

答:
Fixed it with cin.getline. Thanks.</p>

```<code>#include <iostream>

using namespace std;

int main(){

for (;;) {

    char xxx[100] = {};

    cin.getline(xxx, 100);

    for (int i = (sizeof(xxx) / sizeof(*xxx)) - 1; i >= 0; i--) {

        if (xxx[i] != NULL) {

            cout << xxx[i];

        }

    }

    cout << endl << endl;

}

 return 0;

}
</code>```

Title: For statement ends twice?

Body:
Here is my code:

#include <iostream>

using namespace std;

int main() {
char xxx[100] = {};

cin >> xxx;

for (int i = (sizeof(xxx) / sizeof(*xxx)) - 1; i >= 0; i--) {

    if (xxx[i] != NULL) {

        cout << xxx[i];

    }

}

cout << endl << endl;
main();

return 0;

}

The problem is that when I enter "John Smith" into xxx it will output:

nhoJ

htimS

Why does the "cout << endl << endl" happen in place of space?

Body:
Fixed it with cin.getline. Thanks.

#include <iostream>

using namespace std;

int main(){

for (;;) {

    char xxx[100] = {};

    cin.getline(xxx, 100);

    for (int i = (sizeof(xxx) / sizeof(*xxx)) - 1; i >= 0; i--) {

        if (xxx[i] != NULL) {

            cout << xxx[i];

        }

    }

    cout << endl << endl;

}

 return 0;

}


问:
Bing translator exception while integrating with java application
I am trying to integrate bing translator in my java application. I have registered to Microsoft azure cognitive service and Microsoft market place.
while executing below code </p>

```<code>import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

public class Main {
    public static void main(String[] args) {
        try{
            Translate.setClientId(/* my Client Id */);
            Translate.setClientSecret(/* my Client Secret */);

            String translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);

            System.out.println(translatedText);
        }
        catch(Exception e) {
            System.err.println("Exception: " + e.getMessage());
        }
    }
}
</code>```

<p>I am getting below exception: </p>

```<code>Page NoException in thread "main" java.lang.Exception: [microsoft-translator-api] Error retrieving translation : Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveString(MicrosoftTranslatorAPI.java:202)
    at com.memetix.mst.translate.Translate.execute(Translate.java:61)
    at test.SimpleExcelTranalator.main(SimpleExcelTranalator.java:44)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.memetix.mst.MicrosoftTranslatorAPI.getToken(MicrosoftTranslatorAPI.java:139)
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveResponse(MicrosoftTranslatorAPI.java:160)
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveString(MicrosoftTranslatorAPI.java:199)
    ... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at com.memetix.mst.MicrosoftTranslatorAPI.getToken(MicrosoftTranslatorAPI.java:138)
    ... 4 more
</code>```

答:
The datamarket url is where you get your client id and secret from. Is that where you're sending your translation request to? Should be something like
http://api.microsofttranslator.com/v2/Http.svc/Translate?

Also datamarket is being deprecated. You have to switch to Azure Cognitive Services
http://docs.microsofttranslator.com/text-translate.html

Body:
I am trying to integrate bing translator in my java application. I have registered to Microsoft azure cognitive service and Microsoft market place.
while executing below code

import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

public class Main {
    public static void main(String[] args) {
        try{
            Translate.setClientId(/* my Client Id */);
            Translate.setClientSecret(/* my Client Secret */);

            String translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);

            System.out.println(translatedText);
        }
        catch(Exception e) {
            System.err.println("Exception: " + e.getMessage());
        }
    }
}

I am getting below exception:

Page NoException in thread "main" java.lang.Exception: [microsoft-translator-api] Error retrieving translation : Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveString(MicrosoftTranslatorAPI.java:202)
    at com.memetix.mst.translate.Translate.execute(Translate.java:61)
    at test.SimpleExcelTranalator.main(SimpleExcelTranalator.java:44)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.memetix.mst.MicrosoftTranslatorAPI.getToken(MicrosoftTranslatorAPI.java:139)
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveResponse(MicrosoftTranslatorAPI.java:160)
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveString(MicrosoftTranslatorAPI.java:199)
    ... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at com.memetix.mst.MicrosoftTranslatorAPI.getToken(MicrosoftTranslatorAPI.java:138)
    ... 4 more


问:
How to print VARCHAR(MAX) using Print Statement?
I have a code which is:

```<code>DECLARE @Script VARCHAR(MAX)

SELECT @Script = definition FROM manged.sys.all_sql_modules sq
where sq.object_id = (SELECT object_id from managed.sys.objects
Where type = 'P' and Name = 'usp_gen_data')

Declare @Pos int

SELECT  @pos=CHARINDEX(CHAR(13)+CHAR(10),@script,7500)

PRINT SUBSTRING(@Script,1,@Pos)

PRINT SUBSTRING(@script,@pos,8000)
</code>```

The length of the Script is around 10,000 Characters and Since I am using print Statement which can hold only max of 8000. So I am using two print statements.

The problem is when I have a script which is of say 18000 characters then I used to use 3 print statements.

So Is there a way that I could set the number of print statements depending on the length of the script?

答:
You can use this</p>

```<code>declare @i int = 1
while Exists(Select(Substring(@Script,@i,4000))) and (@i < LEN(@Script))
begin
     print Substring(@Script,@i,4000)
     set @i = @i+4000
end
</code>```

Body:
I have a code which is:

DECLARE @Script VARCHAR(MAX)

SELECT @Script = definition FROM manged.sys.all_sql_modules sq
where sq.object_id = (SELECT object_id from managed.sys.objects
Where type = 'P' and Name = 'usp_gen_data')

Declare @Pos int

SELECT  @pos=CHARINDEX(CHAR(13)+CHAR(10),@script,7500)

PRINT SUBSTRING(@Script,1,@Pos)

PRINT SUBSTRING(@script,@pos,8000)

The length of the Script is around 10,000 Characters and Since I am using print Statement which can hold only max of 8000. So I am using two print statements.

The problem is when I have a script which is of say 18000 characters then I used to use 3 print statements.

So Is there a way that I could set the number of print statements depending on the length of the script?

Body:
You can use this

declare @i int = 1
while Exists(Select(Substring(@Script,@i,4000))) and (@i < LEN(@Script))
begin
     print Substring(@Script,@i,4000)
     set @i = @i+4000
end