问:
Make a relation 3 django models and add filter
How do I make a relation 3 django models?

I would like to be able to do the mysql query, but as I do with django, I want to relate 3 models and additionally I want to add a filter by user ID

SQL Query

```<code>SELECT * FROM hospetaje
inner join usuario on (Usuario_idUsuario=idUsuario)
inner join pago on (idHospetaje=Hospetaje_idHospetaje)
where idUsuario = 5
</code>```

My model is

```<code>class Usuario(models.Model):
  idusuario = models.AutoField(db_column='idUsuario', primary_key=True)
  cc = models.CharField(unique=True, max_length=45)
  nombre = models.CharField(max_length=15)
  apellido = models.CharField(max_length=20)
  fecha_nacimiento = models.DateField()
  sexo = models.CharField(max_length=6)
  e_mail = models.CharField(db_column='e-mail', max_length=30)
  telefono = models.CharField(max_length=10)
  usuario = models.CharField(max_length=30)
  contrasena = models.CharField(max_length=10)
 tipousuario_idtipousuario = models.ForeignKey(Tipousuario, models.DO_NOTHING, db_column='TipoUsuario_idTipoUsuario')

class Pago(models.Model):
  idpago = models.AutoField(db_column='idPago', primary_key=True)
  fechapago = models.DateTimeField(db_column='fechaPago')
  fechapagada = models.DateField(db_column='fechaPagada')
  valor = models.FloatField()
  hospetaje_idhospetaje = models.ForeignKey(Hospetaje, models.DO_NOTHING, db_column='Hospetaje_idHospetaje')

class Hospetaje(models.Model):
  idhospetaje = models.AutoField(db_column='idHospetaje', primary_key=True)
  usuario_idusuario = models.ForeignKey('Usuario', models.DO_NOTHING, db_column='Usuario_idUsuario')
  habitacion_idhabitacion = models.ForeignKey(Habitacion, models.DO_NOTHING, db_column='Habitacion_idHabitacion')
  fechainicio = models.DateField(db_column='fechaInicio')
  fechafinal = models.DateField(db_column='fechaFinal', blank=True, null=True)
</code>```

答:
You've already created the "relations" between your models by defining ForeignKey fields.

You can access related models this way:

```<code>pago = Pago.objects.first()
pago.hospetaje_idhospetaje
</code>```

The Django docs have some good examples on how to access Many-to-One relationships.

Body:
How do I make a relation 3 django models?

I would like to be able to do the mysql query, but as I do with django, I want to relate 3 models and additionally I want to add a filter by user ID

SQL Query

SELECT * FROM hospetaje
inner join usuario on (Usuario_idUsuario=idUsuario)
inner join pago on (idHospetaje=Hospetaje_idHospetaje)
where idUsuario = 5

My model is

class Usuario(models.Model):
  idusuario = models.AutoField(db_column='idUsuario', primary_key=True)
  cc = models.CharField(unique=True, max_length=45)
  nombre = models.CharField(max_length=15)
  apellido = models.CharField(max_length=20)
  fecha_nacimiento = models.DateField()
  sexo = models.CharField(max_length=6)
  e_mail = models.CharField(db_column='e-mail', max_length=30)
  telefono = models.CharField(max_length=10)
  usuario = models.CharField(max_length=30)
  contrasena = models.CharField(max_length=10)
 tipousuario_idtipousuario = models.ForeignKey(Tipousuario, models.DO_NOTHING, db_column='TipoUsuario_idTipoUsuario')

class Pago(models.Model):
  idpago = models.AutoField(db_column='idPago', primary_key=True)
  fechapago = models.DateTimeField(db_column='fechaPago')
  fechapagada = models.DateField(db_column='fechaPagada')
  valor = models.FloatField()
  hospetaje_idhospetaje = models.ForeignKey(Hospetaje, models.DO_NOTHING, db_column='Hospetaje_idHospetaje')

class Hospetaje(models.Model):
  idhospetaje = models.AutoField(db_column='idHospetaje', primary_key=True)
  usuario_idusuario = models.ForeignKey('Usuario', models.DO_NOTHING, db_column='Usuario_idUsuario')
  habitacion_idhabitacion = models.ForeignKey(Habitacion, models.DO_NOTHING, db_column='Habitacion_idHabitacion')
  fechainicio = models.DateField(db_column='fechaInicio')
  fechafinal = models.DateField(db_column='fechaFinal', blank=True, null=True)

Body:
You've already created the "relations" between your models by defining ForeignKey fields.

You can access related models this way:

pago = Pago.objects.first()
pago.hospetaje_idhospetaje

The Django docs have some good examples on how to access Many-to-One relationships.


来源: stackexchange

问:
JavaScript - Search object property by key and add its value to array
Let's say I have an object like this:

```<code>var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};
</code>```

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

答:
The simplest way that I could think of using lodash:

```<code>_(object).map(_.keys).flatten().value();
</code>```

This of course assumes that the player keys are always at the same level in the object hierarchy.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have an object like this:

var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

Body:
The simplest way that I could think of using lodash:

_(object).map(_.keys).flatten().value();

This of course assumes that the player keys are always at the same level in the object hierarchy.


问:
Any guidelines for making android apps for Samsung TV
Are there any tutorials or guidelines available on the web for making android apps for the Samsung TV exclusively?

Here's the link:

http://www.samsung.com/us/samsungapps/?cid=ppc_hdt_goo_Apps_TV%20Apps_tv+apps

Looking forward for feedback. Thank you

答:
Have you tried samsung developer forum?
http://www.samsungdforum.com</p>

ContentLicense: CC BY-SA 2.5


问:
Remove span in a div class to convert the string to a number and make calulcations

      "         Price: "
      2000.00

        "         Avg Price: "

```
</div>
</div>
</p>

<p>I'm trying to select the number between strong and multiply it by 0.15 then replace the original value with the new value using javascript</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>var x = document.getElementsByClassName("s3");

    var i;
    var counter = 0;

    for (i = 0; i < x.length; i++) {

      var valueString  = x[0].innerHTML.replace(/Price:/g,"");

        counter = parseFloat(valueString);

        var j = (counter*0.15);
        x[i].innerHTML = (j);

    }</code>```

An example of the innerHTML would be $2000 and I want to take that number and multiply it by 0.15 and replace the value with the calculated number. EX: 2000.00 -> 300.00

This code only gets rid of the Price: and spaces, but I need it to remove the strong and span class "avg" in order to convert the string to a number using parseFloat. I'm not sure how to go about this, any help is appreciated.

答:
I am using .getElementsByTagName("strong")[0] to get the contents of the strong tag. Your valueString variable contained the entire HTML content of the s3 div exluding the "Price:" string. In future it is a good idea to use console.log() to check what a variable contains to help debug the issue.

var x = document.getElementsByClassName("s3");

var i;
var counter = 0;

for (i = 0; i < x.length; i++) {

  var valueString = x[i].getElementsByTagName("strong")[0].innerHTML;

    counter = parseFloat(valueString);

    var j = (counter*0.15).toFixed(2);
    x[i].innerHTML = (j);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class = "s3">
      <span>
          "         Price: "
          <strong>2000.00</strong>
          <span class = "avg">
            "         Avg Price: "
              </span>
       </span>
    </div></code>```

Body:
      "         Price: "
      2000.00

        "         Avg Price: "

I'm trying to select the number between strong and multiply it by 0.15 then replace the original value with the new value using javascript

var x = document.getElementsByClassName("s3");

    var i;
    var counter = 0;

    for (i = 0; i < x.length; i++) {

      var valueString  = x[0].innerHTML.replace(/Price:/g,"");

        counter = parseFloat(valueString);

        var j = (counter*0.15);
        x[i].innerHTML = (j);

    }

An example of the innerHTML would be $2000 and I want to take that number and multiply it by 0.15 and replace the value with the calculated number. EX: 2000.00 -> 300.00

This code only gets rid of the Price: and spaces, but I need it to remove the strong and span class "avg" in order to convert the string to a number using parseFloat. I'm not sure how to go about this, any help is appreciated.

Body:
I am using .getElementsByTagName("strong")[0] to get the contents of the strong tag. Your valueString variable contained the entire HTML content of the s3 div exluding the "Price:" string. In future it is a good idea to use console.log() to check what a variable contains to help debug the issue.

var x = document.getElementsByClassName("s3");

var i;
var counter = 0;

for (i = 0; i < x.length; i++) {

  var valueString = x[i].getElementsByTagName("strong")[0].innerHTML;

    counter = parseFloat(valueString);

    var j = (counter*0.15).toFixed(2);
    x[i].innerHTML = (j);

}

    <div class = "s3">
      <span>
          "         Price: "
          <strong>2000.00</strong>
          <span class = "avg">
            "         Avg Price: "
              </span>
       </span>
    </div>


问:
Limit text to X lines but adapt width to show everything
I have seen a few solutions using text-overflow:ellipsis to show a few lines of a text and end with "..." if it doesn't fit. However, I am looking for a CSS or JS solution where you would have a fixed height (or number of lines) and the width of the container naturally adapts to show the full text content.

If necessary, I can make a few images to explain better what I need.

Hopefully a solution exists !

答:
This would be a rough form.

let quotes = [
      'I do not regret one professional enemy I have made. Any actor who doesn\'t dare to make an enemy should get out of the business.',
      'A man thinks that by mouthing hard words he understands hard things.',
      'To say that a man is made up of certain chemical elements is a satisfactory description only for those who intend to use him as a fertilizer.',
      'Security is a kind of death.',
      'The worst loneliness is not to be comfortable with yourself.',
      'The fact is, sometimes it\'s hard to walk in a single woman\'s shoes. That\'s why we need really special ones now and then to make the walk a little more fun.',
      'Behind the phony tinsel of Hollywood lies the real tinsel.'
    ],
    rows = 3,
    quote, lastQuote,
    $quote = $('.quote'),
    getDifferentQuote = function() {
      quote = quotes[Math.floor(Math.random() * quotes.length)];
      if (quote === lastQuote) {
        return getDifferentQuote();
      } else {
        lastQuote = quote;
        return quote;
      }
    },
    changeQuote = function() {
      quote = getDifferentQuote();
      let item = $('', {
        text : quote,
        class: 'tester'
      });
      item.appendTo($('body'));
      let desiredHeight = item.height() * rows;
      item.css({
        whiteSpace: 'normal',
        width     : 30 + 'px'
      });

      while (item.height() > desiredHeight) {
        item.css({width: (item.width() + 1) + 'px'});
      }
      $quote.css({width: item.width() + 'px'});
      $quote.text(item.text());
      item.remove();
    };
$('button').on('click', changeQuote);
$(window).load(changeQuote);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.holder {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px;
  background-color: #f5f5f5;
  min-height: 100px;
}
.quote {
  text-align: center;
}
.tester {
  position: absolute;
  white-space: nowrap;
  display: block;
  opacity: 0;
}</code>```

<button>Change quote</button>```
</div>
</div>
</p>

<ul>
<li>selecting a random quote, appending it as an invisible item to the body, initially having 1 row,</li>
<li>calculate desired height by multiplying its height with nr. of rows (3 in this example),</li>
<li>make it very narrow and while its height is bigger than the desired one, keep increasing width. </li>
<li>when at desired height, copy its contents to the element in the "panel" and delete invisible item.</li>
</ul>

<p>Of course, a pre-requisite would be to make sure the invisible item has same <code>line-height</code>, <code>font-size</code> and <code>letter-spacing</code> as the one I'm going to use for display, which is true in my case because I haven't styled any of them. Also, if the display item has padding, the invisible one needs the same or you should account for it when calculating.</p>

<p>Hackish, but it works. Questions?</p>

<p>As a side-note, what I described above is inside the <code>changeQuote()</code> function. The rest are just helpers (adding quotes to have texts with various lenghts, a function that makes sure the quotes don't get repeated and other details - you don't need most of this stuff).</p>

<p>And another note: if you're here to learn, you'll probably find what I made useful. If you're here to get a job done, you're on the wrong website, IMHO. The proper way to do it would be to hire a professional.</p>

<hr>

<p>To understand why I'm doing this using an invisible item: even though it's quite fast (faster than I was expecting), if I did it on a visible item theoretically it could cause glimpses of its intermediary states to be rendered. Let's make a test, with the invisible item visible:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let quotes = [
      'I do not regret one professional enemy I have made. Any actor who doesn\'t dare to make an enemy should get out of the business.',
      'A man thinks that by mouthing hard words he understands hard things.',
      'To say that a man is made up of certain chemical elements is a satisfactory description only for those who intend to use him as a fertilizer.',
      'Security is a kind of death.',
      'The worst loneliness is not to be comfortable with yourself.',
      'The fact is, sometimes it\'s hard to walk in a single woman\'s shoes. That\'s why we need really special ones now and then to make the walk a little more fun.',
      'Behind the phony tinsel of Hollywood lies the real tinsel.'
    ],
    rows = 3,
    quote, lastQuote,
    $quote = $('.quote'),
    getDifferentQuote = function() {
      quote = quotes[Math.floor(Math.random() * quotes.length)];
      if (quote === lastQuote) {
        return getDifferentQuote();
      } else {
        lastQuote = quote;
        return quote;
      }
    },
    changeQuote = function() {
      quote = getDifferentQuote();
      let item = $('<span />', {
        text : quote,
        class: 'tester'
      });
      item.appendTo($('body'));
      let desiredHeight = item.height() * rows;
      item.css({
        whiteSpace: 'normal',
        width     : 30 + 'px'
      });

      while (item.height() > desiredHeight) {
        item.css({width: (item.width() + 1) + 'px'});
      }
      $quote.css({width: item.width() + 'px'});
      $quote.text(item.text());
      item.remove();
    };
$('button').on('click', changeQuote);
$(window).load(changeQuote);</code>```

.holder {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px;
  background-color: #f5f5f5;
  min-height: 100px;
}
.quote {
  text-align: center;
}
.tester {
  position: absolute;
  white-space: nowrap;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div class="quote"></div>
</div>
<button>Change quote</button></code>```

It never shows up. It should appear under the button but it's never rendered. At least not on my machine. Pretty cool.

Body:
This would be a rough form.

let quotes = [
      'I do not regret one professional enemy I have made. Any actor who doesn\'t dare to make an enemy should get out of the business.',
      'A man thinks that by mouthing hard words he understands hard things.',
      'To say that a man is made up of certain chemical elements is a satisfactory description only for those who intend to use him as a fertilizer.',
      'Security is a kind of death.',
      'The worst loneliness is not to be comfortable with yourself.',
      'The fact is, sometimes it\'s hard to walk in a single woman\'s shoes. That\'s why we need really special ones now and then to make the walk a little more fun.',
      'Behind the phony tinsel of Hollywood lies the real tinsel.'
    ],
    rows = 3,
    quote, lastQuote,
    $quote = $('.quote'),
    getDifferentQuote = function() {
      quote = quotes[Math.floor(Math.random() * quotes.length)];
      if (quote === lastQuote) {
        return getDifferentQuote();
      } else {
        lastQuote = quote;
        return quote;
      }
    },
    changeQuote = function() {
      quote = getDifferentQuote();
      let item = $('<span />', {
        text : quote,
        class: 'tester'
      });
      item.appendTo($('body'));
      let desiredHeight = item.height() * rows;
      item.css({
        whiteSpace: 'normal',
        width     : 30 + 'px'
      });

      while (item.height() > desiredHeight) {
        item.css({width: (item.width() + 1) + 'px'});
      }
      $quote.css({width: item.width() + 'px'});
      $quote.text(item.text());
      item.remove();
    };
$('button').on('click', changeQuote);
$(window).load(changeQuote);

.holder {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px;
  background-color: #f5f5f5;
  min-height: 100px;
}
.quote {
  text-align: center;
}
.tester {
  position: absolute;
  white-space: nowrap;
  display: block;
  opacity: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div class="quote"></div>
</div>
<button>Change quote</button>

selecting a random quote, appending it as an invisible item to the body, initially having 1 row,

calculate desired height by multiplying its height with nr. of rows (3 in this example),

make it very narrow and while its height is bigger than the desired one, keep increasing width.

when at desired height, copy its contents to the element in the "panel" and delete invisible item.

Of course, a pre-requisite would be to make sure the invisible item has same line-height, font-size and letter-spacing as the one I'm going to use for display, which is true in my case because I haven't styled any of them. Also, if the display item has padding, the invisible one needs the same or you should account for it when calculating.

Hackish, but it works. Questions?

As a side-note, what I described above is inside the changeQuote() function. The rest are just helpers (adding quotes to have texts with various lenghts, a function that makes sure the quotes don't get repeated and other details - you don't need most of this stuff).

And another note: if you're here to learn, you'll probably find what I made useful. If you're here to get a job done, you're on the wrong website, IMHO. The proper way to do it would be to hire a professional.

To understand why I'm doing this using an invisible item: even though it's quite fast (faster than I was expecting), if I did it on a visible item theoretically it could cause glimpses of its intermediary states to be rendered. Let's make a test, with the invisible item visible:

let quotes = [
      'I do not regret one professional enemy I have made. Any actor who doesn\'t dare to make an enemy should get out of the business.',
      'A man thinks that by mouthing hard words he understands hard things.',
      'To say that a man is made up of certain chemical elements is a satisfactory description only for those who intend to use him as a fertilizer.',
      'Security is a kind of death.',
      'The worst loneliness is not to be comfortable with yourself.',
      'The fact is, sometimes it\'s hard to walk in a single woman\'s shoes. That\'s why we need really special ones now and then to make the walk a little more fun.',
      'Behind the phony tinsel of Hollywood lies the real tinsel.'
    ],
    rows = 3,
    quote, lastQuote,
    $quote = $('.quote'),
    getDifferentQuote = function() {
      quote = quotes[Math.floor(Math.random() * quotes.length)];
      if (quote === lastQuote) {
        return getDifferentQuote();
      } else {
        lastQuote = quote;
        return quote;
      }
    },
    changeQuote = function() {
      quote = getDifferentQuote();
      let item = $('<span />', {
        text : quote,
        class: 'tester'
      });
      item.appendTo($('body'));
      let desiredHeight = item.height() * rows;
      item.css({
        whiteSpace: 'normal',
        width     : 30 + 'px'
      });

      while (item.height() > desiredHeight) {
        item.css({width: (item.width() + 1) + 'px'});
      }
      $quote.css({width: item.width() + 'px'});
      $quote.text(item.text());
      item.remove();
    };
$('button').on('click', changeQuote);
$(window).load(changeQuote);

.holder {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px;
  background-color: #f5f5f5;
  min-height: 100px;
}
.quote {
  text-align: center;
}
.tester {
  position: absolute;
  white-space: nowrap;
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div class="quote"></div>
</div>
<button>Change quote</button>

It never shows up. It should appear under the button but it's never rendered. At least not on my machine. Pretty cool.


问:
R add a legend to a france map
Hi I just want to add a legend to this map which represents the fecundity of young women by departments in France :

With this code :

```<code>library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)
</code>```

I dont know how to add that legend.

答:
plot(fr, col=fr$cols)
legend("topright", as.character(unique(fr$fertgroups)), fill = unique(fr$cols))
```

Title: R add a legend to a france map

Body:
Hi I just want to add a legend to this map which represents the fecundity of young women by departments in France :

With this code :

library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)

I dont know how to add that legend.


问:
C++: difference between 0. and 0.0?
I am well aware of the difference between 0 and 0.0 (int and double).

But is there any difference between 0. and 0.0 ( please note the . )?

Thanks a lot in advance,

Axel

答: No, there is not.</p>

Title: C++: difference between 0. and 0.0?

Body: No, there is not.


问:
C++ Primer Lippman 5th exercise 2.27 b
C++ Primer exercise 2.27  5th ed.

Exercise: Which of the following initializations are legal? Explain why.

(b) int *const p2 = &i2;

This is legal according to:
https://github.com/Mooophy/Cpp-Primer/tree/master/ch02#exercise-227

I don't see where i2 has been declared?
(I've looked at the errata also.)

答:
It is exploiting the fact that the * goes with the name, not the type.

i2 is declared as an integer by the question above this one

```<code>int* ip, ip2;
</code>```

not a pointer. So

```<code> int *const p2 = &i2;
</code>```

p2 is assigned the address of i2, a pointer.
The const pointer of p2 does not come in to play unless you try and change the value of p2.

Title: C++ Primer Lippman 5th exercise 2.27 b

Body:
It is exploiting the fact that the * goes with the name, not the type.

i2 is declared as an integer by the question above this one

int* ip, ip2;

not a pointer. So

 int *const p2 = &i2;

p2 is assigned the address of i2, a pointer.
The const pointer of p2 does not come in to play unless you try and change the value of p2.


问:
time(NULL) returning different time
I am trying to get current time in C using time_t current_time = time(NULL).
As I understand, it would return me the current time of system.
I am later trying to convert it into GMT time using struct tm* gmt = gmtime(&current_time).

I print both times using ctime() and asctime() functions.

The current time on my system is GMT + 1. But gmtime() returns me the same time as current_time is. I could not understand why gmtime() is returning me same time. Any help will be appreciated.

Ok here is the code and the output: Current time that windows is showing is 17:54 (Stockholm zone; GMT+1). I want something to return me 15:54. Or perhaps my understanding is wrong ...

```<code>time_t current_time = time(NULL);

struct tm* gmt = gmtime(&current_time);
struct tm* loc = localtime(&current_time);

printf("current time: %s\n", ctime(&current_time));
printf("gmt time %s\n", asctime(gmt));
printf("local time %s\n", asctime(loc));
</code>```

Output:

```<code>current time: Mon Oct  8 17:54:06 2012

gmt time Mon Oct  8 17:54:06 2012

local time Mon Oct  8 17:54:06 2012
</code>```

Accepted Solution: From Simes

That's probably your problem. Check the value of your TZ environment variable; if not present, it will default to GMT. Cygwin doesn't automatically pick up the time zone setting from Windows. See also localtime returns GMT for windows programs running on cygwin shells

答:
Run the debugger over these two lines:

```<code>struct tm* gmt = gmtime(&current_time);

struct tm* loc = localtime(&current_time);
</code>```

Break on the second line, watch members of gmt and when you execute the second line - you will see that some gmt members change value. Apparently some static memory is used by the library. So save the results of the first statement before running the second

Title: time(NULL) returning different time

Body:
I am trying to get current time in C using time_t current_time = time(NULL).
As I understand, it would return me the current time of system.
I am later trying to convert it into GMT time using struct tm* gmt = gmtime(&current_time).

I print both times using ctime() and asctime() functions.

The current time on my system is GMT + 1. But gmtime() returns me the same time as current_time is. I could not understand why gmtime() is returning me same time. Any help will be appreciated.

Ok here is the code and the output: Current time that windows is showing is 17:54 (Stockholm zone; GMT+1). I want something to return me 15:54. Or perhaps my understanding is wrong ...

time_t current_time = time(NULL);

struct tm* gmt = gmtime(&current_time);
struct tm* loc = localtime(&current_time);

printf("current time: %s\n", ctime(&current_time));
printf("gmt time %s\n", asctime(gmt));
printf("local time %s\n", asctime(loc));

Output:

current time: Mon Oct  8 17:54:06 2012

gmt time Mon Oct  8 17:54:06 2012

local time Mon Oct  8 17:54:06 2012

Accepted Solution: From Simes

That's probably your problem. Check the value of your TZ environment variable; if not present, it will default to GMT. Cygwin doesn't automatically pick up the time zone setting from Windows. See also localtime returns GMT for windows programs running on cygwin shells

Body:
Run the debugger over these two lines:

struct tm* gmt = gmtime(&current_time);

struct tm* loc = localtime(&current_time);

Break on the second line, watch members of gmt and when you execute the second line - you will see that some gmt members change value. Apparently some static memory is used by the library. So save the results of the first statement before running the second


问:
Prevent sorting on Implement Abstract Class
Given the following abstract class:

```<code>public abstract class AbstractTest
{
    protected abstract void B();
    protected abstract void Aa();
    protected abstract void Ab();
    protected abstract void C();
}
</code>```

In Visual Studio Code, if I select "Implement Abstract Class":

The methods are automatically generated by ascending, alphabetic order:

Does there exist a setting in VS Code that allows me to retain the order of the methods, in the order which I had originally defined them in?

答:
Visual Studio and VS Code use the Roslyn language services to enable these kind of code fixes.

In order to figure out which members are missing from the implementation, Roslyn uses simple reflection on the base type.

Unfortunately, with reflection, there is no guaranteed member order at all. Compiled IL also does not have any member order, so it’s technically just not possible to get the member definition order from a compiled type. The only way would be to actually look at the source file; but that’s just not how Roslyn works.

Body:
Given the following abstract class:

public abstract class AbstractTest
{
    protected abstract void B();
    protected abstract void Aa();
    protected abstract void Ab();
    protected abstract void C();
}

In Visual Studio Code, if I select "Implement Abstract Class":

The methods are automatically generated by ascending, alphabetic order:

Does there exist a setting in VS Code that allows me to retain the order of the methods, in the order which I had originally defined them in?


问:
pick first item of repeated in rxjs
I am receiving a bunch of streams from socket and want to merge repeated streams into one stream (or pick the first item)

In summary I want do this by rxjs:

```<code>In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: 1 - - - - - 2 - - - 3 - - - 1 - - - - - 2 - - - - - 1 - 2 - - - 3 - -
</code>```

答: distinctUntilChanged does exactly what you need.</p>

Title: pick first item of repeated in rxjs

Body:
I am receiving a bunch of streams from socket and want to merge repeated streams into one stream (or pick the first item)

In summary I want do this by rxjs:

In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: 1 - - - - - 2 - - - 3 - - - 1 - - - - - 2 - - - - - 1 - 2 - - - 3 - -


答: No. You can also write .0 as far as I know.</p>

Title: C++: difference between 0. and 0.0?

Body:
I am well aware of the difference between 0 and 0.0 (int and double).

But is there any difference between 0. and 0.0 ( please note the . )?

Thanks a lot in advance,

Axel


问:
PhpStorm, Laravel and autocompletition
I have a method run() in TreeGen class:

```<code>class TreeGen implements TreeGenerable{

 public function run()
 {
     ...
     $this->pushEmptyGroupsToTree($numFighters);
     ...
 }
}
</code>```

Thing is $this could be one of the 4 Subclasses of tree gen, and all those method implement different versions of pushEmptyGroupsToTree.

But PhpStorm is only looking for pushEmptyGroupsToTree in TreeGen class and off course, I don't have it defined in the super class, so it doesn't detect it.

Is there a way to make him recognize subclass methods?

答:
IDE behaves correctly. You either need to declare this class abstract, or declare abstract method here or in superclass.

UPDATE

Method run of TreeGen could be called from instance of Treegen

```<code>$treeGen = new TreeGen;
$treeGen->run();
</code>```

and that will cause Call to undefined method error.

If TreeGen is not supposed to be called directly it should be abstract.

Title: PhpStorm, Laravel and autocompletition

Body:
I have a method run() in TreeGen class:

class TreeGen implements TreeGenerable{

 public function run()
 {
     ...
     $this->pushEmptyGroupsToTree($numFighters);
     ...
 }
}

Thing is $this could be one of the 4 Subclasses of tree gen, and all those method implement different versions of pushEmptyGroupsToTree.

But PhpStorm is only looking for pushEmptyGroupsToTree in TreeGen class and off course, I don't have it defined in the super class, so it doesn't detect it.

Is there a way to make him recognize subclass methods?

Body:
IDE behaves correctly. You either need to declare this class abstract, or declare abstract method here or in superclass.

UPDATE

Method run of TreeGen could be called from instance of Treegen

$treeGen = new TreeGen;
$treeGen->run();

and that will cause Call to undefined method error.

If TreeGen is not supposed to be called directly it should be abstract.


问:
Why is my Spring oauth server always returning the same access token?
I'm using Spring 4.3.8.RELEASE and spring-boot 1.5.3.RELEASE.  I want to serve oauth access tokens to applications with the proper credentials.  I'm using the org.springframework.security.oauth2.provider.token.store.JdbcTokenStore class to do this.  However, I'm noticing that each time I connect with a client to my server that I have set up with OAuth, the server repeatedly returns the same access token, even after server restarts.  My OAuth server configuration is below

```<code><?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
    xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
        <!-- include this only if you need to authenticate clients via request parameters -->
        <custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <!-- The OAuth2 protected resources are separated out into their own block
        so we can deal with authorization and error handling separately. This isn't
        mandatory, but it makes it easier to control the behaviour. -->
    <http pattern="/oauth/(users|clients)/.*" request-matcher="regex"
        create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
        use-expressions="true" xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/oauth/users/([^/].*?)/tokens/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')"
            method="DELETE" />
        <intercept-url pattern="/oauth/users/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')"
            method="GET" />
        <intercept-url pattern="/oauth/clients/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')"
            method="GET" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
        <expression-handler ref="oauthWebExpressionHandler" />
    </http>

    <!-- The OAuth2 protected resources are separated out into their own block
        so we can deal with authorization and error handling separately. This isn't
        mandatory, but it makes it easier to control the behaviour. -->
    <http pattern="/me/**" create-session="never"
        entry-point-ref="oauthAuthenticationEntryPoint"
        access-decision-manager-ref="accessDecisionManager"
        xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/me" access="ROLE_USER,SCOPE_READ" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <bean id="oauthAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2" />
    </bean>

    <bean id="clientAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2/client" />
        <property name="typeName" value="Basic" />
    </bean>

    <bean id="oauthAccessDeniedHandler"
        class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <bean id="clientCredentialsTokenEndpointFilter"
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="clientAuthenticationManager" />
    </bean>

    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
        xmlns="http://www.springframework.org/schema/beans">
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
                <bean class="org.springframework.security.access.vote.RoleVoter" />
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
            </list>
        </constructor-arg>
    </bean>

    <authentication-manager id="clientAuthenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService" />
    </authentication-manager>

    <authentication-manager alias="authenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>
            <user-service id="userDetailsService">
                <user name="marissa" password="koala" authorities="ROLE_USER" />
                <user name="paul" password="emu" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
        class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails" />
    </bean>

    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="dataSource" />
        <property name="authenticationKeyGenerator">
            <bean class="org.springframework.security.oauth2.UniqueAuthenticationKeyGenerator" />
        </property>
    </bean>

    <bean id="tokenServices"
        class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="tokenEnhancer" ref="tokenEnhancer" />
        <property name="supportRefreshToken" value="true" />
        <property name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="tokenEnhancer"
        class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" />

    <bean id="requestFactory"
        class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="approvalStore"
        class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore">
        <property name="tokenStore" ref="tokenStore" />
    </bean>

    <oauth:authorization-server
        client-details-service-ref="clientDetails" token-services-ref="tokenServices">
        <oauth:client-credentials />
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter" entry-point-ref="entry"
        resource-id="myclientAssignment" token-services-ref="tokenServices" />

    <bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <constructor-arg value="/assignment" />
    </bean>

    <context:property-placeholder location="classpath:application.properties"/>
    <oauth:client-details-service id="clientDetails">
        <oauth:client client-id="${myclient.client.id}"
            authorized-grant-types="client_credentials" authorities="ROLE_CLIENT"
        access-token-validity="30"
            scope="read,write" secret="${myclient.client.secret}" />
    </oauth:client-details-service>

    <mvc:default-servlet-handler />

    <oauth:expression-handler id="oauthExpressionHandler" />

    <oauth:web-expression-handler id="oauthWebExpressionHandler" />

    <http pattern="/api/**"
                  create-session="never"
                  entry-point-ref="oauthAuthenticationEntryPoint"
                  access-decision-manager-ref="accessDecisionManager"
                  xmlns="http://www.springframework.org/schema/security">
     <anonymous enabled="false" />
     <intercept-url pattern="/**"
                             access="IS_AUTHENTICATED_FULLY"/>

     <custom-filter ref="resourceServerFilter"
                             before="PRE_AUTH_FILTER" />
     <access-denied-handler ref="oauthAccessDeniedHandler" />
   </http>

</beans>
</code>```

Here's the shell script I'm using to connect to my local server to retrieve the token ...

```<code>#!/bin/bash

ret=$(curl http://localhost:8080/myproject/oauth/token \
  -u "myclientid:mysecret" \
  -d "grant_type=client_credentials")
echo $ret > /tmp/out
cat /tmp/out
access_token=$( sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/' /tmp/out )
echo $access_token
</code>```

Edit:

Per Hans' request, here is an example access token

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2ODQ4NDAzLCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiI4OGMxZjkzZC0wNmRhLTRmYTAtOTM1OS0yZWMxYzU5MWJlMGIiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.Pf-rjPDj0ZhrNOYuhA0tK8lPLLCzlkqUuFFjb48xskA
</code>```

and here is a second access token

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2OTUzNTg0LCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiIxM2I5M2M4Ni05MmIwLTQyY2UtYjFkNS1lZjRiNmZhNzJkMzgiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.GfSHA_JcQg2WHYCI81lunMFIhxdX6REc4goshB2Lck0
</code>```

答:
Why i am getting same access token for multiple login request?

Ashwani has given answer like below in this post

Access Tokens have fixed Life-Time.

Until that period has not expires, access token remains the same.
During that period if you request access token you will receive the same string but will have reset expiration. It would only happen if
Location, Password etc are exactly same as previous request.
Otherwise new token generated. Sometimes Salesforce resets the
expiration time for last expired token and return in response.

Short-lived access tokens and long-lived refresh tokens

There is no way to expire those tokens directly, so instead, the tokens are issued with a short expiration time so that the application is forced to continually refresh them, giving the service a chance to revoke an application’s access if needed.

@Dave, As you have told that, there is no expiry field, so it is non-expiring access token.

Non-expiring access tokens

Non-expiring access tokens are the easiest method for developers. If you choose this option, it is important to consider the trade-offs you are making.

It isn’t practical to use self-encoded tokens if you want to be able to revoke them arbitrarily. As such, you’ll need to store these tokens in some sort of database, so they can be deleted or marked as invalid as needed.

Note that even if the service intends on issuing non-expiring access tokens for normal use, you’ll still need to provide a mechanism to expire them under exceptional circumstances, such as if the user explicitly wants to revoke an application’s access, or if a user account is deleted.

Non-expiring access tokens are much easier for developers testing their own applications. You can even pre-generate one or more non-expiring access tokens for developers and show it to them on the application details screen. This way they can immediately start making API requests with the token, and not worry about setting up an OAuth flow in order to start testing your API.

In summary, use non-expiring access tokens when:

you have a mechanism to revoke access tokens arbitrarily

you don’t have a huge risk if tokens are leaked

you want to provide an easy authentication mechanism to your
developers

you want third-party applications to have offline access to users’
data

Resource Link: Acess token lifetime

How to refresh access token? Rules are given here: https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/

How to issue an access token are given here:

```<code> +----------+
 | Resource |
 |  Owner   |
 |          |
 +----------+
      v
      |    Resource Owner
     (A) Password Credentials
      |
      v
 +---------+                                  +---------------+
 |         |>--(B)---- Resource Owner ------->|               |
 |         |         Password Credentials     | Authorization |
 | Client  |                                  |     Server    |
 |         |<--(C)---- Access Token ---------<|               |
 |         |    (w/ Optional Refresh Token)   |               |
 +---------+                                  +---------------+

        Figure 5: Resource Owner Password Credentials Flow
</code>```

The flow illustrated in Figure 5 includes the following steps:

(A)  The resource owner provides the client with its username and
password.

(B)  The client requests an access token from the authorization
server's token endpoint by including the credentials received
from the resource owner.  When making the request, the client
authenticates with the authorization server.

(C)  The authorization server authenticates the client and validates
the resource owner credentials, and if valid, issues an access
token.

The authorization server MUST follow the rules:

o  require client authentication for confidential clients or for any
client that was issued client credentials (or with other
authentication requirements),

o  authenticate the client if client authentication is included, and

o  validate the resource owner password credentials using its
existing password validation algorithm.

Resource Link: https://www.rfc-editor.org/rfc/rfc6749#page-47

Body:
I'm using Spring 4.3.8.RELEASE and spring-boot 1.5.3.RELEASE.  I want to serve oauth access tokens to applications with the proper credentials.  I'm using the org.springframework.security.oauth2.provider.token.store.JdbcTokenStore class to do this.  However, I'm noticing that each time I connect with a client to my server that I have set up with OAuth, the server repeatedly returns the same access token, even after server restarts.  My OAuth server configuration is below

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
    xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />

        <custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <http pattern="/oauth/(users|clients)/.*" request-matcher="regex"
        create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
        use-expressions="true" xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/oauth/users/([^/].*?)/tokens/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')"
            method="DELETE" />
        <intercept-url pattern="/oauth/users/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')"
            method="GET" />
        <intercept-url pattern="/oauth/clients/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')"
            method="GET" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
        <expression-handler ref="oauthWebExpressionHandler" />
    </http>

    <http pattern="/me/**" create-session="never"
        entry-point-ref="oauthAuthenticationEntryPoint"
        access-decision-manager-ref="accessDecisionManager"
        xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/me" access="ROLE_USER,SCOPE_READ" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <bean id="oauthAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2" />
    </bean>

    <bean id="clientAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2/client" />
        <property name="typeName" value="Basic" />
    </bean>

    <bean id="oauthAccessDeniedHandler"
        class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <bean id="clientCredentialsTokenEndpointFilter"
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="clientAuthenticationManager" />
    </bean>

    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
        xmlns="http://www.springframework.org/schema/beans">
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
                <bean class="org.springframework.security.access.vote.RoleVoter" />
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
            </list>
        </constructor-arg>
    </bean>

    <authentication-manager id="clientAuthenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService" />
    </authentication-manager>

    <authentication-manager alias="authenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>
            <user-service id="userDetailsService">
                <user name="marissa" password="koala" authorities="ROLE_USER" />
                <user name="paul" password="emu" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
        class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails" />
    </bean>

    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="dataSource" />
        <property name="authenticationKeyGenerator">
            <bean class="org.springframework.security.oauth2.UniqueAuthenticationKeyGenerator" />
        </property>
    </bean>

    <bean id="tokenServices"
        class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="tokenEnhancer" ref="tokenEnhancer" />
        <property name="supportRefreshToken" value="true" />
        <property name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="tokenEnhancer"
        class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" />

    <bean id="requestFactory"
        class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="approvalStore"
        class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore">
        <property name="tokenStore" ref="tokenStore" />
    </bean>

    <oauth:authorization-server
        client-details-service-ref="clientDetails" token-services-ref="tokenServices">
        <oauth:client-credentials />
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter" entry-point-ref="entry"
        resource-id="myclientAssignment" token-services-ref="tokenServices" />

    <bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <constructor-arg value="/assignment" />
    </bean>

    <context:property-placeholder location="classpath:application.properties"/>
    <oauth:client-details-service id="clientDetails">
        <oauth:client client-id="${myclient.client.id}"
            authorized-grant-types="client_credentials" authorities="ROLE_CLIENT"
        access-token-validity="30"
            scope="read,write" secret="${myclient.client.secret}" />
    </oauth:client-details-service>

    <mvc:default-servlet-handler />

    <oauth:expression-handler id="oauthExpressionHandler" />

    <oauth:web-expression-handler id="oauthWebExpressionHandler" />

    <http pattern="/api/**"
                  create-session="never"
                  entry-point-ref="oauthAuthenticationEntryPoint"
                  access-decision-manager-ref="accessDecisionManager"
                  xmlns="http://www.springframework.org/schema/security">
     <anonymous enabled="false" />
     <intercept-url pattern="/**"
                             access="IS_AUTHENTICATED_FULLY"/>

     <custom-filter ref="resourceServerFilter"
                             before="PRE_AUTH_FILTER" />
     <access-denied-handler ref="oauthAccessDeniedHandler" />
   </http>

</beans>

Here's the shell script I'm using to connect to my local server to retrieve the token ...

#!/bin/bash

ret=$(curl http://localhost:8080/myproject/oauth/token \
  -u "myclientid:mysecret" \
  -d "grant_type=client_credentials")
echo $ret > /tmp/out
cat /tmp/out
access_token=$( sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/' /tmp/out )
echo $access_token

Edit:

Per Hans' request, here is an example access token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2ODQ4NDAzLCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiI4OGMxZjkzZC0wNmRhLTRmYTAtOTM1OS0yZWMxYzU5MWJlMGIiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.Pf-rjPDj0ZhrNOYuhA0tK8lPLLCzlkqUuFFjb48xskA

and here is a second access token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2OTUzNTg0LCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiIxM2I5M2M4Ni05MmIwLTQyY2UtYjFkNS1lZjRiNmZhNzJkMzgiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.GfSHA_JcQg2WHYCI81lunMFIhxdX6REc4goshB2Lck0

Body:
Why i am getting same access token for multiple login request?

Ashwani has given answer like below in this post

Access Tokens have fixed Life-Time.

Until that period has not expires, access token remains the same.
During that period if you request access token you will receive the same string but will have reset expiration. It would only happen if
Location, Password etc are exactly same as previous request.
Otherwise new token generated. Sometimes Salesforce resets the
expiration time for last expired token and return in response.

Short-lived access tokens and long-lived refresh tokens

There is no way to expire those tokens directly, so instead, the tokens are issued with a short expiration time so that the application is forced to continually refresh them, giving the service a chance to revoke an application’s access if needed.

@Dave, As you have told that, there is no expiry field, so it is non-expiring access token.

Non-expiring access tokens

Non-expiring access tokens are the easiest method for developers. If you choose this option, it is important to consider the trade-offs you are making.

It isn’t practical to use self-encoded tokens if you want to be able to revoke them arbitrarily. As such, you’ll need to store these tokens in some sort of database, so they can be deleted or marked as invalid as needed.

Note that even if the service intends on issuing non-expiring access tokens for normal use, you’ll still need to provide a mechanism to expire them under exceptional circumstances, such as if the user explicitly wants to revoke an application’s access, or if a user account is deleted.

Non-expiring access tokens are much easier for developers testing their own applications. You can even pre-generate one or more non-expiring access tokens for developers and show it to them on the application details screen. This way they can immediately start making API requests with the token, and not worry about setting up an OAuth flow in order to start testing your API.

In summary, use non-expiring access tokens when:

you have a mechanism to revoke access tokens arbitrarily

you don’t have a huge risk if tokens are leaked

you want to provide an easy authentication mechanism to your
developers

you want third-party applications to have offline access to users’
data

Resource Link: Acess token lifetime

How to refresh access token? Rules are given here: https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/

How to issue an access token are given here:

 +----------+
 | Resource |
 |  Owner   |
 |          |
 +----------+
      v
      |    Resource Owner
     (A) Password Credentials
      |
      v
 +---------+                                  +---------------+
 |         |>--(B)---- Resource Owner ------->|               |
 |         |         Password Credentials     | Authorization |
 | Client  |                                  |     Server    |
 |         |<--(C)---- Access Token ---------<|               |
 |         |    (w/ Optional Refresh Token)   |               |
 +---------+                                  +---------------+

        Figure 5: Resource Owner Password Credentials Flow

The flow illustrated in Figure 5 includes the following steps:

(A)  The resource owner provides the client with its username and
password.

(B)  The client requests an access token from the authorization
server's token endpoint by including the credentials received
from the resource owner.  When making the request, the client
authenticates with the authorization server.

(C)  The authorization server authenticates the client and validates
the resource owner credentials, and if valid, issues an access
token.

The authorization server MUST follow the rules:

o  require client authentication for confidential clients or for any
client that was issued client credentials (or with other
authentication requirements),

o  authenticate the client if client authentication is included, and

o  validate the resource owner password credentials using its
existing password validation algorithm.

Resource Link: https://www.rfc-editor.org/rfc/rfc6749#page-47


答:
The DOM APIs document.querySelector or document.querySelectorAll would come in handy here.

You can use these to access the  DOM nodes directly instead of having to parse out other HTML, etc.

var numLabels = document.querySelectorAll('.s3 strong');

for(var label of numLabels) {
  var value = parseFloat(label.innerText);
  label.innerText = (value * 0.15).toFixed(2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="s3">
  <span>
      "         Price: "
      <strong>2000.00</strong>
      <span class = "avg">
        "         Avg Price: "
          </span>
  </span>
</div>

<div class="s3">
  <span>
      "         Price: "
      <strong>1000.00</strong>
      <span class = "avg">
        "         Avg Price: "
          </span>
  </span>
</div></code>```

Title: Remove span in a div class to convert the string to a number and make calulcations

Body:
The DOM APIs document.querySelector or document.querySelectorAll would come in handy here.

You can use these to access the <strong> DOM nodes directly instead of having to parse out other HTML, etc.

var numLabels = document.querySelectorAll('.s3 strong');

for(var label of numLabels) {
  var value = parseFloat(label.innerText);
  label.innerText = (value * 0.15).toFixed(2);
}

<div class="s3">
  <span>
      "         Price: "
      <strong>2000.00</strong>
      <span class = "avg">
        "         Avg Price: "
          </span>
  </span>
</div>

<div class="s3">
  <span>
      "         Price: "
      <strong>1000.00</strong>
      <span class = "avg">
        "         Avg Price: "
          </span>
  </span>
</div>


问:
Is there an equivalent of the Devise helper `sign_in` that I can use in a Capybara feature test?
I am trying to write a feature test for a resource which would only be available to a signed in user, is there an equivalent helpr method to devise's `sign_in' that I can use, or do I have to take Capybara manually through the signin in process?</p>

```<code>require 'rails_helper'
require_relative '../support/new_quote_form'

feature 'creating quote request' do
    let(:user) { FactoryGirl.create(:user) }
    let(:new_quote_form) { NewQuoteForm.new }

    before do
        sign_in(user) #Would be nice and easy!
    end

    scenario 'completing quote data' do
        new_quote_form.visit_page.fill_in_with().submit
        expect(page).to have_content('Quote request created')
    end

    scenario 'cannot reqest quote with invalid data' do
        new_quote_form.visit_page.submit
        expect(page).to have_content("Must be selected")
    end
end
</code>```

答:
The Warden test helpers can be used with Devise and Capybara to shortcut logging here.  Here is the article in Devises wiki talking about it -
 https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara</p>

Body:
I am trying to write a feature test for a resource which would only be available to a signed in user, is there an equivalent helpr method to devise's `sign_in' that I can use, or do I have to take Capybara manually through the signin in process?

require 'rails_helper'
require_relative '../support/new_quote_form'

feature 'creating quote request' do
    let(:user) { FactoryGirl.create(:user) }
    let(:new_quote_form) { NewQuoteForm.new }

    before do
        sign_in(user) #Would be nice and easy!
    end

    scenario 'completing quote data' do
        new_quote_form.visit_page.fill_in_with().submit
        expect(page).to have_content('Quote request created')
    end

    scenario 'cannot reqest quote with invalid data' do
        new_quote_form.visit_page.submit
        expect(page).to have_content("Must be selected")
    end
end


问:
position:absolute breaks CSS dropdown
I am making something with ace editor. As part of this, I have a dropdown menu that allows theme selection. This is on a bar at the top, (which will eventually have more options). I know that, in order to position the bar at the very top, I need to use position:absolute in the CSS code. However, this breaks the dropdown, and it no longer actually drops down. To see what I mean, here is a fiddle. (To compare, removing position: absolute in the CSS for #navbar makes it work fine, but is not at the very top [most visible in a full window].)
Note: In the fiddle, I have removed everything not related to the navbar, such as the ace code.

答:
You have to make the drop down relative to the parent if its going to be in absolute position.
Set the parent position to relative, and then the dropdown will be positioned inside or within the parent tag.
Like Example:</p>

```<code><div style="position:relative;">
<div class="dropdown" style="position:absolute; top:0; left:0;">...</div>
</div>
</code>```

Title: position:absolute breaks CSS dropdown

Body:
You have to make the drop down relative to the parent if its going to be in absolute position.
Set the parent position to relative, and then the dropdown will be positioned inside or within the parent tag.
Like Example:

<div style="position:relative;">
<div class="dropdown" style="position:absolute; top:0; left:0;">...</div>
</div>


问:
SSRS Report - Removing right side white space
I'm developing an SSRS report in Visual Studio 2012. The report is set up to use landscape orientation. There is a 0.25in margin on the left and no margin on the right. The report is 10.5 inches wide. ConsumeContainerWhitespace is set to True. There are no hidden objects outside of the normal report area.

When I look at the report in print view or actually print it out there is a huge amount of white space on the right side of the report. It's almost like the report is being shrunk and then left justified when printing.

I would love to get this fixed so the report prints the same as it looks in the designer. If anyone has an opinion or some input it would be most welcome. Thank you!

答:
You have me stumped but things I would check:

There isn't a textbox or label or something pushing past the boundary of the expected margin.  This causes the report to print like what you are seeing.  Just expand the report and make sure everything is actually less than 10.25 inches.

Is your paper size set to letter?


问:
Getting data in order with Jsoup
I'm trying to get data from html in order from a web. Html code looks like:

First Text

     Written by excedent

quote message

Second Text

Third Text

```

What I want to do is create an Android layout scraping html, but I need to preserve the order of the elements. In this case:

TextView => First Text

TextView => Quote Message

TextView => Second Text

ImageView => img

TextView => Third Text

The problem comes when I try to get html values in order, using JSoup I get a String with "First Text Second Text Third Text" with Element.ownText, an then img at the end, resulting:

TextView => First Text Second Text Third Text

TextView => Quote Message

ImageView => img

What can I do to get that data in order?

Thanks in advance

答:
You can parse the html into a list of html nodes. The list of nodes will preserve the DOM order and give what you want.

Check the parseFragment method :

This method will give you a list of nodes.

Title: Getting data in order with Jsoup

Body:
I'm trying to get data from html in order from a web. Html code looks like:

First Text

     Written by excedent

quote message

Second Text

Third Text

What I want to do is create an Android layout scraping html, but I need to preserve the order of the elements. In this case:

TextView => First Text

TextView => Quote Message

TextView => Second Text

ImageView => img

TextView => Third Text

The problem comes when I try to get html values in order, using JSoup I get a String with "First Text Second Text Third Text" with Element.ownText, an then img at the end, resulting:

TextView => First Text Second Text Third Text

TextView => Quote Message

ImageView => img

What can I do to get that data in order?

Thanks in advance


问:
com.ibm.websphere.jtaextensions.NotSupportedException thrown under load
I have an application containing 4 MDB's each of which receives SOAP messages over JMS from MQ. Once the messages have been received we process the XML into an object model and process accordingly which always involves either loading or saving messages to an Oracle database via Hibernate.

Additionally we have a quartz process with fires every minute that may or may not trigger so actions which could also read or write to the database using Hibernate.

When the system in under high load, i.e. processing large numbers 1k + and potentially performing some database read/writes triggered by our quartz process we keep seeing the following exception be thrown in our logs.

===============================================================================
at com.integrasp.iatrade.logic.MessageContextRouting.lookup(MessageContextRouting. java:150)
at com.integrasp.iatrade.logic.RequestResponseManager.findRequestDestination(Reque stResponseManager.java:153) at com.integrasp.iatrade.logic.RequestResponseManager.findRequestDestination(Reque stResponseManager.java:174)
at com.integrasp.iatrade.logic.IOLogic.processResponse(IOLogic.java:411)
 at com.integrasp.iatrade.logic.FxOrderQuoteManager.requestQuote(FxOrderQuoteManage r.java:119)
at com.integrasp.iatrade.logic.FxOrderQuoteManager.processRequest(FxOrderQuoteMana ger.java:682)
at com.integrasp.iatrade.logic.FxOrderSubmissionManager.processRequest(FxOrderSubm issionManager.java:408)
at com.integrasp.iatrade.eo.SubmitOrderRequest.process(SubmitOrderRequest.java:60)
at com.integrasp.iatrade.ejb.BusinessLogicRegister.perform(BusinessLogicRegister.j ava:85)
at com.integrasp.iatrade.ejb.mdb.OrderSubmissionBean.onMessage(OrderSubmissionBean .java:147)
at com.ibm.ejs.jms.listener.MDBWrapper$PriviledgedOnMessage.run(MDBWrapper.java:30 2)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:63 )
at com.ibm.ejs.jms.listener.MDBWrapper.callOnMessage(MDBWrapper.java:271)
at com.ibm.ejs.jms.listener.MDBWrapper.onMessage(MDBWrapper.java:240)
at com.ibm.mq.jms.MQSession.run(MQSession.java:1593)
at com.ibm.ejs.jms.JMSSessionHandle.run(JMSSessionHandle.java:970)
at com.ibm.ejs.jms.listener.ServerSession.connectionConsumerOnMessage(ServerSessio n.java:891)
at com.ibm.ejs.jms.listener.ServerSession.onMessage(ServerSession.java:656)
at com.ibm.ejs.jms.listener.ServerSession.dispatch(ServerSession.java:623)
at sun.reflect.GeneratedMethodAccessor79.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.ja va:43)
at java.lang.reflect.Method.invoke(Method.java:615)
at com.ibm.ejs.jms.listener.ServerSessionDispatcher.dispatch(ServerSessionDispatch er.java:37)
at com.ibm.ejs.container.MDBWrapper.onMessage(MDBWrapper.java:96)
at com.ibm.ejs.container.MDBWrapper.onMessage(MDBWrapper.java:132)
at com.ibm.ejs.jms.listener.ServerSession.run(ServerSession.java:481)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1473)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor42.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.ja va:43)
at java.lang.reflect.Method.invoke(Method.java:615)
at org.hibernate.transaction.WebSphereExtendedJTATransactionLookup$TransactionMana gerAdapter$TransactionAdapter.registerSynchronization(WebSphereExtendedJTATransa ctionLookup.java:225)
... 30 more
Caused by: com.ibm.websphere.jtaextensions.NotSupportedException
at com.ibm.ws.jtaextensions.ExtendedJTATransactionImpl.registerSynchronizationCall backForCurrentTran(ExtendedJTATransactionImpl.java:247)

... 34 more

Could any body help to shed come light on what com.ibm.websphere.jtaextensions.NotSupportedException means. The IBM documentation says

"The exception is thrown by the transaction manager if an attempt is made to register a SynchronizationCallback in an environment or at a time when this function is not available. "

Which to me sounds like the container is rejecting hibernates call to start a transaction. If anybody has any idea on why the container could be throwing the message please let me know.

Thanks in advance

Karl

答:
If you really need high load I would remove the Hibernate layer between your app and the database. Without Hibernate you have less moving parts and more control. </p>

<p>That is the only advice I can give you. </p>

OwnerDisplayName: Karl

Body:
If you really need high load I would remove the Hibernate layer between your app and the database. Without Hibernate you have less moving parts and more control.

That is the only advice I can give you.

OwnerDisplayName: tuinstoel


问:
firefox : why no change in my statusbar?
edit
I have a statusbar that can be used to enable and disable addons.

```<code>  <popupset>
  <menupopup id="inlinetransContextMenu" position="end_after">
    <image id="preficon" value="pref" />
    <menuitem id="translator-context-menuitem-preferences"
    label="preferences" onclick="alert('horay')" />
  </menupopup>
</popupset>

<!-- ========================================= -->
</code>```

答:
When you define:

```<code><menupopup id="inlinetransContextMenu" position="end_after">
    <image id="preficon" value="pref" />
    <menuitem id="translator-context-menuitem-preferences"
    label="preferences" onclick="alert('horay')" />
</menupopup>
</code>```

Your popup consists of two element, an image and a menuitem. Items in a popup a laid out vertically so the image is above the menu item.

If you want to associate the image with the menu item, you have to do it differently, as described in the documentation:

A menuitem as a property image which should hold the path to the icon. Furthermore you have to give the it the class menuitem-iconic for the icon to show up (it is a predefined style class (probably an XBL binding)):

image

  Type: image URL

  The URL of the image to appear on the element. If this attribute is empty or left out, no image appears. The position of the image is determined by the dir and orient attributes.

Note: The menuitem must have a class of menuitem-iconic for the image to appear.

So your definition should look like:

```<code><menupopup id="inlinetransContextMenu" position="end_after">
    <menuitem id="translator-context-menuitem-preferences"
              image="chrome://inlinetrans/skin/pref.png"
              class="menuitem-iconic"
              label="preferences"
              onclick="alert('horay')" />
</menupopup>
</code>```

I don't understand your other problem: why when I try to suppress the image on the statusbar is no change at all with my statusbar. What does suppress mean in this context? Do you want to remove the icon? Or change?

Update:

You have to set image and label as attributes:

```<code><statusbarpanel id="status-bar-intrans"
   context="inlinetransContextMenu"
   onclick="overlay.clickIcon(event)"
   onmouseover="var elmt=document.getElementById('status-bar-intrans');if ('enabled' == overlay.status) { elmt.tooltipText= 'inlinetrans dalam kondisi aktif';} else { elmt.tooltipText='inlinetrans dalam kondisi tidak aktif'; }">
   image="chrome://youraddon/skin/image.png"
   label="inlinetrans" />
</code>```

and change the attribute image. Or via src and CSS. It is all described in the documentation.

Body:
edit
I have a statusbar that can be used to enable and disable addons.

  <popupset>
  <menupopup id="inlinetransContextMenu" position="end_after">
    <image id="preficon" value="pref" />
    <menuitem id="translator-context-menuitem-preferences"
    label="preferences" onclick="alert('horay')" />
  </menupopup>
</popupset>

Body:
When you define:

<menupopup id="inlinetransContextMenu" position="end_after">
    <image id="preficon" value="pref" />
    <menuitem id="translator-context-menuitem-preferences"
    label="preferences" onclick="alert('horay')" />
</menupopup>

Your popup consists of two element, an image and a menuitem. Items in a popup a laid out vertically so the image is above the menu item.

If you want to associate the image with the menu item, you have to do it differently, as described in the documentation:

A menuitem as a property image which should hold the path to the icon. Furthermore you have to give the it the class menuitem-iconic for the icon to show up (it is a predefined style class (probably an XBL binding)):

image

  Type: image URL

  The URL of the image to appear on the element. If this attribute is empty or left out, no image appears. The position of the image is determined by the dir and orient attributes.

Note: The menuitem must have a class of menuitem-iconic for the image to appear.

So your definition should look like:

<menupopup id="inlinetransContextMenu" position="end_after">
    <menuitem id="translator-context-menuitem-preferences"
              image="chrome://inlinetrans/skin/pref.png"
              class="menuitem-iconic"
              label="preferences"
              onclick="alert('horay')" />
</menupopup>

I don't understand your other problem: why when I try to suppress the image on the statusbar is no change at all with my statusbar. What does suppress mean in this context? Do you want to remove the icon? Or change?

Update:

You have to set image and label as attributes:

<statusbarpanel id="status-bar-intrans"
   context="inlinetransContextMenu"
   onclick="overlay.clickIcon(event)"
   onmouseover="var elmt=document.getElementById('status-bar-intrans');if ('enabled' == overlay.status) { elmt.tooltipText= 'inlinetrans dalam kondisi aktif';} else { elmt.tooltipText='inlinetrans dalam kondisi tidak aktif'; }">
   image="chrome://youraddon/skin/image.png"
   label="inlinetrans" />

and change the attribute image. Or via src and CSS. It is all described in the documentation.


问:
AWS Device Farm fail to upload apk
I'm having a problem using AWS Device Farm, but the problem is that Amazon is not very specific on what goes wrong.

After I created a new run and try to upload my apk file it shows this message before getting to finish the upload:

There was a problem uploading your file. Please try again.

There are no error codes. I have already tried several times using a signed app for debug and for release, but neither of them finishes the upload. Is this a temporal problem in Amazon cloud or it is a known error?

答:
I work for the AWS Device Farm team.

Sorry to hear that you are running in to issues.

If it is the App that is giving you an error you should check if you are able to run the app locally on a real device. If yes, then this should be working on device farm. At times, app build for emulators/simulators are uploaded and can cause the error.

If it is the test apk that you are uploading then the same thing as point 1 should be confirmed.

If both of the points above are true and you are still getting an error please start a thread on AWS Device Farm forums and we can take a closer look at your runs or you can share your run url here and we can take a look.

Title: AWS Device Farm fail to upload apk


问:
ExtJS 4: How can I get all grid columns in current order?
When I use grid.columns it returns all columns from grid (visible or not), but it's not in current order..

Then I tried grid.getView().getGridColumns() and it returned the columns in current order, but only the visible ones.

How can I get all columns, visible and not visible, in current order?

答:
I had the opposite problem as I need only the visible ones. For all columns grid.columns seems like the easiest way (since 2.3). I then put them in a map by name because I needed to access row cells:</p>

```<code>var headerColumns = myGrid.columns;
var headerMap = {};
//put them in a map of name, index
Ext.each(headerColumns, function(headerColumn, i) {
  headerMap[headerColumn.dataIndex] = i;
});
</code>```

Body:
I had the opposite problem as I need only the visible ones. For all columns grid.columns seems like the easiest way (since 2.3). I then put them in a map by name because I needed to access row cells:

var headerColumns = myGrid.columns;
var headerMap = {};
//put them in a map of name, index
Ext.each(headerColumns, function(headerColumn, i) {
  headerMap[headerColumn.dataIndex] = i;
});


问:
How do you create a mongodb replica set or shard that is externally available in kubernetes?
I have followed tutorials and set up working mongodb replica sets however when it comes to exposing them as a service I am stuck with using a LoadBalancer which directs to any pod. In most cases this ends up being a secondary database and not terrible helpful. I have also managed to get separate mongodb replicas set up and then tried to connect to those externally however connections fail because internal replicaset ips are all through local google cloud dns.

What I am hoping for is something like this.

Then (potentially) there is a single connection uri that could connect you to your mongodb replicaset without needing individual mongodb connection details.

I'm not sure if this is possible but any help is greatly appreciated!

答:
If you configure a mongodb replica set with stateful sets, you should
 also create a headless service. Then you can connect to the replica set with a url like:

“mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/dbname_?”

Here mongo-0,mongo-1,mongo-2 are pod names and "mongo" is the headless service name.

If you still want to able to connect to a specific mongo instance, you can create separate service (of type=NodePort) for each of the deployment/replica and then you should be able to connect to a specific mongo instance using <any-node-ip>:<nodeport>
But you'll not be able to leverage the advantages of having a mongo replica set in this case.


问:
Can't Query Product Package Server Relational & Count Properties
In my Ruby script, I can't seem to get the Softlayer_Product_Package_Server relational properties from the SoftLayer API endpoint. My Ruby code:

```<code>packageServerList = client['SoftLayer_Product_Package_Server'].getAllObjects
packageServerList.each do |packageServer|
     packageServer['package']
end
</code>```

The packageServer['package'] just gives me a null object. Some of the other relations have the same issue ("brand", "catalog", "itemPrice"), but "item" seems to work. Taken from:

This is confusing because the REST request works and shows the data from a 'package' object mask.

答:
To get relational or/and count properties, it's necessary to use an Object Masks, please make the below change in your code:

```<code>packageServerList = client['SoftLayer_Product_Package_Server'].object_mask('mask[package, brand, caralog]').getAllObjects
</code>```

References:

Using Object Masks - Ruby

Body:
In my Ruby script, I can't seem to get the Softlayer_Product_Package_Server relational properties from the SoftLayer API endpoint. My Ruby code:

packageServerList = client['SoftLayer_Product_Package_Server'].getAllObjects
packageServerList.each do |packageServer|
     packageServer['package']
end

The packageServer['package'] just gives me a null object. Some of the other relations have the same issue ("brand", "catalog", "itemPrice"), but "item" seems to work. Taken from:

This is confusing because the REST request works and shows the data from a 'package' object mask.

Body:
To get relational or/and count properties, it's necessary to use an Object Masks, please make the below change in your code:

packageServerList = client['SoftLayer_Product_Package_Server'].object_mask('mask[package, brand, caralog]').getAllObjects

References:

Using Object Masks - Ruby


问:
Saving the number of equal notes in variables - Angular 2
I have an API that returns me a JSON with notes ranging from 1 to 5 and I need to store a quantity of equal notes in variables.

Example:

```<code>var n1 = 5; // Quantity of 10 notes with a value of 1 - [1,1,1,1,1]
var n2 = 3; // Quantity of 3 notes with a value of 2 - [2,2,2]
var n3 = 4; // Quantity of 4 notes with a value of 3 - [3,3,3,3]
</code>```

My JSON looks something like this:

```<code>[
  {
    "author": "Lorem ipsum",
    "note": "5",
    "description": "Lorem ipsum dolor sit amet"
  }
]
</code>```

And the code I use for this is this:

```<code>numNotas() {
  this.http.get(this.url).map(res => res.json())
    .subscribe(data => {
      console.log(data);
  });
}
</code>```

I tried to use something like console.log(data.note) to try to list only the numbers and I could try something to save the same notes in the respective variables, but the console returned me undefined. So how could I get these same notes and save them in the variables in a correct way?

答:
Try the following code after the .map() operation in your rxjs stream.

You may need to import the reduce operator with import 'ngrx/add/operators/reduce.

const json = [
  { note: "5" },
  { note: "5" },
  { note: "5" },
  { note: "3" },
  { note: "3" },
]

console.log(
  json
    .map(obj => parseInt(obj.note))
    .reduce((acc, val) => {
      acc[val]++
      return acc
    }, { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0})
)```

Body:
I have an API that returns me a JSON with notes ranging from 1 to 5 and I need to store a quantity of equal notes in variables.

Example:

var n1 = 5; // Quantity of 10 notes with a value of 1 - [1,1,1,1,1]
var n2 = 3; // Quantity of 3 notes with a value of 2 - [2,2,2]
var n3 = 4; // Quantity of 4 notes with a value of 3 - [3,3,3,3]

My JSON looks something like this:

[
  {
    "author": "Lorem ipsum",
    "note": "5",
    "description": "Lorem ipsum dolor sit amet"
  }
]

And the code I use for this is this:

numNotas() {
  this.http.get(this.url).map(res => res.json())
    .subscribe(data => {
      console.log(data);
  });
}

I tried to use something like console.log(data.note) to try to list only the numbers and I could try something to save the same notes in the respective variables, but the console returned me undefined. So how could I get these same notes and save them in the variables in a correct way?


问:
Printing float with chosen length in julia
When I save my data files, I have a parameter that it is a float, which I want to keep it as a float in the filename. I don't have round up errors, because I define the values of the parameter using

```<code>parameters = zeros(Float64, 1000)##50)
iijj = 4.8999
for jjj in 1:1000
    iijj += 1/10000
    iijj = round(iijj, 4)
    parameters[jjj] = iijj
end
</code>```

and thus every parameter[i] is a float with just 4decimals.
My issue comes when printing the files, I am using

```<code>printfile = open("outfile_param$(param).dat" ,"w")
</code>```

where param=parameters[i]. If I have for example 4.89, I would like to have the name outfile_param4.8900.dat, instead of outfile_param4.89.dat.

I know there are several ways to write in an outputfile, but I would like to keep the format that I have because if not it would be a pain to correct the programs that I work with.

答:
You can use @sprintf to have more precise control over the formatting:

```<code>julia> @sprintf("outfile_param%.4f.dat", 4.89)
"outfile_param4.8900.dat"
</code>```

Body:
When I save my data files, I have a parameter that it is a float, which I want to keep it as a float in the filename. I don't have round up errors, because I define the values of the parameter using

parameters = zeros(Float64, 1000)##50)
iijj = 4.8999
for jjj in 1:1000
    iijj += 1/10000
    iijj = round(iijj, 4)
    parameters[jjj] = iijj
end

and thus every parameter[i] is a float with just 4decimals.
My issue comes when printing the files, I am using

printfile = open("outfile_param$(param).dat" ,"w")

where param=parameters[i]. If I have for example 4.89, I would like to have the name outfile_param4.8900.dat, instead of outfile_param4.89.dat.

I know there are several ways to write in an outputfile, but I would like to keep the format that I have because if not it would be a pain to correct the programs that I work with.

Body:
You can use @sprintf to have more precise control over the formatting:

julia> @sprintf("outfile_param%.4f.dat", 4.89)
"outfile_param4.8900.dat"

ContentLicense: CC BY-SA 4.0


答:
It is the same meaning as .. in any path specification, i.e. the parent directory.
For example, C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/ corresponds to C:/mingw64/lib/gcc/x86_64-w64-mingw32/5.1.0/.

Title: format of gcc -print-search-dirs output

Body:
when run from the command line (win7 cmd) gcc -print-search-dirs produces:

install: C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/
programs: =C:/mingw64/bin/../libexec/gcc/x86_64-w64-mingw32/5.1.0/;C:/mingw64/bin/../libexec/gcc/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/x86_64-w64-mingw32/5.1.0/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/
libraries: =C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/;C:/mingw64/bin/../lib/gcc/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/x86_64-w64-mingw32/5.1.0/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/../lib/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../x86_64-w64-mingw32/5.1.0/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../lib/;C:/mingw510/x86_64-510-posix-seh-rt_v4-rev0/mingw64/mingw/lib/x86_64-w64-mingw32/5.1.0/;C:/mingw510/x86_64-510-posix-seh-rt_v4-rev0/mingw64/mingw/lib/../lib/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/;C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../;C:/mingw510/x86_64-510-posix-seh-rt_v4-rev0/mingw64/mingw/lib/`

I understand the semi-colons (like PATH) but I'm not clear on the /../ as shown. Could someone explain?


问:
C# how to enable button from another class
I have a form1, there's a "download" button, and a "next" button. By default, the "next" button is disabled. When I click "download" button, I will call a method from download.cs, different from form1.cs. After downloading, I want the "next" button to be enabled, so in download.cs, after receiving all files, I put

form1.btnNext.Enabled = true;

But it doesn't work. I also put this in form1.cs

public void enableButton(bool enabled)

{
     btnNext.Enabled = enabled;
  }

and in download.cs I put:

private form1 form1;
  ...

form1.enableButton(true);

but it doesn't work either. Could any1 show me where I'm wrong? thanks in advance.

答:
If you are freezing your UI while download than

1- Define a event in your Downloader class

```<code>    public delegate void EnableUI(bool shdEnable);

    public event EnableUI MakeUIEnabled;
</code>```

2- Hook this event in your form1 class , i assume that you are creating an object of download class in the download button or it is created at class level , lets say this object as customDownloader

```<code>   customDownloader.MakeUIEnabled+=new EnableUI(EnableUIControls);
</code>```

3- Define a event hander in form1 class as shown below.

```<code>  public void EnableUIControls(bool shdEnable)
    {
        btnNext.Enabled = shdEnable;

    }
</code>```

4- Let's sya that there is a downloadfile() method in download.cs file so when your download is completed than raise this event.

```<code>      public void DownLoadFile()
      {
          if(MakeUIEnabled!=null)
             MakeUIEnabled(true);

      }
</code>```

tha's it

Body:
If you are freezing your UI while download than

1- Define a event in your Downloader class

    public delegate void EnableUI(bool shdEnable);

    public event EnableUI MakeUIEnabled;

2- Hook this event in your form1 class , i assume that you are creating an object of download class in the download button or it is created at class level , lets say this object as customDownloader

   customDownloader.MakeUIEnabled+=new EnableUI(EnableUIControls);

3- Define a event hander in form1 class as shown below.

  public void EnableUIControls(bool shdEnable)
    {
        btnNext.Enabled = shdEnable;

    }

4- Let's sya that there is a downloadfile() method in download.cs file so when your download is completed than raise this event.

      public void DownLoadFile()
      {
          if(MakeUIEnabled!=null)
             MakeUIEnabled(true);

      }

tha's it