问:
How to change a text based onclick with JavaScript?
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

```<code><p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func();">ES</a> - <a href="#" id="EN" onclick="func();">EN</a> - <a href="#" id="JP" onclick="func();">JP</a>
</code>```

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

答:
```<code>// Using JavaScript

// Firstly we get the demo element
var demo = document.getElementById("demo");

// When an element on the document si clicked
document.onclick = function(event)

// if the target element has an id of "ES" change demo content to spanish
    if (event.target.id == "ES") {
    demo.innerHTML = "Spanish or EspagnolText";

  } else if (event.target.id == "EN") {

// else if element has an id of "EN" change demo content to english
    demo.innerHTML = "English Text";
  }
}
</code>```

Body:
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

This message should be edited.

ES - EN - JP

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).


来源: stackexchange

问:
Any advice for speeding up the compile time in Flex Builder 3?
I run Flex Builder 3 on a mac and as my project grows - the compile time gets longer and longer and longer.  I am using some SWC's and there is a fair amount of code but it shouldn't take minutes to build and crash daily should it?</p>

答:
Usually the first build takes the longest, and then it's pretty quick after that. That's using Vista x64 w/ core 2 duo.

Otherwise, I am nearly certain a Intel Core i7 Extreme Edition 965 3.2GHz upgrade processor would speed your Flex building up nicely .. :) :) :)

OwnerDisplayName: onekidney

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: travis

OwnerDisplayName: Scott Evernden


问:
In spring Oauth 2 authorization server Implementation , how to return an authorization code after user sign up
Normally ,the client redirect to Oauth server ,with client id

```<code>http://localhost:8181/sparklr2/oauth/authorize?response_type=code&client_id=tonr-with-redirect&state=xyz
</code>```

the login page is displayed ,after proper credentials are received and authenticated ,confirmation is not call back done to client with authorization code

```<code>http://localhost:9090/tonr2/sparklr/redirect?code=gm4XN3&state=xyz
</code>```

If the user is not registered and sign up need to be done ,then how to generate a authorization code after sign up with out login

答:
I think this is a general question for Spring security, what you want is a login flow which supports signup and generates a complete authentication at the end of the signup flow.

So you will have to create a custom login form flow that offers signup and then completes the authentication at the end of the signup flow.

If you do this properly Spring oauth should take over and continue the redirect flow just as if you signed on the normal way.

ContentLicense: CC BY-SA 3.0

Body:
Normally ,the client redirect to Oauth server ,with client id

http://localhost:8181/sparklr2/oauth/authorize?response_type=code&client_id=tonr-with-redirect&state=xyz

the login page is displayed ,after proper credentials are received and authenticated ,confirmation is not call back done to client with authorization code

http://localhost:9090/tonr2/sparklr/redirect?code=gm4XN3&state=xyz

If the user is not registered and sign up need to be done ,then how to generate a authorization code after sign up with out login


问:
Itext 7 overriding default margin in pdfHtml
I have html content that has to start at the absolute top left corner of the page. However, the HtmlConverter automatically adds a 0.5in gap from the top and left side of the pdf page. How do I override this default margin?</p>

答:
You can set the margins of a page through CSS using @page. The following declaration sets all the page-margins to 0, as well as draws a border around paragraphs for visual reference:

```<code>@page{
    margin:0pt;
}
p{
    border-left: solid 2pt blue;
    border-top: solid 1pt blue;
    border-bottom: solid 1pt blue;
}
</code>```

Use the following as input:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>margin example</title>
    <link href="margin.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div>
        <p>This page should have the margins set at 0</p>
    </div>
</body>
</html>
</code>```

And you'll see that the paragraph's border is touching the left side of the page, but not yet the top side. That's because the paragraph has some innate margin as a blockelement as well. Setting this to 0 will do the trick:

```<code>p{
    border-left: solid 2pt blue;
    border-top: solid 1pt blue;
    border-bottom: solid 1pt blue;
    margin-top: 0pt;
}

@page{
    margin:0pt;
}
</code>```

And the output:

Body:
You can set the margins of a page through CSS using @page. The following declaration sets all the page-margins to 0, as well as draws a border around paragraphs for visual reference:

@page{
    margin:0pt;
}
p{
    border-left: solid 2pt blue;
    border-top: solid 1pt blue;
    border-bottom: solid 1pt blue;
}

Use the following as input:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>margin example</title>
    <link href="margin.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div>
        <p>This page should have the margins set at 0</p>
    </div>
</body>
</html>

And you'll see that the paragraph's border is touching the left side of the page, but not yet the top side. That's because the paragraph has some innate margin as a blockelement as well. Setting this to 0 will do the trick:

p{
    border-left: solid 2pt blue;
    border-top: solid 1pt blue;
    border-bottom: solid 1pt blue;
    margin-top: 0pt;
}

@page{
    margin:0pt;
}

And the output:


问:
How do you disable the datepicker in Microsoft Edge?
I have several inputs with type="date" and want to disable the default date picker in Microsoft Edge since I'm using jQuery's datepicker. How do I disable this using CSS or JavaScript? It works fine in Chrome and Firefox but not Edge.

A working JSFiddle

HTML

```<code><script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>

<input type="date">
</code>```

JS

```<code>$(document).ready(function() {
    if (!Modernizr.inputtypes.date || $(window).width() >= 900) {
        $('input[type=date]').datepicker();
    }
});

$(window).resize(function() {
    if (!Modernizr.inputtypes.date || $(window).width() >= 900) {
        $('input[type=date]').datepicker();
    }
    else {
        $('input[type=date]').datepicker("destroy");
    }
});
</code>```

CSS

```<code>input[type=date]::-webkit-inner-spin-button, input[type=date]::-webkit-calendar-picker-indicator  {
    display: none;
    -webkit-appearance: none;
}
</code>```

答:
The input type must be text and not date. This...

```<code><input type="date" />
</code>```

Should be

```<code><input type="text" />
</code>```

Otherwise Chrome and Edge will add a datepicker. Instead use a class or id to identify it as datepicker and do something like $(".datepicker").datepicker();

ContentLicense: CC BY-SA 4.0

Body:
I have several inputs with type="date" and want to disable the default date picker in Microsoft Edge since I'm using jQuery's datepicker. How do I disable this using CSS or JavaScript? It works fine in Chrome and Firefox but not Edge.

A working JSFiddle

HTML

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

<input type="date">

JS

$(document).ready(function() {
    if (!Modernizr.inputtypes.date || $(window).width() >= 900) {
        $('input[type=date]').datepicker();
    }
});

$(window).resize(function() {
    if (!Modernizr.inputtypes.date || $(window).width() >= 900) {
        $('input[type=date]').datepicker();
    }
    else {
        $('input[type=date]').datepicker("destroy");
    }
});

CSS

input[type=date]::-webkit-inner-spin-button, input[type=date]::-webkit-calendar-picker-indicator  {
    display: none;
    -webkit-appearance: none;
}

Body:
The input type must be text and not date. This...

<input type="date" />

Should be

<input type="text" />

Otherwise Chrome and Edge will add a datepicker. Instead use a class or id to identify it as datepicker and do something like $(".datepicker").datepicker();


问:
Wrong calculation in the sum of the value of dynamic columns with delete
I am trying to create a restaurant order form where in i input the values on textboxes and will display on the list with the subtotals and total after button click using Ajax.

my problem is that the sum of the subtotals gives me wrong value
and doesnt change if i click the delete button.

| qty | price|subtotal |

| 10 | 3.50  | 35.00 |

| 10 | 9.00  | 90.00 |

Total : 180.00  instead of 125.00

wherein it calculated the number of rows x last subtotal value.

Please see the code snippet attached TIA!

var impo = document.getElementById("imp_text");
var quant = document.getElementById("qta");

$(document).on("click", "table.dynatable button.delete-row", function() {
  $(this).parents("tr").remove();
});

function loaddata() {
  var importo = $("#imp_text").val();
  var quantita = $("#qta").val();
  var totale = importo * quantita;
  var desc_importo = "Altro ";
  var markup = "
" + quantita + "	" + desc_importo + "	" + importo + "	" + totale + "	<button type='button' class='delete-row'>X</button>
";

  $("table.dynatable tbody").append(markup);

  var $tblrows = $("#tableordine tbody tr");
  $tblrows.each(function(index) {
    var $tblrow = $(this);

    if (!isNaN(totale)) {

      $tblrow.find('.subtot').val(totale.toFixed(2));
      var grandTotal = 0;

      $(".subtot").each(function() {
        var stval = parseFloat($(this).val());
        grandTotal += isNaN(stval) ? 0 : stval;
      });

      $('.grdtot').val(grandTotal.toFixed(2));
    }

  });
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">

<head>
</head>

<body>
  <font color="black">

    <table class="table dynatable" id="tableordine">
      <thead>
        <tr>
          <th>Qty</th>
          <th>Import</th>
          <th>Price</th>
          <th>subtotal</th>
        </tr>
      </thead>
      <tbody>

      </tbody>
    </table>

    <hr/> Totale:<input type="text" class="grdtot">

<hr/>
    <FORM name="Keypad" action="">
      Import : <input name="ReadOut" id="imp_text" type="Text" size=24 value=" "> Quantity : <input type="text" name="readqta" id="qta" value="1" />
      <p>

        <input type="button" id="entraordine" class="add-row menu_button" value="Entra" onclick="loaddata();" />
    </form>
</body>
</html></code>```

答:
Here you go with the solution https://jsfiddle.net/tbskqrby/</p>

```<code>$(document).on("click", "table.dynatable button.delete-row", function() {
    $(this).parents("tr").remove();
    rowCal();
});

rowCal = function(){
    var $tblrows = $("#tableordine tbody tr");
    $tblrows.each(function(index) {
        var $tblrow = $(this);

        if (!isNaN(totale)) {

            $tblrow.find('.subtot').val(totale.toFixed(2));
            var grandTotal = 0;

            $(".subtot").each(function() {
                var stval = parseFloat($(this).val());
                grandTotal += isNaN(stval) ? 0 : stval;
            });

            $('.grdtot').val(grandTotal.toFixed(2));
       }

   });
}
</code>```

Body:
I am trying to create a restaurant order form where in i input the values on textboxes and will display on the list with the subtotals and total after button click using Ajax.

my problem is that the sum of the subtotals gives me wrong value
and doesnt change if i click the delete button.

| qty | price|subtotal |

| 10 | 3.50  | 35.00 |

| 10 | 9.00  | 90.00 |

Total : 180.00  instead of 125.00

wherein it calculated the number of rows x last subtotal value.

Please see the code snippet attached TIA!

var impo = document.getElementById("imp_text");
var quant = document.getElementById("qta");

$(document).on("click", "table.dynatable button.delete-row", function() {
  $(this).parents("tr").remove();
});

function loaddata() {
  var importo = $("#imp_text").val();
  var quantita = $("#qta").val();
  var totale = importo * quantita;
  var desc_importo = "Altro ";
  var markup = "
" + quantita + "	" + desc_importo + "	" + importo + "	" + totale + "	<button type='button' class='delete-row'>X</button>
";

  $("table.dynatable tbody").append(markup);

  var $tblrows = $("#tableordine tbody tr");
  $tblrows.each(function(index) {
    var $tblrow = $(this);

    if (!isNaN(totale)) {

      $tblrow.find('.subtot').val(totale.toFixed(2));
      var grandTotal = 0;

      $(".subtot").each(function() {
        var stval = parseFloat($(this).val());
        grandTotal += isNaN(stval) ? 0 : stval;
      });

      $('.grdtot').val(grandTotal.toFixed(2));
    }

  });
  }

          Qty
          Import
          Price
          subtotal

 Totale:<input type="text" class="grdtot">

    <FORM name="Keypad" action="">
      Import : <input name="ReadOut" id="imp_text" type="Text" size=24 value=" "> Quantity : <input type="text" name="readqta" id="qta" value="1" />

        <input type="button" id="entraordine" class="add-row menu_button" value="Entra" onclick="loaddata();" />
    </form>

Body:
Here you go with the solution https://jsfiddle.net/tbskqrby/

$(document).on("click", "table.dynatable button.delete-row", function() {
    $(this).parents("tr").remove();
    rowCal();
});

rowCal = function(){
    var $tblrows = $("#tableordine tbody tr");
    $tblrows.each(function(index) {
        var $tblrow = $(this);

        if (!isNaN(totale)) {

            $tblrow.find('.subtot').val(totale.toFixed(2));
            var grandTotal = 0;

            $(".subtot").each(function() {
                var stval = parseFloat($(this).val());
                grandTotal += isNaN(stval) ? 0 : stval;
            });

            $('.grdtot').val(grandTotal.toFixed(2));
       }

   });
}


问:
Random number generator that returns unique entries in sorted order
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

```<code>public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541
</code>```

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

答:
You want a lot of pseudo-random 64 bit numbers, all unique.  Given unique inputs and the same key, encryption is unique -- it has to be because it is reversible.  DES is a 64-bit block cipher, so encrypting the numbers 0, 1, 2, 3, 4, ...  10^12 in DES with ECB mode will give you a trillion unique 64-bit numbers.  With the same key they are guaranteed unique because the inputs are unique.  A different key will given a different set of unique numbers, but some may be duplicates of numbers in the first set.

For 128 bit numbers use AES, which has a 128 bit block size, again in ECB mode and with a fixed key.

The only internal state needed is the key you are using and a single number indicating how far you have got in the [0..10^12] range.

You will need to sort the output separately.  Given the ease of restarting the process from the stored last number to generate the next batch of numbers, I suspect that a merge-sort would be relatively easy to implement, with each new batch being merged into the already sorted main file as you produce it.  Batch sizes can be kept to within memory capacity, with the major file being held on disc.

This solution does not use java.util.Random.  How important is that for you?  Encryption is designed to appear random to all but the most sophisticated cryptographic analysis and is probably 'more random' than the standard Java Random PRNG.

Body:
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.


问:
Can't handle large integers in Python 3
I'm trying to implement a very simple RSA algorithm, when I choose 2 primes larger than 3 digits and when I try to decrypt the message my IDE freezes and I thought because of it being a bigInt so I've waited for like 10 min and nothing did happen.

Here's my code:

```<code>def gcd (m,n):
if (m%n ==0):
    return n
else:
    return gcd(n,m%n)

def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
          lastremainder, (quotient, remainder) = remainder,      divmod(lastremainder, remainder)
    x, lastx = lastx - quotient*x, x
    y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
    raise ValueError
return x % m
p = 9883
q = 9887
n = p*q
phi = (p-1)*(q-1)
e = 509

    m = 320

    d = modinv(e,phi)
    c = (pow(m,e)%n)
    msg = pow(c,d) % n ## MY IDE FREEZES WHEN IT REACHES THIS LINE! SURE OF IT
    print(msg)
</code>```

答:
Your line :

```<code>c = (pow(m,e)%n)
</code>```

should be :

```<code>c = (pow(m,e,n))
</code>```

As per the official documentation, this is a much more efficient approach to computing modulo over a large number

EDIT : same thing goes for :

```<code>msg = pow(c,d) % n
</code>```

Which becomes :

```<code>msg = pow(c,d, n)
</code>```

Regarding the size, Python is actually very smart with integers, and will switch the internal representation if a number become too big to fit in a traditional integer. Thus size is often not a concern

Title: Can't handle large integers in Python 3

Body:
I'm trying to implement a very simple RSA algorithm, when I choose 2 primes larger than 3 digits and when I try to decrypt the message my IDE freezes and I thought because of it being a bigInt so I've waited for like 10 min and nothing did happen.

Here's my code:

def gcd (m,n):
if (m%n ==0):
    return n
else:
    return gcd(n,m%n)

def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
          lastremainder, (quotient, remainder) = remainder,      divmod(lastremainder, remainder)
    x, lastx = lastx - quotient*x, x
    y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
    raise ValueError
return x % m
p = 9883
q = 9887
n = p*q
phi = (p-1)*(q-1)
e = 509

    m = 320

    d = modinv(e,phi)
    c = (pow(m,e)%n)
    msg = pow(c,d) % n ## MY IDE FREEZES WHEN IT REACHES THIS LINE! SURE OF IT
    print(msg)

Body:
Your line :

c = (pow(m,e)%n)

should be :

c = (pow(m,e,n))

As per the official documentation, this is a much more efficient approach to computing modulo over a large number

EDIT : same thing goes for :

msg = pow(c,d) % n

Which becomes :

msg = pow(c,d, n)

Regarding the size, Python is actually very smart with integers, and will switch the internal representation if a number become too big to fit in a traditional integer. Thus size is often not a concern


问:
FullCalendar Custom/Override Header title
I want change the titleFormat of my calendar.

At present, the title is in an h2 tag and we cannot personalize it by adding html code to the titleFormat option.
For example put a span tag on my fixed value of the titleFormat (which is [] there).

I would want to know if it is possible to override the updateTitle method of the class Header, without modifying fullcalendar.js. Or another possibility.

I have 2 views : week with title format '[Semaine] W' and custom one Day with title format 'dddd D MMMM YYYY'.

My version of FullCalendar is v2.3.0.

答:
A simple way is to overwrite the view.title within the viewRender event:

```<code>...
,
header: {
  center: 'title',
},
viewRender: function(view, element) {
  view.title = 'Your Custom Title';
},
...
</code>```

Body:
A simple way is to overwrite the view.title within the viewRender event:

...
,
header: {
  center: 'title',
},
viewRender: function(view, element) {
  view.title = 'Your Custom Title';
},
...


问:
Parse Server REST API - Group by and Sum
Is it possible to group by and sum values using the Parse Server REST API.

e.g. https://parseapi.back4app.com/classes/myclass?groupby=name&sum=score

If i have a table of 100k rows i would not like to let the client download all the result in order to perform a sum of the values.

Example Source:

```<code>name    | score
frank   | 50
frank   | 20
ben     | 30
</code>```

Result:

```<code>name    | score
frank   | 70
ben     | 30
</code>```

答: Groups and sum are not implemented as the backing database in mongodb and this falls into the aggregation pipelines. We’re currently looking into it for groups. </p>

Body:
Is it possible to group by and sum values using the Parse Server REST API.

e.g. https://parseapi.back4app.com/classes/myclass?groupby=name&sum=score

If i have a table of 100k rows i would not like to let the client download all the result in order to perform a sum of the values.

Example Source:

name    | score
frank   | 50
frank   | 20
ben     | 30

Result:

name    | score
frank   | 70
ben     | 30


问:
Check @RequestMapping - unit test
I have a task to do:
This controller should have its own unit test to verify, that @RequestMapping is set to / api / report / article_pairs.

```<code> @RestController
 @RequestMapping("/api/report/article_pairs")
 public class ArticlePairsController extends ReportController<ArticlePairs>{

public ArticlePairsController(HttpReportExecutor<ArticlePairs> articlePairs) {
    super(articlePairs);
}

@PostMapping()
public HttpEntity<Void> proceed(@RequestBody ArticlePairs articlePairs) {

    articlePairs.setDbconn(schemaName + "." + CENTRALA);

    return executeReport(articlePairs, "report.articlePairs");
  }
}
</code>```

If someone in the future would change this value, a unit test should show this.

Unit testing is a new issue for me, so could I ask for some advice? thank you in advance.

答:
You have not stated which version of Spring you are using, but if it is greater than 3.2 you could set up a simple unit test that ONLY tests a given Controller and not the whole context as follows:</p>

```<code>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringJUnit4ClassRunner.class)
public class SitemapControllerTest {

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders.standaloneSetup(SitemapControllerTest.class).build();
    }

    @Test
    public void testHappyPath() throws Exception {

        mvc.perform(post("/api/report/article_pairs")
                .content("{yourjsoncontent}")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}
</code>```

Title: Check @RequestMapping - unit test

Body:
I have a task to do:
This controller should have its own unit test to verify, that @RequestMapping is set to / api / report / article_pairs.

 @RestController
 @RequestMapping("/api/report/article_pairs")
 public class ArticlePairsController extends ReportController<ArticlePairs>{

public ArticlePairsController(HttpReportExecutor<ArticlePairs> articlePairs) {
    super(articlePairs);
}

@PostMapping()
public HttpEntity<Void> proceed(@RequestBody ArticlePairs articlePairs) {

    articlePairs.setDbconn(schemaName + "." + CENTRALA);

    return executeReport(articlePairs, "report.articlePairs");
  }
}

If someone in the future would change this value, a unit test should show this.

Unit testing is a new issue for me, so could I ask for some advice? thank you in advance.

Body:
You have not stated which version of Spring you are using, but if it is greater than 3.2 you could set up a simple unit test that ONLY tests a given Controller and not the whole context as follows:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringJUnit4ClassRunner.class)
public class SitemapControllerTest {

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders.standaloneSetup(SitemapControllerTest.class).build();
    }

    @Test
    public void testHappyPath() throws Exception {

        mvc.perform(post("/api/report/article_pairs")
                .content("{yourjsoncontent}")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}


问:
shiny app with module as a package
I'm trying to create a package of a shiny app organized with module. I can't find any help, every example which i can find doesn't use module. Someone can give me an example ?</p>

答:
You will have to make sure the ui part as well as the server part of the module get exported in your package

```<code>#' @export
myModuleUI <- function(id){
  ns = NS(id)
  plotOutput(ns("plot"))
}

#' @export
myModuleServer <- function(input, output, session){
  output$plot <- renderPlot({hist(rnorm(100))})
}
</code>```

From the script that loads your packae you can then use

```<code>library(myPackage)

shinyApp(
  fluidPage(myModuleUI("someId")),
  function(input,output,session){
    callModule(myModuleServer, "someId")
  }
)
</code>```

When it comes to documenting your modules, there is no standard way of doing this. Most packages use a minimal function-like documentation together with an example app -- see the answer of Joris Meys.

Title: shiny app with module as a package

Body:
You will have to make sure the ui part as well as the server part of the module get exported in your package

#' @export
myModuleUI <- function(id){
  ns = NS(id)
  plotOutput(ns("plot"))
}

#' @export
myModuleServer <- function(input, output, session){
  output$plot <- renderPlot({hist(rnorm(100))})
}

From the script that loads your packae you can then use

library(myPackage)

shinyApp(
  fluidPage(myModuleUI("someId")),
  function(input,output,session){
    callModule(myModuleServer, "someId")
  }
)

When it comes to documenting your modules, there is no standard way of doing this. Most packages use a minimal function-like documentation together with an example app -- see the answer of Joris Meys.


问:
Creating a new dataframe with only 1 row per value
I am trying to fill a pandas dataframe (Dataframe 2) with rows from an original dataframe (Dataframe 1). I've created a mock Dataframe 1 below:

```<code>Ref Number  Name
1           Alpha
2           Alpha
3           Alpha
4           Alpha
5           Beta
6           Beta
7           Beta
8           Charlie
</code>```

I want to delete rows where the value Name has occurred in previous rows. I.e. Dataframe 2 should look like

```<code>Ref Number  Name
1           Alpha
5           Beta
8           Charlie
</code>```

The Ref Number doesn't matter in this instance. In my working files, I'm planning on adding a column to specify something, and then to refer to that when applying some function.

How would I go about this with Pandas? I've got a CSV with ~5000 rows and I want to limit that to a 2nd dataframe with ~1000.

答:
Use drop_duplicates with specifying column Name for find duplicates:

```<code>df = df.drop_duplicates('Name')
print (df)
   Ref Number     Name
0           1    Alpha
4           5     Beta
7           8  Charlie
</code>```

Body:
I am trying to fill a pandas dataframe (Dataframe 2) with rows from an original dataframe (Dataframe 1). I've created a mock Dataframe 1 below:

Ref Number  Name
1           Alpha
2           Alpha
3           Alpha
4           Alpha
5           Beta
6           Beta
7           Beta
8           Charlie

I want to delete rows where the value Name has occurred in previous rows. I.e. Dataframe 2 should look like

Ref Number  Name
1           Alpha
5           Beta
8           Charlie

The Ref Number doesn't matter in this instance. In my working files, I'm planning on adding a column to specify something, and then to refer to that when applying some function.

How would I go about this with Pandas? I've got a CSV with ~5000 rows and I want to limit that to a 2nd dataframe with ~1000.

Body:
Use drop_duplicates with specifying column Name for find duplicates:

df = df.drop_duplicates('Name')
print (df)
   Ref Number     Name
0           1    Alpha
4           5     Beta
7           8  Charlie


问:
Set toolbar title
I am trying to set my toolbar title like so:

```<code>public class StatisticsPage extends Fragment  {

    public StatisticsPage(){}
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.statistics_pagelayout, container, false);

        Spinner spinner = (Spinner) rootView.findViewById(R.id.statsSpin);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.statspage, R.layout.dropdown_item);
        spinner.setAdapter(adapter);
        getSupportActionBar().setTitle("My title");

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                switch (position) {
                    case 0:
                        break;
                    case 1:
                        // do whatever stuff you wanna do here
                        Fragment Fragment_one;
                        FragmentManager man= getActivity().getSupportFragmentManager();
                        FragmentTransaction tran = man.beginTransaction();
                        Fragment_one = new BreweryStatistics();
                        tran.replace(R.id.main, Fragment_one);//tran.
                        tran.addToBackStack(null);
                        tran.commit();
                        break;
                    case 2:
                        Fragment Fragment_two;
                        FragmentManager mantwo= getActivity().getSupportFragmentManager();
                        FragmentTransaction trantwo = mantwo.beginTransaction();
                        Fragment_two = new StyleStatistics();
                        trantwo.replace(R.id.main, Fragment_two);//tran.
                        trantwo.addToBackStack(null);
                        trantwo.commit();
                        break;
                    case 3:
                        Fragment Fragment_three;
                        FragmentManager manthree= getActivity().getSupportFragmentManager();
                        FragmentTransaction tranthree = manthree.beginTransaction();
                        Fragment_three = new TasteStatisticsPage();
                        tranthree.replace(R.id.main, Fragment_three);//tran.
                        tranthree.addToBackStack(null);
                        tranthree.commit();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);
        String url = "myURL";
        String userURLComp = "u=" + userID;

        url = url + userURLComp ;

        new getBasicStats(getActivity()).execute(url);

        return rootView;
    }
}
</code>```

Basically this line in the above code does not work in the fragment:

```<code>getSupportActionBar().setTitle("My title");
</code>```

Also How can I stop my app title from showing up in the app bar? I would also like to make the title white when I can set it.

答: The best and easiest way to do this, is to go to Android Manifest and change the label within the Activity section. This is what's responsible for labelling the Activity along the toolbar. This saves you writing lines of code in the class file.

Title: Set toolbar title

Body:
I am trying to set my toolbar title like so:

public class StatisticsPage extends Fragment  {

    public StatisticsPage(){}
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.statistics_pagelayout, container, false);

        Spinner spinner = (Spinner) rootView.findViewById(R.id.statsSpin);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.statspage, R.layout.dropdown_item);
        spinner.setAdapter(adapter);
        getSupportActionBar().setTitle("My title");

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                switch (position) {
                    case 0:
                        break;
                    case 1:
                        // do whatever stuff you wanna do here
                        Fragment Fragment_one;
                        FragmentManager man= getActivity().getSupportFragmentManager();
                        FragmentTransaction tran = man.beginTransaction();
                        Fragment_one = new BreweryStatistics();
                        tran.replace(R.id.main, Fragment_one);//tran.
                        tran.addToBackStack(null);
                        tran.commit();
                        break;
                    case 2:
                        Fragment Fragment_two;
                        FragmentManager mantwo= getActivity().getSupportFragmentManager();
                        FragmentTransaction trantwo = mantwo.beginTransaction();
                        Fragment_two = new StyleStatistics();
                        trantwo.replace(R.id.main, Fragment_two);//tran.
                        trantwo.addToBackStack(null);
                        trantwo.commit();
                        break;
                    case 3:
                        Fragment Fragment_three;
                        FragmentManager manthree= getActivity().getSupportFragmentManager();
                        FragmentTransaction tranthree = manthree.beginTransaction();
                        Fragment_three = new TasteStatisticsPage();
                        tranthree.replace(R.id.main, Fragment_three);//tran.
                        tranthree.addToBackStack(null);
                        tranthree.commit();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);
        String url = "myURL";
        String userURLComp = "u=" + userID;

        url = url + userURLComp ;

        new getBasicStats(getActivity()).execute(url);

        return rootView;
    }
}

Basically this line in the above code does not work in the fragment:

getSupportActionBar().setTitle("My title");

Also How can I stop my app title from showing up in the app bar? I would also like to make the title white when I can set it.


问:
IOS application, ID bundle errors on XCode
I created an application with the Ionic Framework that allows me to make hybrid applications.
When I open my project on XCode, I have errors from XCode that I can not solve.

My errors are:

"Automatic signing is unable to resolve an issue with the target's
entities file"

"Provisioning profile ios team provisioning profile * doesn't include the aps-environment entitlement "

"Code signing is required for product type 'Application' in SDK 'iOS 10.3' "

I think the ID bundle has a mistake, however, I do not understand how to solve it.
How do I create a correct ID bundle without going through the project creation box since mine is already creating basic? (My ID bundle was generated by the global application's in the config.xml file)

Is it necessary to have a paid developer account to be able to create one? Or can I test my app simply on my phone?

Thanks in advance!

答:
These errors you are getting because of the no Provisioning profile & Developer Certificate.
To Brief of what is provisioning profile & Developer certificates are, These are security certificates providing by Apple to make sure that the iOS application is built by identified developer.

If you see there is a check mark: "Automatically manage signing" on.
  Because of that, it's trying to create provisioning profiles and
  certificates automatically without any proper apple membership
  account. That results in an error.

To run on a device, you don't need to have paid account. Any Apple ID will work. You need to have at least normal Apple ID and have to put any random bundle identifier there to run on your iPhone. (You can follow this link to How to run on iPhone without certificates)

Answering another question of yours: Yes, it's required to have Apple paid account to create a Bundle identifier. Even if you test it now on iPhone using above trick, to distribute in future to AppStore you need one.


问:
replace document in IE modal dialog
Browser : IE6/IE7.

I want to load a new document into my html modal dialog, either via a form target or a javascript function.

```<code><html> <!-- quirks mode -->
<head>
<script>
function openModal(url) {
    if(window.showModalDialog)  showModalDialog(url);
    else {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
            open(url, "", "modal=yes");
        } catch (e) {
            alert("dialog windows unsupported by browser");
        }
    }
}
</script>
</head>
<body style="background:red" onload="setTimeout(function(){document.body.style.backgroundColor='white'},100)">
<a href="javascript:openModal(location.href)">Open Modal</a>
<form>
<input type="submit" value="Send Form" />
</form>
<a href="javascript:location.reload()">Reload content</a>
</body>
</html>
</code>```

In Gecko-based browsers, it works.

In IE, when in the modal dialog window, the form opens a new window (even if I specify the target="_self" attribute), and the javascript reload() fails silently. If I try to do a location.replace(location.href) or location.href=_someurl_, it opens a new window.

So my question : how can I get IE to replace the current document in a modal dialog window?

答:
I just run into the same problem with Internet Explorer 8, so after playing around with it for a while it seems that there are some solutions such as

```<code>location.reload();return false;
</code>```

or

```<code>window.location = window.location;
</code>```

or

```<code>window.location.reload(true);
</code>```

However, none of them work for me - either nothing happens, or, best case, a new window opens.

What I've come up with as some kind of workaround is to use

```<code>document.forms[0].submit();
</code>```

It may not work for all constellations as you need a form on your page (and make sure that the form submission does not perform any unwanted changes), but it worked for me. Also make sure that you don't forget to put the

```<code><base target="_self" />
</code>```

into the header of your page as described by Alsciende.

HTH

G.

Title: replace document in IE modal dialog

Body:
Browser : IE6/IE7.

I want to load a new document into my html modal dialog, either via a form target or a javascript function.

Open Modal
<form>
<input type="submit" value="Send Form" />
</form>
Reload content

In Gecko-based browsers, it works.

In IE, when in the modal dialog window, the form opens a new window (even if I specify the target="_self" attribute), and the javascript reload() fails silently. If I try to do a location.replace(location.href) or location.href=_someurl_, it opens a new window.

So my question : how can I get IE to replace the current document in a modal dialog window?

Body:
I just run into the same problem with Internet Explorer 8, so after playing around with it for a while it seems that there are some solutions such as

location.reload();return false;

or

window.location = window.location;

or

window.location.reload(true);

However, none of them work for me - either nothing happens, or, best case, a new window opens.

What I've come up with as some kind of workaround is to use

document.forms[0].submit();

It may not work for all constellations as you need a form on your page (and make sure that the form submission does not perform any unwanted changes), but it worked for me. Also make sure that you don't forget to put the

<base target="_self" />

into the header of your page as described by Alsciende.

HTH

G.


问:
Check uploaded image's dimensions
I'm using asp.net 3.5 and c# on my web site. Here is my question:

I have an upload button and asp:Image on a page. An user can upload an image from his computer and that image will be displayed in the asp:image. But before I display the image, I would like to check the width and height of the uploaded image. How do I do this?

答:
Try this.

```<code>              public boolean CheckImgDimensions(string imgPath, int ValidWidth , int ValidHeight){

                 var img = Image.FromFile(Server.MapPath(imgPath));

                 return (img.width == ValidWidth &&  img.height == ValidHeight );
                }
</code>```

Use:

```<code>if ( CheckImgDimensions("~/Content/img/MyPic.jpg",128,128) ){
     /// what u want
  }
</code>```

Title: Check uploaded image's dimensions

Body:
Try this.

              public boolean CheckImgDimensions(string imgPath, int ValidWidth , int ValidHeight){

                 var img = Image.FromFile(Server.MapPath(imgPath));

                 return (img.width == ValidWidth &&  img.height == ValidHeight );
                }

Use:

if ( CheckImgDimensions("~/Content/img/MyPic.jpg",128,128) ){
     /// what u want
  }


问:
PHP silex Formbuilder and object with array of object
I am using PHP with the Silex framework and after some hours trying to find a satisfying solution I am still blocked with the following problem regarding forms and objects containing array of Objects. The hours spent permitted me to find a working solution but I hope there is a better way to do that with Silex.

In my application I have a User class that is defined like :

```<code>class User implements UserInterface
{
    private $id;
    private $username;
    private $displayname;
    private $capacities;
    //...
}
</code>```

$capacities variable contains an array of objects from another class (Capacity). A Capacity is a specific role in my app with various information (label, place of the capacity ...) and I have added, in that Capacity class a boolean telling if the Capacity is active for a specific user, when attached to a user via the $capacities array.

At the moment I am able to create the form that looks as I want with the following code :

```<code>use Planning\Domain\User;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, array(
                    'required'    => true,
                    'label' => "Login (pour Jean Durant → jdurant)"
                    ))
            ->add('displayname', TextType::class, array(
                    'label' => "Nom à afficher"
                ));

        $choices = array();
        $choicesActive = array();
        foreach ($builder->getData()->getCapacities() as $id => $capacity) {
            $choices[$capacity->getLabel()] = $capacity->getId();
            if ($capacity->getActive()) {
                $choicesActive[] = $capacity->getId();
            }
        }

        $builder->add('capacities', ChoiceType::class, array(
            'choices' => $choices,
            'data' => $choicesActive,
            'label' => "Groupes",
            'multiple' => True,
            'expanded' => True
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,

        ));
    }

    public function getName()
    {
        return 'capacity';
    }
}
</code>```

but the User object I am getting after the form is validated contains for capacities :

```<code>[capacities:Planning\Domain\User:private] => Array
    (
        [0] => 2
        [1] => 4
        [2] => 1
    )
</code>```

capacities variable contains the list of values for checkboxes that have been checked in the form. The issue is that my User object is not consistant with its definition which says that the capacities property should be an array of Capacity objects. What I am doing at the moment is that I have added the following code to my controller when $userForm->isSubmitted() and $userForm->isValid() :

```<code>// Getting the array from the returned user, should contain Capacity object but just contains the IDs.
$capacitiesChecked = $userForm->getData()->getCapacities();
// We regenerate the full array of capacities for this user
$user->setCapacities($app["dao.capacity"]->findAll());

// Then we will activate capacities that have been checked, one by one
foreach ($capacitiesChecked as $capacityChecked) {
    $user->getCapacityById($capacityChecked)->setActive(True);
}
</code>```

This is working and I am happy with it but being new to Silex and the framework world, I am surprized that I have not been able to find an easier way to answer my problem which I believe should be quite common.

I might be missing something from the Silex/Symfony philosophy and I hope someone there will be able to point me to the correct place to get more information or find a solution!

Edit following @dbrumann answer

As it might not be clear how my data is organized, here are the tables in my database :

user

id

username

displayname

capacity

id

label

place

user_capacity

id_user

id_capacity

There might be an issue with the modeling of my project but I have a Capacity class and a User class and User has an attribute with an array containing all the Capacity available in the database and each one of this Capacity object has an active attribute that is set to True if there is an entry in the table user_capacity that links user and capacity. What I would like is ONE form that allows me to properly update data into tables user and user_capacity.

答:
I have found a solution that I think is acceptable and might be useful for someone landing on this page. So what I have done is that I have changed my User class so that the $capacities attribute now contains only Capacity objects that are related to the user. But to get all the capacities available on the form, I am passing them as an option (allCapacities) and iterating over them to find which one are present in User->capacities to check them in the form.

The updated class used to build the form is as following:

```<code>class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, array(
                    'required'    => true,
                    'label' => "Login (pour Jean Durant → jdurant)"
                    ))
            ->add('displayname', TextType::class, array(
                    'label' => "Nom à afficher"
                ));

        $choices = array();
        $choicesActive = array();
        foreach ($options["allCapacities"] as $id => $capacity) {
            $choices[] = $capacity;
            if ($builder->getData()->hasCapacity($capacity)) {
                $choicesActive[] = $capacity;

            }
        }

        $builder->add('capacities', ChoiceType::class, array(
            'choices' => $choices,
            'data' => $choicesActive,
            'choice_label' => function($category, $key, $index) {
                return $category->getLabel();
            },
            'label' => "Groupes",
            'multiple' => True,
            'expanded' => True,
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,
        ));

        $resolver->setRequired(array(
            'allCapacities',
        ));

    }

    public function getName()
    {
        return 'capacity';
    }
}
</code>```

This is working as expected and does seem to be overcomplicated but there might be easier solution by changing the design, any comment on this would then be welcome!

Body:
I am using PHP with the Silex framework and after some hours trying to find a satisfying solution I am still blocked with the following problem regarding forms and objects containing array of Objects. The hours spent permitted me to find a working solution but I hope there is a better way to do that with Silex.

In my application I have a User class that is defined like :

class User implements UserInterface
{
    private $id;
    private $username;
    private $displayname;
    private $capacities;
    //...
}

$capacities variable contains an array of objects from another class (Capacity). A Capacity is a specific role in my app with various information (label, place of the capacity ...) and I have added, in that Capacity class a boolean telling if the Capacity is active for a specific user, when attached to a user via the $capacities array.

At the moment I am able to create the form that looks as I want with the following code :

use Planning\Domain\User;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, array(
                    'required'    => true,
                    'label' => "Login (pour Jean Durant → jdurant)"
                    ))
            ->add('displayname', TextType::class, array(
                    'label' => "Nom à afficher"
                ));

        $choices = array();
        $choicesActive = array();
        foreach ($builder->getData()->getCapacities() as $id => $capacity) {
            $choices[$capacity->getLabel()] = $capacity->getId();
            if ($capacity->getActive()) {
                $choicesActive[] = $capacity->getId();
            }
        }

        $builder->add('capacities', ChoiceType::class, array(
            'choices' => $choices,
            'data' => $choicesActive,
            'label' => "Groupes",
            'multiple' => True,
            'expanded' => True
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,

        ));
    }

    public function getName()
    {
        return 'capacity';
    }
}

but the User object I am getting after the form is validated contains for capacities :

[capacities:Planning\Domain\User:private] => Array
    (
        [0] => 2
        [1] => 4
        [2] => 1
    )

capacities variable contains the list of values for checkboxes that have been checked in the form. The issue is that my User object is not consistant with its definition which says that the capacities property should be an array of Capacity objects. What I am doing at the moment is that I have added the following code to my controller when $userForm->isSubmitted() and $userForm->isValid() :

// Getting the array from the returned user, should contain Capacity object but just contains the IDs.
$capacitiesChecked = $userForm->getData()->getCapacities();
// We regenerate the full array of capacities for this user
$user->setCapacities($app["dao.capacity"]->findAll());

// Then we will activate capacities that have been checked, one by one
foreach ($capacitiesChecked as $capacityChecked) {
    $user->getCapacityById($capacityChecked)->setActive(True);
}

This is working and I am happy with it but being new to Silex and the framework world, I am surprized that I have not been able to find an easier way to answer my problem which I believe should be quite common.

I might be missing something from the Silex/Symfony philosophy and I hope someone there will be able to point me to the correct place to get more information or find a solution!

Edit following @dbrumann answer

As it might not be clear how my data is organized, here are the tables in my database :

user

id

username

displayname

capacity

id

label

place

user_capacity

id_user

id_capacity

There might be an issue with the modeling of my project but I have a Capacity class and a User class and User has an attribute with an array containing all the Capacity available in the database and each one of this Capacity object has an active attribute that is set to True if there is an entry in the table user_capacity that links user and capacity. What I would like is ONE form that allows me to properly update data into tables user and user_capacity.

Body:
I have found a solution that I think is acceptable and might be useful for someone landing on this page. So what I have done is that I have changed my User class so that the $capacities attribute now contains only Capacity objects that are related to the user. But to get all the capacities available on the form, I am passing them as an option (allCapacities) and iterating over them to find which one are present in User->capacities to check them in the form.

The updated class used to build the form is as following:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, array(
                    'required'    => true,
                    'label' => "Login (pour Jean Durant → jdurant)"
                    ))
            ->add('displayname', TextType::class, array(
                    'label' => "Nom à afficher"
                ));

        $choices = array();
        $choicesActive = array();
        foreach ($options["allCapacities"] as $id => $capacity) {
            $choices[] = $capacity;
            if ($builder->getData()->hasCapacity($capacity)) {
                $choicesActive[] = $capacity;

            }
        }

        $builder->add('capacities', ChoiceType::class, array(
            'choices' => $choices,
            'data' => $choicesActive,
            'choice_label' => function($category, $key, $index) {
                return $category->getLabel();
            },
            'label' => "Groupes",
            'multiple' => True,
            'expanded' => True,
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,
        ));

        $resolver->setRequired(array(
            'allCapacities',
        ));

    }

    public function getName()
    {
        return 'capacity';
    }
}

This is working as expected and does seem to be overcomplicated but there might be easier solution by changing the design, any comment on this would then be welcome!


问:
Passing parameters in Angular js Getters
I am using angular 1.6.x

I have a list of checkboxes which maintain their state using a variable (selectedJobIds). The variable contains selected job ids, like,

```<code>$scope.selectedJobIds = {
 23: true,
 56: true,
 47: false
}
</code>```

Now, I need to check the checkboxes which exist in this object and have value true. Also, the checkboxes should be checked even if they don't exist in the object.

Right now, it is not able to differentiate between non-existent id and id with false value. It unchecks both of them.

Tried Approaches:
1) I tried to implement ternary condition in
ng-model="(angular.isDefined(selectedJobIds[job.iid])?selectedJobIds[job.iid]:true)"

But it throws syntax error.

2) I tried using getter/setter of ng-model-options
But the problem is that I can't able to pass job id to the getter function. Also, I am not able to get the scope of the current element, so I can access its value. So, I can use this id to detect its existence and non-existence in selectedJobIds variable.

HTML:

```<code><ul class="list-unstyled filtered-trucks-ul">
  <li ng-repeat="job in dType track by $index" style="vertical-align: middle;">
      <input type="checkbox" name="job_id" value="{{job.iid}}"
             ng-click="selectFilterJob()"
             ng-model="selectedJobIds[job.iid]" />
      <img src="23.png">
      {{ job.rref + ' (' +job.iid+ ')' | uppercase }}
      </li>
</ul>
</code>```

JS:

```<code>$scope.checkedFilteredJobs = {
    getterFunc: function(newName) {
        console.log(newName)
        // if(angular.isDefined($scope.selectedJobIds[id]))
        // {
        //    return $scope.selectedJobIds[id];
        // }
        // else {
        return true;
        // }
    }
};
</code>```

答:
Use ng-init to initialize missing properties:

var app = angular.module('myApp', []);

app.controller('myAppController', ['$scope', function($scope) {

  $scope.dType = [{iid: 23}, {iid: 56}, {iid: 47}, {iid: 1234}, {iid: 888}];
  $scope.selectedJobs = {
    23: true,
    56: true,
    47: false
  };

  $scope.initMissing = function(job) {
    if (!$scope.selectedJobs.hasOwnProperty(job.iid))
      $scope.selectedJobs[job.iid] = true
  }

}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="myApp" ng-controller="myAppController">
  <ul>
    <li ng-repeat="job in dType track by $index">
      <input type="checkbox" ng-init="initMissing(job)" name="job_id"
             ng-model="selectedJobs[job.iid]" />
    </li>
  </ul>
</div></code>```

Body:
I am using angular 1.6.x

I have a list of checkboxes which maintain their state using a variable (selectedJobIds). The variable contains selected job ids, like,

$scope.selectedJobIds = {
 23: true,
 56: true,
 47: false
}

Now, I need to check the checkboxes which exist in this object and have value true. Also, the checkboxes should be checked even if they don't exist in the object.

Right now, it is not able to differentiate between non-existent id and id with false value. It unchecks both of them.

Tried Approaches:
1) I tried to implement ternary condition in
ng-model="(angular.isDefined(selectedJobIds[job.iid])?selectedJobIds[job.iid]:true)"

But it throws syntax error.

2) I tried using getter/setter of ng-model-options
But the problem is that I can't able to pass job id to the getter function. Also, I am not able to get the scope of the current element, so I can access its value. So, I can use this id to detect its existence and non-existence in selectedJobIds variable.

HTML:

      <input type="checkbox" name="job_id" value="{{job.iid}}"
             ng-click="selectFilterJob()"
             ng-model="selectedJobIds[job.iid]" />

      {{ job.rref + ' (' +job.iid+ ')' | uppercase }}

JS:

$scope.checkedFilteredJobs = {
    getterFunc: function(newName) {
        console.log(newName)
        // if(angular.isDefined($scope.selectedJobIds[id]))
        // {
        //    return $scope.selectedJobIds[id];
        // }
        // else {
        return true;
        // }
    }
};

Body:
Use ng-init to initialize missing properties:

var app = angular.module('myApp', []);

app.controller('myAppController', ['$scope', function($scope) {

  $scope.dType = [{iid: 23}, {iid: 56}, {iid: 47}, {iid: 1234}, {iid: 888}];
  $scope.selectedJobs = {
    23: true,
    56: true,
    47: false
  };

  $scope.initMissing = function(job) {
    if (!$scope.selectedJobs.hasOwnProperty(job.iid))
      $scope.selectedJobs[job.iid] = true
  }

}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="myApp" ng-controller="myAppController">
  <ul>
    <li ng-repeat="job in dType track by $index">
      <input type="checkbox" ng-init="initMissing(job)" name="job_id"
             ng-model="selectedJobs[job.iid]" />
    </li>
  </ul>
</div>


问:
Pattern type error in OCaml
I am implementing my own version of lists in OCaml for a school project. It is defined as such :

```<code>type 'a my_list =
    | Item of ('a * 'a my_list)
    | Empty
;;
</code>```

My goal is to implement 20 functions from the List module, and nth is giving me a lot of hard work. It is a recursive function which also calls hd and length funtions. Here is the code :

```<code>let rec length my_list =
    match my_list with
    | Empty -> 0
    | Item (hd, tl) -> (length tl) + 1
;;

let hd my_list = function
    | Empty -> raise (Failure "hd")
    | Item (hd, tl) -> hd
;;

let rec nth my_list n =
    let len = (length my_list) in
    match my_list with
    | lz when lz < 0 -> raise (Invalid_argument "nth")
    | sup when n > len - 1 -> raise (Failure "nth")
    | 0 -> (hd my_list)
    | _ -> (nth my_list (n - 1))
;;
</code>```

On compilation I got this error :

```<code>$>ocamlc -w Aelz -warn-error A mylist.ml
File "mylist.ml", line 44, characters 10-11:
Error: This pattern matches values of type int
       but a pattern was expected which matches values of type 'a my_list
</code>```

Referring to the following line of nth: | 0 -> (hd my_list)

Any Ideas ?
Thank you

EDIT 1: Thank you everyone for your wiseful answers, here is the final code :

```<code>let rec nth my_list n =
    if n < 0 then raise (Invalid_argument "nth") else
    if my_list = Empty then raise (Failure "nth") else
    if n = 0 then hd my_list else nth (tl my_list) (n-1)
;;
</code>```

EDIT 2: Thanks to your suggestions, this one is more strongly typed :

```<code>let rec nth my_list n =
    if n < 0 then raise (Invalid_argument "nth") else
            match my_list with
            | Empty -> raise (Failure "nth")
            | Item (hd, tl) -> if n=0 then hd else
                    nth tl (n-1)
;;
</code>```

答:
You're overthinking the nth function. I'm not sure what you meant to do when writing it, but is the approach I'm thinking of:

If n is negative, raise an error.

If the list is empty, raise an error. You cannot get the nth element of an empty list.

If the list isn't empty, see whether n equals 0.

If yes, return the head of the list.

If not, recurse.

Also, as a side-note, avoid pattern-matching on basic types. Instead of

```<code>match n with
| x when x<0 -> (* ... *)
| _ -> (* ... *)
</code>```

prefer using if:

```<code>if n<0 then (* ... *) else (* ... *)
</code>```

EDIT

On the other hand, when dealing with non-basic types, pattern-matching is strongly advised. So, instead of

```<code>if my_list = Empty then (* ... *) else (* ... *)
</code>```

prefer the following

```<code>match my_list with
| Empty -> (* ... *)
| Item (hd, tl) -> (* ... *)
</code>```

Furthermore (and I think this is what's causing you trouble with nth), you can combine both approaches:

```<code>if n < 0 then (* ... *)
else match my_list with
  | Empty -> (* ... *)
  | Item (hd, tl) -> (* ... *)
</code>```

or

```<code>match my_list with
  | Empty -> (* ... *)
  | Item (hd, tl) -> if n < 0 then (* ... *) else (* ... *)
</code>```

(Hint: The latter is probably what you need for nth.)

Of course, the type-checker is here to make sure that your types are consistent in your code.

Title: Pattern type error in OCaml

Body:
I am implementing my own version of lists in OCaml for a school project. It is defined as such :

type 'a my_list =
    | Item of ('a * 'a my_list)
    | Empty
;;

My goal is to implement 20 functions from the List module, and nth is giving me a lot of hard work. It is a recursive function which also calls hd and length funtions. Here is the code :

let rec length my_list =
    match my_list with
    | Empty -> 0
    | Item (hd, tl) -> (length tl) + 1
;;

let hd my_list = function
    | Empty -> raise (Failure "hd")
    | Item (hd, tl) -> hd
;;

let rec nth my_list n =
    let len = (length my_list) in
    match my_list with
    | lz when lz < 0 -> raise (Invalid_argument "nth")
    | sup when n > len - 1 -> raise (Failure "nth")
    | 0 -> (hd my_list)
    | _ -> (nth my_list (n - 1))
;;

On compilation I got this error :

$>ocamlc -w Aelz -warn-error A mylist.ml
File "mylist.ml", line 44, characters 10-11:
Error: This pattern matches values of type int
       but a pattern was expected which matches values of type 'a my_list

Referring to the following line of nth: | 0 -> (hd my_list)

Any Ideas ?
Thank you

EDIT 1: Thank you everyone for your wiseful answers, here is the final code :

let rec nth my_list n =
    if n < 0 then raise (Invalid_argument "nth") else
    if my_list = Empty then raise (Failure "nth") else
    if n = 0 then hd my_list else nth (tl my_list) (n-1)
;;

EDIT 2: Thanks to your suggestions, this one is more strongly typed :

let rec nth my_list n =
    if n < 0 then raise (Invalid_argument "nth") else
            match my_list with
            | Empty -> raise (Failure "nth")
            | Item (hd, tl) -> if n=0 then hd else
                    nth tl (n-1)
;;

Body:
You're overthinking the nth function. I'm not sure what you meant to do when writing it, but is the approach I'm thinking of:

If n is negative, raise an error.

If the list is empty, raise an error. You cannot get the nth element of an empty list.

If the list isn't empty, see whether n equals 0.

If yes, return the head of the list.

If not, recurse.

Also, as a side-note, avoid pattern-matching on basic types. Instead of

match n with
| x when x<0 -> (* ... *)
| _ -> (* ... *)

prefer using if:

if n<0 then (* ... *) else (* ... *)

EDIT

On the other hand, when dealing with non-basic types, pattern-matching is strongly advised. So, instead of

if my_list = Empty then (* ... *) else (* ... *)

prefer the following

match my_list with
| Empty -> (* ... *)
| Item (hd, tl) -> (* ... *)

Furthermore (and I think this is what's causing you trouble with nth), you can combine both approaches:

if n < 0 then (* ... *)
else match my_list with
  | Empty -> (* ... *)
  | Item (hd, tl) -> (* ... *)

or

match my_list with
  | Empty -> (* ... *)
  | Item (hd, tl) -> if n < 0 then (* ... *) else (* ... *)

(Hint: The latter is probably what you need for nth.)

Of course, the type-checker is here to make sure that your types are consistent in your code.


问:
MobileGestalt no access to InverseDeviceID
This happens with every app when I try to use OpenGLES on my iPhone7+ with iOS10.3. But it works without any problems on my iPhone7 iOS10.1.

This is the message I get:

```<code>libMobileGestalt MobileGestaltSupport.m:153: pid 304 (OpenGLES_Ch4_1) does not have sandbox access for ... and IS NOT appropriately entitled
libMobileGestalt MobileGestalt.c:549: no access to InverseDeviceID
</code>```

Does anyone have an idea about these messages?

I wonder if it is bugs or something else in iOS10.3? Because when I run the app on iPhone5s iOS10.2, those messages did not shown on the screen. While I upgraded the phone to iOS10.3.1, the massages shown again.

The reason why I ask this question is that some animation effects perform quite stuck on my iPhone7+, but it is completely smooth on iPhone5s. But now it seems it is no relationship between the message above and the stuck, and I have to check my iPhone7+...

答:
Google Map display and functionality works fine with this warning

Check my answer here:
https://stackoverflow.com/a/44970665/3378076

Body:
This happens with every app when I try to use OpenGLES on my iPhone7+ with iOS10.3. But it works without any problems on my iPhone7 iOS10.1.

This is the message I get:

libMobileGestalt MobileGestaltSupport.m:153: pid 304 (OpenGLES_Ch4_1) does not have sandbox access for ... and IS NOT appropriately entitled
libMobileGestalt MobileGestalt.c:549: no access to InverseDeviceID

Does anyone have an idea about these messages?

I wonder if it is bugs or something else in iOS10.3? Because when I run the app on iPhone5s iOS10.2, those messages did not shown on the screen. While I upgraded the phone to iOS10.3.1, the massages shown again.

The reason why I ask this question is that some animation effects perform quite stuck on my iPhone7+, but it is completely smooth on iPhone5s. But now it seems it is no relationship between the message above and the stuck, and I have to check my iPhone7+...


问:
Check if user accepted a push notification permission in iOS in codenameone
How can I check if the user denied or accepted the push notification permission message in ios in codenameone or native?</p>

答:
I found a solution implementing a funtion native to IOS 10

This methods are working perfectly in Objective-c and codenameone code

```<code>//------------------------------------------------------------------------------
//This method is use to check if the user enable or disable push notification
//------------------------------------------------------------------------------
-(BOOL)isPushNotificationIsEnable{

    if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
        NSLog(@"isPushNotificationIsEnable()->YES");
        return YES;
    } else {
        NSLog(@"isPushNotificationIsEnable()->NO");
        return NO;
    }
}
//------------------------------------------------------------------------------
//This method is use to launch the Notification screen of your app
//------------------------------------------------------------------------------
Display.getInstance().execute("App-Prefs:root=NOTIFICATIONS_ID&path=your package name app", new ActionListener() {
     String methodName = "startLocationSetting";
      @Override
      public void actionPerformed(ActionEvent evt) {

            boolean status = Utils.isPushNotificationEnable();

      }

});
//------------------------------------------------------------------------------
</code>```

Body:
I found a solution implementing a funtion native to IOS 10

This methods are working perfectly in Objective-c and codenameone code

//------------------------------------------------------------------------------
//This method is use to check if the user enable or disable push notification
//------------------------------------------------------------------------------
-(BOOL)isPushNotificationIsEnable{

    if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
        NSLog(@"isPushNotificationIsEnable()->YES");
        return YES;
    } else {
        NSLog(@"isPushNotificationIsEnable()->NO");
        return NO;
    }
}
//------------------------------------------------------------------------------
//This method is use to launch the Notification screen of your app
//------------------------------------------------------------------------------
Display.getInstance().execute("App-Prefs:root=NOTIFICATIONS_ID&path=your package name app", new ActionListener() {
     String methodName = "startLocationSetting";
      @Override
      public void actionPerformed(ActionEvent evt) {

            boolean status = Utils.isPushNotificationEnable();

      }

});
//------------------------------------------------------------------------------


问:
Difference between Xamarin.Forms and Xamarin Cross Platform
I've been 2 years with Xamarin Environment and mostly I used Xamarin.Forms. But yet, I have no idea what Xamarin Cross Platform is? Can anyone provide some structural differences?</p>

答:
When we talk about Xamarin there are two approaches in development of native apps:

Traditional Xamarin approach

Xamarin.Forms

There is a good quote from Xamarin web site

Share code everywhere. Use the same language, APIs and data structures
to share an average of 75% of app code across all mobile development
platforms. Build user interfaces with Xamarin.Forms and share nearly
100%.

Important note is that these numbers can vary from project to project so this is some assumption for general usage of Xamarin.

And as you can see from the image below about "differences" between these two approaches. Traditional Xamarin approach (Xamarin.iOS and Xamarin.Android) they’re both built on top of Mono, an open-source version of the .NET Framework. To develop those apps you use C# and there is an opportunity to share up to 75% of the codebase as you can see on the image bellow and from a quote from Xamarin.

Using Xamarin Traditional approach you can use a C# as a programming language to write your models, call web services, etc. So you are writing that code logic once and using/share it across the Xamarin.Android and Xamarin.iOS projects, and in those separate projects you are writing code that is specific for that platform and you have access to their APIs.

Also, there is a quote from Xamarin about the traditional approach:

Anything you can do in Objective-C, Swift, or Java can be done in C#
with Xamarin using Visual Studio.

And project structure with Xamarin traditional looks like this:

Shared code project: Codebase that is common and reusable for your other projects.

Xamarin.Android: Project for your Android app where you are writing code using Android-specific APIs, writing your UI code, etc.

Xamarin.iOS: Project for your iOS app where you are writing code
using iOS specific APIs, writing your UI code, etc.

More info about Xamarin traditional here.

Now about Xamarin.Forms, the best definition is quoted from the Xamarin website:

Xamarin.Forms is a framework that allows developers to rapidly create
cross-platform user interfaces. It provides it's own abstraction for
the user interface that will be rendered using native controls on iOS,
Android, Windows, or Windows Phone. This means that applications can
share a large portion of their user interface code and still retain
the native look and feel of the target platform.

As you can conclude from the text above, Xamarin.Forms is a framework that allows you to write your UI using C# or with XAML with the opportunity to use MVVM... With Xamarin.Forms you can write your codebase and your UI which will be shared across the platforms.

Note: this is a very simple project structure, of course, you can add more project for different layers

Shared code project: Holds your common code base and also because you are using Xamarin.Forms you can write code for your UI

Xamarin.iOS and Xamarin.Android: Code for that specific platform, and some advanced topics such as Custom renderers and Dependency services.

Of course, there is some of the limitations if you are using Xamarin.Forms for example out of the box you can only use UI controls that are common across all platforms. You can read my blog post about Xamarin.Forms pros and cons here.

More info about Xamarin.Forms here.

I hope that this answer is not confusing for you and as a conclusion in one or two sentences... Using Xamarin Traditional you can share your code logic between platform-specific projects, and using Xamarin.Forms you can share code logic and also code for UI across your projects.

Note: For shared project and code sharing strategy you can use "Shared Project" and "PCL" this is a topic for another question... so in this answer, I was simplifying this and use shared project term for that type of project in Xamarin app solution.

UPDATE, Summer of 2020:

.NET Maui is announced in May of 2020, the question about the difference between MAUI and Xamarin.Forms could be found in the StackOverflow thread here: What is MAUI? and what are differences between MAUI and Xamarin