问:
Scroll Background Relative to Page
This is my first time on Stack Overflow, so I apologize if my question is a bit verbose.  I have a bit of a quandary:

I want to create this parallax-scrolling effect where the background image (the height of which is larger than that of the window) always scrolls in direct relationship to your progress on the page.

For example, when you've scrolled 25% of the way down the page, the background image should have scrolled by 25%. And when you've scrolled to the very bottom of the page (100%), the background image should have scrolled to its bottom as well (100%).

With this parallax effect, the background image would still scroll, but it wouldn't tile or need to be stretched. However, with my current code (show below), the background does scroll much at a much slower rate than the content on the page; however it eventually reaches the bottom of the background and starts tiling.

I feel like I'm missing something mathematically. Any ideas?

Here's the jQuery I'm using:

NOTE: the background image has a height of 1200px

```<code>$(window).scroll(function() {
    var x = $(this).scrollTop(); /* Scroll Position */
    var y = $('html').height(); /* Height of Page */
    var z = x / y; /* Progress of current position on page */
    $('html').css('background-position', '0% ' + (z * 1200) + 'px');
});
</code>```

EDIT: I figured out the issue: Just as you don't start scrolling a page until you're at the bottom of the viewport, I shouldn't start scrolling the background image until that point either. So what I need now is a new function.  If r is the viewport height, the function shouldn't move the background image down for the first r pixels when scrolling down, and it shouldn't move the background image up for the last r pixels when scrolling up. Boy, this is turning into a real parallax-scrolling project. Any suggestions?

答:
I think this is what you were going for:

```<code>$(window).scroll(function() {
  var scrollPos = $(this).scrollTop();
  var pageHeight = $(document).height() - $(this).height();
  var progress = scrollPos / pageHeight;
  var backgroundOffset = (progress*100) + '%';
  $("html").css("background-position", "0% " + backgroundOffset);
});
</code>```

See demo

Title: Scroll Background Relative to Page

Body:
This is my first time on Stack Overflow, so I apologize if my question is a bit verbose.  I have a bit of a quandary:

I want to create this parallax-scrolling effect where the background image (the height of which is larger than that of the window) always scrolls in direct relationship to your progress on the page.

For example, when you've scrolled 25% of the way down the page, the background image should have scrolled by 25%. And when you've scrolled to the very bottom of the page (100%), the background image should have scrolled to its bottom as well (100%).

With this parallax effect, the background image would still scroll, but it wouldn't tile or need to be stretched. However, with my current code (show below), the background does scroll much at a much slower rate than the content on the page; however it eventually reaches the bottom of the background and starts tiling.

I feel like I'm missing something mathematically. Any ideas?

Here's the jQuery I'm using:

NOTE: the background image has a height of 1200px

$(window).scroll(function() {
    var x = $(this).scrollTop(); /* Scroll Position */
    var y = $('html').height(); /* Height of Page */
    var z = x / y; /* Progress of current position on page */
    $('html').css('background-position', '0% ' + (z * 1200) + 'px');
});

EDIT: I figured out the issue: Just as you don't start scrolling a page until you're at the bottom of the viewport, I shouldn't start scrolling the background image until that point either. So what I need now is a new function.  If r is the viewport height, the function shouldn't move the background image down for the first r pixels when scrolling down, and it shouldn't move the background image up for the last r pixels when scrolling up. Boy, this is turning into a real parallax-scrolling project. Any suggestions?

Body:
I think this is what you were going for:

$(window).scroll(function() {
  var scrollPos = $(this).scrollTop();
  var pageHeight = $(document).height() - $(this).height();
  var progress = scrollPos / pageHeight;
  var backgroundOffset = (progress*100) + '%';
  $("html").css("background-position", "0% " + backgroundOffset);
});

See demo


来源: stackexchange

问:
How to find the webpage loading time using cocoa touch?
I am doing an application which has to display the WebPage loading time as a msg. Can anyone please help me to find the loading time?

Thanks,
kabilan

答: Yes. In your UIWebViewDelegate, measure the time difference between -webViewDidStartLoad: and -webViewDidFinishLoad:

ContentLicense: CC BY-SA 2.5


问:
IIS and OLE DB External table is not in the expected format
I am having some very strange issues with OLE DB connecting to Excel workbooks.

Our system has a large Excel macro enabled template (we have Excel 2010 and Excel 2016). Occasionally a user will add pictures, charts, tabs, etc that give the error External table is not in the expected format when attempting to read a hidden tab in the workbook that the users do not access.

Normally, we have the user download a new template and redo the work without adding pictures.

Recently, there was many occurrences of this behavior and I attempted to investigate on my development computer.  I found that I could not open a connection to the "corrupted" file via the website during the file upload process where the file is read into a byte stream and a temporary .xlsm file is created and opened using an OleDbConnection and data is read from a hidden tab.

Nothing I did to the file would open it to be opened via the code hosted in IIS. This includes the following:

Remove all pictures

Remove all tabs but the hidden tab

Unhide the tab we read from

save the workbook as an xlsx to remove macros

save the workbook as a 2003 - 2007 workbook and then save back to either an xlsx or xlsm

The website is running under .NET Framework 4.0 and is running under IIS.

For my investigation, I wrote the following code and hosted it on the same development computer in a page in a test web application hosted in IIS Express under .NET Framework 4.0 and it successfully opened and read the data from the original "corrupted" file.

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReadExcelTabToDataSet : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string szSheetName = @"C:\Temp\Test.xlsm";
        string szConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=\"Excel 12.0;HDR=YES\";Data Source=" + szSheetName;

        string szQuery = "Select 'Configuration$' as Sheet, * From [Configuration$B1:S2]";
        string szExcelTableName = "ValidateFlag";
        DataSet ds;

        using (OleDbConnection conn = new OleDbConnection(szConnection))
        {
            using (OleDbDataAdapter da = new OleDbDataAdapter(szQuery, conn))
            {
                conn.Open();
                ds = new DataSet();
                da.Fill(ds, szExcelTableName);
            }
        }
    }
}
</code>```

This raises lots of warning bells and has stumped me.  This test seems to rule out everything but how OleDb performs when hosted in IIS.  When this page is copied to our site, it fails on the conn.Open().

Does anyone understand why this is happening and how to fix it? I do not want to penalize our users for strange Microsoft issues like this.

Thanks,

EDIT 1

If the file is marked "read-only" and it is in a directory that has full access, then the file can be opened and the data may be read successfully.

This still presents an issue since we are opening the file, checking information and finally, making changes on the tab.

答:
I began investigating using ClosedXml (a .NET solution built around OpenXML) to get past many of the OleDb issues that I am encountering.  When attempting to open the "corrupted" workbooks using ClosedXml, I received an error message that I was able to duplicate using the Microsoft Open XML SDK.

The cause of the issue is a form button that executes VBA code to copy data within the template from 1 tab to another.  The text in the form button contained a carriage return (i.e. a br).  When the size of the template gets large and the user saves their work, Excel corrupts the HTML by not terminating the br.  While the ACE OleDB command provides no indication, the Open XML SDK provides the following message:

Cannot open the file: Part /xl/drawings/vmlDrawing4.vml: The 'br' start tag on line 19 position 29 does not match the end tag of 'font'. Line 20, position 9.

If the extension of the template is renamed from .xlsm to .zip, the actual file can be inspected and the cause can be fixed. In this case, I had to remove the break between words on the button.

It does concern me that Excel becomes unstable as the file size is increased and does not save workbooks correctly at that point, but I am able to work around this one case.

ContentLicense: CC BY-SA 3.0

Body:
I am having some very strange issues with OLE DB connecting to Excel workbooks.

Our system has a large Excel macro enabled template (we have Excel 2010 and Excel 2016). Occasionally a user will add pictures, charts, tabs, etc that give the error External table is not in the expected format when attempting to read a hidden tab in the workbook that the users do not access.

Normally, we have the user download a new template and redo the work without adding pictures.

Recently, there was many occurrences of this behavior and I attempted to investigate on my development computer.  I found that I could not open a connection to the "corrupted" file via the website during the file upload process where the file is read into a byte stream and a temporary .xlsm file is created and opened using an OleDbConnection and data is read from a hidden tab.

Nothing I did to the file would open it to be opened via the code hosted in IIS. This includes the following:

Remove all pictures

Remove all tabs but the hidden tab

Unhide the tab we read from

save the workbook as an xlsx to remove macros

save the workbook as a 2003 - 2007 workbook and then save back to either an xlsx or xlsm

The website is running under .NET Framework 4.0 and is running under IIS.

For my investigation, I wrote the following code and hosted it on the same development computer in a page in a test web application hosted in IIS Express under .NET Framework 4.0 and it successfully opened and read the data from the original "corrupted" file.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReadExcelTabToDataSet : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string szSheetName = @"C:\Temp\Test.xlsm";
        string szConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=\"Excel 12.0;HDR=YES\";Data Source=" + szSheetName;

        string szQuery = "Select 'Configuration$' as Sheet, * From [Configuration$B1:S2]";
        string szExcelTableName = "ValidateFlag";
        DataSet ds;

        using (OleDbConnection conn = new OleDbConnection(szConnection))
        {
            using (OleDbDataAdapter da = new OleDbDataAdapter(szQuery, conn))
            {
                conn.Open();
                ds = new DataSet();
                da.Fill(ds, szExcelTableName);
            }
        }
    }
}

This raises lots of warning bells and has stumped me.  This test seems to rule out everything but how OleDb performs when hosted in IIS.  When this page is copied to our site, it fails on the conn.Open().

Does anyone understand why this is happening and how to fix it? I do not want to penalize our users for strange Microsoft issues like this.

Thanks,

EDIT 1

If the file is marked "read-only" and it is in a directory that has full access, then the file can be opened and the data may be read successfully.

This still presents an issue since we are opening the file, checking information and finally, making changes on the tab.


问:
How to display the role of a user in FOSUserBundle
I would like to display the user role in Symfony with the FOSUserBundle.

```<code>public function showAction() {
    $model = new User();
    $role = $model->getRoles();
    $user = $this->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    return $this->render('@FOSUser/Profile/show.html.twig', array(
        'user' => $user,
        'role' => $role,
    ));
}
</code>```

This my code in my ProfileController put that I can not call in Twig. Here is my Twig file:

```<code><div class="fos_user_user_show">

<p><b>{{ 'Username'|trans }}</b>: {{ user.username }}</p>
<p><b>{{ 'Email'|trans }}</b>: {{ user.email }}</p>
<p><b>{{ 'Role'|trans }}</b>: {{ role.user }}</p>
</code>```

答:
This should also work</p>

```<code><p><b>{{ 'Role'|trans }}</b>: {{ user.roles }}</p>
</code>```

Body:
I would like to display the user role in Symfony with the FOSUserBundle.

public function showAction() {
    $model = new User();
    $role = $model->getRoles();
    $user = $this->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    return $this->render('@FOSUser/Profile/show.html.twig', array(
        'user' => $user,
        'role' => $role,
    ));
}

This my code in my ProfileController put that I can not call in Twig. Here is my Twig file:

{{ 'Username'|trans }}: {{ user.username }}

{{ 'Email'|trans }}: {{ user.email }}

{{ 'Role'|trans }}: {{ role.user }}

Body:
This should also work

<p><b>{{ 'Role'|trans }}</b>: {{ user.roles }}</p>


问:
How to make markers layers using gmaps api without using Google Fusion Tables
How to make markers or polygon or polyline layers like in https://www.google.com/mymaps ?
like this one:

I have store marker in markers array and iterate over it to hide it on maps, but it is causing lag since it iterate at large number of markers. So I thought I should implement layers to my markers but dont know how to do it.

Any comment would be apreciated, event it is a reason why this question got down vote

答:
Just in case anyone has same problem like above, I manage it to work by registering componen.setMap to dummy dom event listener
so far its work very well (better than setting map by looping)
*sory for my bad english and thank you</p>


问:
Scrape off some array values for asserting (Protractor)
Is there a way to scrape off or remove random or few values that are returned by the element.all array ?

The scenario i am trying to automate is to check that the word 'HTML' should be present in every row returned from the list of array.

I have used the w3Schools as a dummy test website to trial my scenario, below is the code which is failing because of assertion.

```<code>describe('Searching for word HTML', function() {
    var array=[];
    var counter=0;
    it('Beginning of the test', function() {

    browser.ignoreSynchronization = true;
    browser.get('https://www.w3schools.com/html/default.asp');

    browser.sleep(5000).then(function(){});

    var lines = element.all(by.css('#leftmenuinnerinner>a'));
    lines.count().then(function(counting){
        console.log("There are total "+counting+" links");
        counter=counter+counting;
        return counting;
    })
    lines.getText().then(function(text){

        console.log("Values:::: "+text);
        for(var k=0;k<text.length;k++){
        expect(text[k]).toContain('HTML');
        }
    })
    })
})
</code>```

I know i could use the xpath values & iterate through a loop of 76 values only but i am trying via a approach of css selector & i need to strictly get the entire list of values, so is there a way i could trim or scrape off the values 'HTTP Messages','HTTP Methods','PX to EM Converter' & 'Keyboard Shortcuts' dynamically through my code from the array returned so that my assertion passes ?

答:
The best way to avoid for loop is each. See the documentation:

http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.each

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to scrape off or remove random or few values that are returned by the element.all array ?

The scenario i am trying to automate is to check that the word 'HTML' should be present in every row returned from the list of array.

I have used the w3Schools as a dummy test website to trial my scenario, below is the code which is failing because of assertion.

describe('Searching for word HTML', function() {
    var array=[];
    var counter=0;
    it('Beginning of the test', function() {

    browser.ignoreSynchronization = true;
    browser.get('https://www.w3schools.com/html/default.asp');

    browser.sleep(5000).then(function(){});

    var lines = element.all(by.css('#leftmenuinnerinner>a'));
    lines.count().then(function(counting){
        console.log("There are total "+counting+" links");
        counter=counter+counting;
        return counting;
    })
    lines.getText().then(function(text){

        console.log("Values:::: "+text);
        for(var k=0;k<text.length;k++){
        expect(text[k]).toContain('HTML');
        }
    })
    })
})

I know i could use the xpath values & iterate through a loop of 76 values only but i am trying via a approach of css selector & i need to strictly get the entire list of values, so is there a way i could trim or scrape off the values 'HTTP Messages','HTTP Methods','PX to EM Converter' & 'Keyboard Shortcuts' dynamically through my code from the array returned so that my assertion passes ?


问:
kendo-angular-ui grid with pagination as well as grouping in angular2
Can we have pagination and grouping together in kendo-angular-ui grid? want to understand if this is possible in kendo grid using angular2?

I tried to create a example where I can have both grouping and pagination together, but somehow pagination is not working.

<kendo-grid [groupable]="false" [data]="gridView" [group]="groups" [pageSize]="pageSize" [skip]="skip" [pageable]="true" (dataStateChange)="dataStateChange($event)">
        <kendo-grid-column field="ProductID" title="ID" [width]="80"></kendo-grid-column>
        <kendo-grid-column field="ProductName" title="Name" [width]="300"></kendo-grid-column>
        <kendo-grid-column field="UnitPrice" title="Unit Price" [width]="120"></kendo-grid-column>
        <kendo-grid-column field="Category.CategoryName" title="Category">
            <ng-template kendoGridGroupHeaderTemplate let-value="value">
                {{value}}
            </ng-template>
        </kendo-grid-column>
</kendo-grid>

Plunker Example

答: In their documentation they have a working example with grouping and pagination.</p>


问:
Tensorflow: nan during matrix multiplication and addition
I'm using a function (ndegree_poly) which gets a tensor and an array of weights, and calculates the result of a polynomial from them.

The code seems straight forward enough, but when the degree increases, or the function is repeated multiple times, the resulting tensor contains a bunch of nans and infs. The infs are reasonable. But if the numbers are getting really small, shouldn't they become zero, instead of nan?

```<code>import tensorflow as tf

function_degree = 10

def ndegree_poly(x, a, degree=6):
        op = tf.add_n([tf.multiply(tf.pow(x, i), a[i]) for i in range(1, degree)])
        return tf.add(op, a[0])

with tf.Session() as sess:
    poly_weight = tf.Variable(tf.random_normal([function_freedom, 1, 5]))

    mat = tf.Variable(tf.random_normal([2, 5]))

    result0 = ndegree_poly(mat, poly_weight, function_degree)
    result1 = ndegree_poly(result0, poly_weight, function_degree)
    result2 = ndegree_poly(result1, poly_weight, function_degree)
    result3 = ndegree_poly(result2, poly_weight, function_degree)
    result4 = ndegree_poly(result3, poly_weight, function_degree)

    sess.run(tf.global_variables_initializer())
    print(sess.run(result4))
</code>```

it prints:

```<code>[[-0.28569764         nan         nan         nan        -inf]
 [        nan         nan  3.55561209         nan  0.53827095]]
</code>```

答:
The nan values do not come from very small coefficients, it's just the "natural" result of trying to do ∞ - ∞, as the coefficients come from a normal distribution and so are both positive and negative.

```<code>import math
import tensorflow as tf

tf_inf = tf.constant(inf)
res = tf_inf - tf_inf
with tf.Session() as sess:
    print(sess.run(res))

>>> nan
</code>```

Body:
I'm using a function (ndegree_poly) which gets a tensor and an array of weights, and calculates the result of a polynomial from them.

The code seems straight forward enough, but when the degree increases, or the function is repeated multiple times, the resulting tensor contains a bunch of nans and infs. The infs are reasonable. But if the numbers are getting really small, shouldn't they become zero, instead of nan?

import tensorflow as tf

function_degree = 10

def ndegree_poly(x, a, degree=6):
        op = tf.add_n([tf.multiply(tf.pow(x, i), a[i]) for i in range(1, degree)])
        return tf.add(op, a[0])

with tf.Session() as sess:
    poly_weight = tf.Variable(tf.random_normal([function_freedom, 1, 5]))

    mat = tf.Variable(tf.random_normal([2, 5]))

    result0 = ndegree_poly(mat, poly_weight, function_degree)
    result1 = ndegree_poly(result0, poly_weight, function_degree)
    result2 = ndegree_poly(result1, poly_weight, function_degree)
    result3 = ndegree_poly(result2, poly_weight, function_degree)
    result4 = ndegree_poly(result3, poly_weight, function_degree)

    sess.run(tf.global_variables_initializer())
    print(sess.run(result4))

it prints:

[[-0.28569764         nan         nan         nan        -inf]
 [        nan         nan  3.55561209         nan  0.53827095]]

Body:
The nan values do not come from very small coefficients, it's just the "natural" result of trying to do ∞ - ∞, as the coefficients come from a normal distribution and so are both positive and negative.

import math
import tensorflow as tf

tf_inf = tf.constant(inf)
res = tf_inf - tf_inf
with tf.Session() as sess:
    print(sess.run(res))

>>> nan


问:
How to handle traversing in CustomItem of J2ME in a mobile phone which does not support traversing?
How to handle traversing in CustomItem of J2ME in a mobile phone which does not support traversing?

I am doing a mobile application using J2ME - MIDP 2.0. In my application I draw the table using javax.microedition.lcdui.CustomItem. I also implement the traverse method. But in some mobile phones the traversing is not supported. How to implemnent the traversing process in a mobile which does not support traversing?

答:
I got the solution for the problem.

First we find the device does support traversing or not by the method "getInteractionModes()" of the class "javax.microedition.lcdui.CustomItem".From that we get the traversing support or not.

If traversing is not support means then add a Command button for that then implement the traversing operation inside the button click event handling ( public void commandAction(Command c, Item item) ).

finding the device support traversing or not is shown in the following coding snippet

```<code>int supported_interaction_modes=this.getInteractionModes();
boolean horizontal_interaction,vertical_interaction;

if((supported_interaction_modes&CustomItem.TRAVERSE_HORIZONTAL)!=0)
  horizontal_interaction=true;
else
  horizontal_interaction=false;

if((supported_interaction_modes&CustomItem.TRAVERSE_VERTICAL)!=0)
  vertical_interaction=true;
else
  vertical_interaction=false;
</code>```

In the above coding snippet "this" refers to the child class of CustomItem (javax.microedition.lcdui.CustomItem) which is user-defined class for CustomItem operations.

Body:
I got the solution for the problem.

First we find the device does support traversing or not by the method "getInteractionModes()" of the class "javax.microedition.lcdui.CustomItem".From that we get the traversing support or not.

If traversing is not support means then add a Command button for that then implement the traversing operation inside the button click event handling ( public void commandAction(Command c, Item item) ).

finding the device support traversing or not is shown in the following coding snippet

int supported_interaction_modes=this.getInteractionModes();
boolean horizontal_interaction,vertical_interaction;

if((supported_interaction_modes&CustomItem.TRAVERSE_HORIZONTAL)!=0)
  horizontal_interaction=true;
else
  horizontal_interaction=false;

if((supported_interaction_modes&CustomItem.TRAVERSE_VERTICAL)!=0)
  vertical_interaction=true;
else
  vertical_interaction=false;

In the above coding snippet "this" refers to the child class of CustomItem (javax.microedition.lcdui.CustomItem) which is user-defined class for CustomItem operations.


问:
Node.js async taking too long to execute
I've got my array of queries

```<code>var array = [ 'UPDATE EVALUATION SET mark = "16" WHERE id_eval = "21" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "9" WHERE id_eval = "22" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "8" WHERE id_eval = "34" AND id_usr = "125"'
            ]
</code>```

However, when I try to execute them all at once with async, my web page says Waiting for localhost... and it keeps on loading forever. What am I doing wrong?

```<code>async.forEach(array, function(query, callback) {
    connection.query(query, function(err, rows, fields) {
        if(err) {
            return console.error(err);
        }

        callback();
    });
}, function(err){
    if(err) {
        return console.log(err);
    }
});
</code>```

答:
Usually you have a request handler like this:

```<code>const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});
</code>```

Your browser holds the connection until res.endwas called!

In your environment it should look somethinge like

```<code>const server = http.createServer((req, res) => {

  // ...
  async.forEach(array, function(query, callback){
    connection.query(query, function(err, rows, fields) {
        // you may do some work here but leave it *alyways* via callback!
        callback(err);
    });
  }, function(err){
    if(err){ // this may be errors from above
      return console.log(err);
    }
    // Exit here !
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('All done.\n');
  });
});
</code>```

...or a bit cleaner

```<code>function doSomeDatabaseUpdates(onFinished) {
  var array = [...];
  async.forEach(array, function(query, callback){
    connection.query(query, function(err, rows, fields) {
        // you may do some work here but leave it *alyways* via callback!
        callback(err);
    });
  },
  function IGetCalledAfterAboveCallbackWereExecuted(err){
    if(err){ // this may be errors from above
      return console.log(err);
    }
    // Exit here !
    onFinished();
  });
}

const server = http.createServer((req, res) => {

  // ... do some work

  if (doSomeUpdated === true) {
    doSomeDatabaseUpdates(function calledAfterUpdates() {
      res.end("updates something");
    });
  } else {
    res.end("nothing to do");
  }

});
</code>```

Body:
I've got my array of queries

var array = [ 'UPDATE EVALUATION SET mark = "16" WHERE id_eval = "21" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "9" WHERE id_eval = "22" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "8" WHERE id_eval = "34" AND id_usr = "125"'
            ]

However, when I try to execute them all at once with async, my web page says Waiting for localhost... and it keeps on loading forever. What am I doing wrong?

async.forEach(array, function(query, callback) {
    connection.query(query, function(err, rows, fields) {
        if(err) {
            return console.error(err);
        }

        callback();
    });
}, function(err){
    if(err) {
        return console.log(err);
    }
});

Body:
Usually you have a request handler like this:

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

Your browser holds the connection until res.endwas called!

In your environment it should look somethinge like

const server = http.createServer((req, res) => {

  // ...
  async.forEach(array, function(query, callback){
    connection.query(query, function(err, rows, fields) {
        // you may do some work here but leave it *alyways* via callback!
        callback(err);
    });
  }, function(err){
    if(err){ // this may be errors from above
      return console.log(err);
    }
    // Exit here !
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('All done.\n');
  });
});

...or a bit cleaner

function doSomeDatabaseUpdates(onFinished) {
  var array = [...];
  async.forEach(array, function(query, callback){
    connection.query(query, function(err, rows, fields) {
        // you may do some work here but leave it *alyways* via callback!
        callback(err);
    });
  },
  function IGetCalledAfterAboveCallbackWereExecuted(err){
    if(err){ // this may be errors from above
      return console.log(err);
    }
    // Exit here !
    onFinished();
  });
}

const server = http.createServer((req, res) => {

  // ... do some work

  if (doSomeUpdated === true) {
    doSomeDatabaseUpdates(function calledAfterUpdates() {
      res.end("updates something");
    });
  } else {
    res.end("nothing to do");
  }

});


问:
Test code coverage is 50% in brances using Istanbul for Mocha test. How to make it 100%?
New to writing unit test cases.Code Coverage is 50% in branch using istanbul for react code with testing - MOCHA + CHAI + ENZYME. Not able to figure out what's missing in the code.

subscription.js:

```<code>import React from 'react';
export default class Subscription extends React.Component {
constructor(props) {

super(props);
this.state = {
  input:'',
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}

handleSubmit(e){
e.preventDefault();

this.setState({
 input: ''
})
}

handleChange(e) {
this.setState({
  input:e.target.value
})
}

render() {

  //Setting up className here
  //let inputSel = this.state.isChecked?"active":"";

  return (
        <div>
          <form onSubmit={this.handleSubmit}>
            <input type="email" onChange={this.handleChange} value={this.state.input} />
            <button className="buttonStyle">Subscribe</button>
          </form>
        </div>
  );
 }

 } //end of class
</code>```

app.js:

```<code>  import React from 'react';
  import {render} from 'react-dom';
  import Subscription from './Subscription'

  class App extends React.Component {

  constructor(props) {
  super(props);
  }

  render() {
     return (
      <div>
        <Subscription />
      </div>
  );
  }

   }

   render(<App />,document.getElementById('app'));
</code>```

test.js

```<code>        import React from 'react';
        import sinon from 'sinon';
        import {mount,shallow} from 'enzyme';
        import { expect } from 'chai';

        import Subscription from '../src/client/app/Subscription'

        describe('<Subscription />', function() {

          before(function() {
            it('should have subscription component',function(){
              expect(shallow (<Subscription />)).to.have.length(1);
            });

          });

          it('should have a form ',function(){
            const wrapper = shallow (<Subscription />);
            expect(wrapper.find('form')).to.have.length(1);
          });
          it('should have an input box with type email', function() {
            const wrapper = shallow (<Subscription />);
            expect(wrapper.find('input[type="email"]')).to.have.length(1);
          // expect(wrapper.find('.subscribeinput')).to.equal(true);

          });
          it('should have a button', function () {
            const wrapper = shallow(<Subscription />);
            expect(wrapper.find('button')).to.have.length(1);
          });
          it('input and button should be child of form',function(){
            const wrapper = shallow (<Subscription />);
            expect(wrapper.find('input').parent().is('form')).to.equal(true);
            expect(wrapper.find('button').parent().is('form')).to.equal(true);
          });

          it('should have an initial email state', function () {
            const wrapper = mount(<Subscription/>);
            expect(wrapper.state().input).to.equal('');
          });
          it('should update the src state on changing input', function () {
            const wrapper = mount(<Subscription/>);
            wrapper.find('input').simulate('change', {target: {value: 'hello@ifelse.io'}});
            //wrapper.setState({ input: (wrapper.find('input[type="email"]').value()) });
            expect(wrapper.state().input).to.equal('hello@ifelse.io');
          });
          it('should update the input box on subscribe', function () {
            const handleSubmit = sinon.spy();
            const wrapper = mount(<Subscription/>);
            wrapper.find('button').simulate('submit', { preventDefault() {} });
            expect(handleSubmit).to.have.been.called;
            expect(wrapper.state('input')).to.equal('');
          });

        });
</code>```

** Result of Coverage summary using Istanbul **

Coverage summary
Statements   : 100% ( 9/9 )
Branches     : 50% ( 1/2 )
Functions    : 100% ( 1/1 )
Lines        : 100% ( 9/9 )

why is branches alone 50%? what should be done to make it 100%?

答:
This is an ongoing issue with Istanbul and ES6 syntax.  The super call is being picked up as a branch.

One workaround is to place this comment block right beneath super(props):

```<code>/* istanbul ignore next */
</code>```

I have still yet to find a proper solution as I am not keen on littering my source with ignore blocks.

source: https://github.com/gotwarlost/istanbul/issues/690

Body:
New to writing unit test cases.Code Coverage is 50% in branch using istanbul for react code with testing - MOCHA + CHAI + ENZYME. Not able to figure out what's missing in the code.

subscription.js:

import React from 'react';
export default class Subscription extends React.Component {
constructor(props) {

super(props);
this.state = {
  input:'',
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}

handleSubmit(e){
e.preventDefault();

this.setState({
 input: ''
})
}

handleChange(e) {
this.setState({
  input:e.target.value
})
}

render() {

  //Setting up className here
  //let inputSel = this.state.isChecked?"active":"";

  return (

          <form onSubmit={this.handleSubmit}>
            <input type="email" onChange={this.handleChange} value={this.state.input} />
            <button className="buttonStyle">Subscribe</button>
          </form>

  );
 }

 } //end of class

app.js:

  import React from 'react';
  import {render} from 'react-dom';
  import Subscription from './Subscription'

  class App extends React.Component {

  constructor(props) {
  super(props);
  }

  render() {
     return (

        <Subscription />

  );
  }

   }

   render(<App />,document.getElementById('app'));

test.js

        import React from 'react';
        import sinon from 'sinon';
        import {mount,shallow} from 'enzyme';
        import { expect } from 'chai';

        import Subscription from '../src/client/app/Subscription'

        describe('<Subscription />', function() {

          before(function() {
            it('should have subscription component',function(){
              expect(shallow (<Subscription />)).to.have.length(1);
            });

          });

          it('should have a form ',function(){
            const wrapper = shallow (<Subscription />);
            expect(wrapper.find('form')).to.have.length(1);
          });
          it('should have an input box with type email', function() {
            const wrapper = shallow (<Subscription />);
            expect(wrapper.find('input[type="email"]')).to.have.length(1);
          // expect(wrapper.find('.subscribeinput')).to.equal(true);

          });
          it('should have a button', function () {
            const wrapper = shallow(<Subscription />);
            expect(wrapper.find('button')).to.have.length(1);
          });
          it('input and button should be child of form',function(){
            const wrapper = shallow (<Subscription />);
            expect(wrapper.find('input').parent().is('form')).to.equal(true);
            expect(wrapper.find('button').parent().is('form')).to.equal(true);
          });

          it('should have an initial email state', function () {
            const wrapper = mount(<Subscription/>);
            expect(wrapper.state().input).to.equal('');
          });
          it('should update the src state on changing input', function () {
            const wrapper = mount(<Subscription/>);
            wrapper.find('input').simulate('change', {target: {value: 'hello@ifelse.io'}});
            //wrapper.setState({ input: (wrapper.find('input[type="email"]').value()) });
            expect(wrapper.state().input).to.equal('hello@ifelse.io');
          });
          it('should update the input box on subscribe', function () {
            const handleSubmit = sinon.spy();
            const wrapper = mount(<Subscription/>);
            wrapper.find('button').simulate('submit', { preventDefault() {} });
            expect(handleSubmit).to.have.been.called;
            expect(wrapper.state('input')).to.equal('');
          });

        });

** Result of Coverage summary using Istanbul **

Coverage summary
Statements   : 100% ( 9/9 )
Branches     : 50% ( 1/2 )
Functions    : 100% ( 1/1 )
Lines        : 100% ( 9/9 )

why is branches alone 50%? what should be done to make it 100%?

Body:
This is an ongoing issue with Istanbul and ES6 syntax.  The super call is being picked up as a branch.

One workaround is to place this comment block right beneath super(props):

/* istanbul ignore next */

I have still yet to find a proper solution as I am not keen on littering my source with ignore blocks.

source: https://github.com/gotwarlost/istanbul/issues/690


问:
Group by field name
I want to do Group by by City but this possibility doesn't shows up. where is my mistake? there is field city in python file and it's showing up in tree view but not really in Group by     </p>

```<code><openerp>
    <data>

    <record id="vpicktree" model="ir.ui.view">
            <field name="name">Picking tree city</field>
            <field name="model">stock.picking</field>
            <field name="inherit_id" ref="stock.vpicktree"/>
            <field name="arch" type="xml">
                <field name="location_dest_id" position="after">
                    <field name="city"/>
                </field>
            </field>
        </record>

       <record model="ir.ui.view" id="stock_picking_filter_city_search">
            <field name="name">stock.picking.tree.filter_search</field>
            <field name="model">stock.picking</field>
            <field name="arch" type="xml">
                <search string="City">
                    <filter name="city" string="City" context="{'group_by':'city'}"/>
                 </search>
             </field>
       </record>

        <record id="action_picking_tree_city" model="ir.actions.act_window">
            <field name="name">City</field>
            <field name="res_model">stock.picking</field>
            <field name="type">ir.actions.act_window</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,kanban,calendar</field>
            <field name="domain"></field>
            <field name="context">{ 'group_by':'city' }</field>
            <field name="search_view_id" ref="stock.view_picking_internal_search"/>
        </record>
    </data>
</openerp>
</code>```

答:
The group by must be in search view not on the action setion as you did, so you have to edit your search view:</p>

```<code>   <record model="ir.ui.view" id="stock_picking_filter_city_search">
        <field name="name">stock.picking.tree.filter_search</field>
        <field name="model">stock.picking</field>
        <field name="arch" type="xml">
            <search string="City">
                <filter name="city" string="City" context="{'group_by':'city'}"/>

                <group expand="0" string="Grouper par">
                    <filter string="City" icon="terp-personal" domain="[]" context="{'group_by':'city'}"/>
                </group>

             </search>
         </field>
   </record>
</code>```

Title: Group by field name

Body:
I want to do Group by by City but this possibility doesn't shows up. where is my mistake? there is field city in python file and it's showing up in tree view but not really in Group by

<openerp>
    <data>

    <record id="vpicktree" model="ir.ui.view">
            <field name="name">Picking tree city</field>
            <field name="model">stock.picking</field>
            <field name="inherit_id" ref="stock.vpicktree"/>
            <field name="arch" type="xml">
                <field name="location_dest_id" position="after">
                    <field name="city"/>
                </field>
            </field>
        </record>

       <record model="ir.ui.view" id="stock_picking_filter_city_search">
            <field name="name">stock.picking.tree.filter_search</field>
            <field name="model">stock.picking</field>
            <field name="arch" type="xml">
                <search string="City">
                    <filter name="city" string="City" context="{'group_by':'city'}"/>
                 </search>
             </field>
       </record>

        <record id="action_picking_tree_city" model="ir.actions.act_window">
            <field name="name">City</field>
            <field name="res_model">stock.picking</field>
            <field name="type">ir.actions.act_window</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,kanban,calendar</field>
            <field name="domain"></field>
            <field name="context">{ 'group_by':'city' }</field>
            <field name="search_view_id" ref="stock.view_picking_internal_search"/>
        </record>
    </data>
</openerp>

Body:
The group by must be in search view not on the action setion as you did, so you have to edit your search view:

   <record model="ir.ui.view" id="stock_picking_filter_city_search">
        <field name="name">stock.picking.tree.filter_search</field>
        <field name="model">stock.picking</field>
        <field name="arch" type="xml">
            <search string="City">
                <filter name="city" string="City" context="{'group_by':'city'}"/>

                <group expand="0" string="Grouper par">
                    <filter string="City" icon="terp-personal" domain="[]" context="{'group_by':'city'}"/>
                </group>

             </search>
         </field>
   </record>


问:
Can Kotlin data class have more than one constructor?
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

```<code>data class User(val name: String, val age: Int)
</code>```

Is it possible to declare a second constructor for that data class?

答:
Yes, but each variable should be initialized, so you may set default arguments in your data class constructor, like this:

```<code>data class Person(val age: Int, val name: String = "Person without name")
</code>```

Now you can create instance of this data class in two ways

Person(30)

Person(20, "Bob")

Body:
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age: Int)

Is it possible to declare a second constructor for that data class?

Body:
Yes, but each variable should be initialized, so you may set default arguments in your data class constructor, like this:

data class Person(val age: Int, val name: String = "Person without name")

Now you can create instance of this data class in two ways

Person(30)

Person(20, "Bob")


问:
How to sort dates of string?
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

```<code>func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }
</code>```

Please guide me where I am doing wrong ?

答: It is not necessary to convert these strings to Date type.  You can simply sort them as strings and they will come out in the right order.</p>

Title: How to sort dates of string?

Body:
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }

Please guide me where I am doing wrong ?


问:
Open a Modal from another modal and close the first (launching) modal
I'm using Bootstrap Modal Window plugin its work fine but i would like to open another model window when i click next and close first one. how can i do it?

```<code>$('[data-toggle="modal"]').click(function(e)
    {
        e.preventDefault();
        var url = $(this).attr('href');
        if (url.indexOf('#') == 0)
        {
            $(url).modal('open');
        }
        else
        {
            $.get(url, function(data)
            {
                $(data).modal();
            }).success(function() { $('input:text:visible:first').focus(); });
        }
    });

<a href="next.html" data-toggle="modal">Add Record</a>
</code>```

next.html File Code

```<code><div class="modal fade" id="compose-modal" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">First Window</h4>
            </div>
            <form action="#" method="post">

                <div class="modal-footer clearfix">
                    <button type="button" data-dismiss="modal">Discard</button>

                    <button type="submit">Submit</button>
                     <a href="next2.html" data-toggle="modal" >Next</a>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

答:
All right everybody, stand back; I've got this.

This method negates both the padding & scrolling issues present in other methods (see bottom) and is [IMO] the cleanest way to achieve the required functionality using Bootstrap Modals.

Inline

```<code><a onclick="$('.modal-to-close').one('hidden.bs.modal', function() { $('.modal-to-open').modal('show'); }).modal('hide');">Open Modal</a>
</code>```

Full Fat:

```<code><script>
    $(function () {
        $('.selector').click(function() {
            $('.modal-to-close').one('hidden.bs.modal', function() {
                $('.modal-to-open').modal('show');
            }).modal('hide');
        });
    });
</script>

<a class="selector">Open Modal</a>
</code>```

Beastmode:

```<code><script>
    $(function () {
        $('[data-bm-close][data-bm-open]').on('click', function () {
            var $this = $(this);
            $($this.data('bm-close')).one('hidden.bs.modal', function () {
                $($this.data('bm-open')).modal('show');
            }).modal('hide');
        });
    });
</script>

<a data-bm-close=".modal-to-close" data-bm-open=".modal-to-open">Open Modal</a>
</code>```

Tip: Unless you need to do this more than once, I recommend using the Inline version.

Issues present in other answers

It creates a problem, when your modal has more height than your
  screen. As data-dismiss="modal" removes modal-open class from body
  tag. so, when you scroll, modal doesn't scrolls, but the faded
  background starts moving. which is bad. // Deepak Yadav

Can confirm the issue reported by @Deepak. Furthermore the page will
  increment and enforce "padding-right" by +17px each time you open a
  modal from inside another (modal might need to be taller than the page
  for this to happen). This holds true for almost all methods on this
  page. See my answer for a method that avoids these issues. // Matthew Hudson

Body:
I'm using Bootstrap Modal Window plugin its work fine but i would like to open another model window when i click next and close first one. how can i do it?

$('[data-toggle="modal"]').click(function(e)
    {
        e.preventDefault();
        var url = $(this).attr('href');
        if (url.indexOf('#') == 0)
        {
            $(url).modal('open');
        }
        else
        {
            $.get(url, function(data)
            {
                $(data).modal();
            }).success(function() { $('input:text:visible:first').focus(); });
        }
    });

Add Record

next.html File Code

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

First Window

            <form action="#" method="post">

                    <button type="button" data-dismiss="modal">Discard</button>

                    <button type="submit">Submit</button>
                     Next

            </form>

Body:
All right everybody, stand back; I've got this.

This method negates both the padding & scrolling issues present in other methods (see bottom) and is [IMO] the cleanest way to achieve the required functionality using Bootstrap Modals.

Inline

<a onclick="$('.modal-to-close').one('hidden.bs.modal', function() { $('.modal-to-open').modal('show'); }).modal('hide');">Open Modal</a>

Full Fat:

<script>
    $(function () {
        $('.selector').click(function() {
            $('.modal-to-close').one('hidden.bs.modal', function() {
                $('.modal-to-open').modal('show');
            }).modal('hide');
        });
    });
</script>

<a class="selector">Open Modal</a>

Beastmode:

<script>
    $(function () {
        $('[data-bm-close][data-bm-open]').on('click', function () {
            var $this = $(this);
            $($this.data('bm-close')).one('hidden.bs.modal', function () {
                $($this.data('bm-open')).modal('show');
            }).modal('hide');
        });
    });
</script>

<a data-bm-close=".modal-to-close" data-bm-open=".modal-to-open">Open Modal</a>

Tip: Unless you need to do this more than once, I recommend using the Inline version.

Issues present in other answers

It creates a problem, when your modal has more height than your
  screen. As data-dismiss="modal" removes modal-open class from body
  tag. so, when you scroll, modal doesn't scrolls, but the faded
  background starts moving. which is bad. // Deepak Yadav

Can confirm the issue reported by @Deepak. Furthermore the page will
  increment and enforce "padding-right" by +17px each time you open a
  modal from inside another (modal might need to be taller than the page
  for this to happen). This holds true for almost all methods on this
  page. See my answer for a method that avoids these issues. // Matthew Hudson


问:
Short form for class function without arrow function
In React I create return null components - https://github.com/joshwcomeau/return-null - so I do this:

```<code>class Blah extends Component {
    render = () => null
}
</code>```

Now I am using an arrow function here only for simplicity's sake. This causes Babel to do extra overhead (unnecessarily binding) which is not needed.

Is there a shot form of class methods that just return without arrow binding? Like this:

```<code>class Blah extends Component {
    render() null
}
</code>```

答:
You can assign () => null to some variable and use it whenever you want to have null component, for example:

```<code>const rnull = () => null;

class Blah extends Component {
    render = rnull
}
</code>```

There isn't any syntax to make this even simpler or shorter.

Body:
In React I create return null components - https://github.com/joshwcomeau/return-null - so I do this:

class Blah extends Component {
    render = () => null
}

Now I am using an arrow function here only for simplicity's sake. This causes Babel to do extra overhead (unnecessarily binding) which is not needed.

Is there a shot form of class methods that just return without arrow binding? Like this:

class Blah extends Component {
    render() null
}

Body:
You can assign () => null to some variable and use it whenever you want to have null component, for example:

const rnull = () => null;

class Blah extends Component {
    render = rnull
}

There isn't any syntax to make this even simpler or shorter.


问:
libGDX: Scale Textures when smaller resolution
I've read some articles about Viewports to solve the problem with different resolution. But in every example they used a smaller size for the texture than the resolution of the screen. But what happens when my texture size is for example 1920 x 1080 and my screen is just 800 x 400?
Is there any kind of Viewport that can scale the texture? I didn't found anything for this problem. </p>

答:
Looks like you mean scaling and not compressing. Compressing is a technique to lower the file size of a file, like a .jpg does over a uncompressed .bmp. So if you mean scaling then it completely depends on what you want. If you have a 1920x1080 texture and want this to completely fit the 800x400 screen it needs to be stretched since 1920x1080 = 16x9 and 800x400 = 2:1 = 16:8.

To stretch the image you need to use StretchViewport. You would create the viewport with the world dimensions you want to show. So in this case the 1920x1080 image, or perhaps 16x9 and put that texture with there "world units) in your world. StretchViewport will make sure the viewport is stretched to whatever size you use.

If you want it to fit as much as possible but remain the aspect ratio of 16:9 then you can use the FitViewport. Like StretchViewport each viewport (except ScreenViewport) need to be supplied with world units, this is a important concept. World units are not meters nor pixels until you define your world units as such. Anyway, FitViewport will also make sure each device sees as much of your world as you supply it but your assets won't stretch/deform. Instead it will create a "black" bar, much like TV's do when the aspect ratio is not equal.

ScreenViewport, by default just takes the size of the screen. So a 1920x1080 pixel screen would show 1920x1080 world units and a 640x480 pixel screen would show 640x480 world units. Therefore, the higher resolution the screen has the more of the world is visible. The amount of world units a screen pixel represents can be changed.

There are a view others: FillViewport is like FitViewport it will remain aspect ratio but always fills the screen. And thus some parts may not be visible. For that reason I can't think of a use for this one over FitViewport. And there is ExtentVieport, a mix between FitViewport and ScreenViewport.


问:
Using autolayout in a tableHeaderView
I have a UIView subclass that contains a multi-line UILabel. This view uses autolayout.

I would like to set this view as the tableHeaderView of a UITableView (not a section header). The height of this header will depend on the text of the label, which in turn depends on the width of the device. The sort of scenario autolayout should be great at.

I have found and attempted many many solutions to get this working, but to no avail. Some of the things I've tried:

setting a preferredMaxLayoutWidth on each label during layoutSubviews

defining an intrinsicContentSize

attempting to figure out the required size for the view and setting the tableHeaderView's frame manually.

adding a width constraint to the view when the header is set

a bunch of other things

Some of the various failures I've encountered:

label extends beyond the width of the view, doesn't wrap

frame's height is 0

app crashes with exception Auto Layout still required after executing -layoutSubviews

The solution (or solutions, if necessary) should work for both iOS 7 and iOS 8. Note that all of this is being done programmatically. I've set up a small sample project in case you want to hack on it to see the issue. I've reset my efforts to the following start point:

```<code>SCAMessageView *header = [[SCAMessageView alloc] init];
header.titleLabel.text = @"Warning";
header.subtitleLabel.text = @"This is a message with enough text to span multiple lines. This text is set at runtime and might be short or long.";
self.tableView.tableHeaderView = header;
</code>```

What am I missing?

答:
For anyone still looking for a solution, this is for Swift 3 & iOS 9+. Here is one using only AutoLayout. It also updates correctly on device rotation.

```<code>extension UITableView {
    // 1.
    func setTableHeaderView(headerView: UIView) {
        headerView.translatesAutoresizingMaskIntoConstraints = false

        self.tableHeaderView = headerView

        // ** Must setup AutoLayout after set tableHeaderView.
        headerView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        headerView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        headerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    }

    // 2.
    func shouldUpdateHeaderViewFrame() -> Bool {
        guard let headerView = self.tableHeaderView else { return false }
        let oldSize = headerView.bounds.size
        // Update the size
        headerView.layoutIfNeeded()
        let newSize = headerView.bounds.size
        return oldSize != newSize
    }
}
</code>```

To use:

```<code>override func viewDidLoad() {
    ...

    // 1.
    self.tableView.setTableHeaderView(headerView: customView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // 2. Reflect the latest size in tableHeaderView
    if self.tableView.shouldUpdateHeaderViewFrame() {

        // **This is where table view's content (tableHeaderView, section headers, cells)
        // frames are updated to account for the new table header size.
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }
}
</code>```

The gist is that you should let tableView manage the frame of tableHeaderView the same way as table view cells. This is done through tableView's beginUpdates/endUpdates.

The thing is that tableView doesn't care about AutoLayout when it updates the children frames. It uses the current tableHeaderView's size to determine where the first cell/section header should be.

1) Add a width constraint so that the tableHeaderView uses this width whenever we call layoutIfNeeded(). Also add centerX and top constraints to position it correctly relative to the tableView.

2) To let the tableView knows about the latest size of tableHeaderView, e.g., when the device is rotated, in viewDidLayoutSubviews we can call layoutIfNeeded() on tableHeaderView. Then, if the size is changed, call beginUpdates/endUpdates.

Note that I don't include beginUpdates/endUpdates in one function, as we might want to defer the call to later.

Check out a sample project

Title: Using autolayout in a tableHeaderView

Body:
I have a UIView subclass that contains a multi-line UILabel. This view uses autolayout.

I would like to set this view as the tableHeaderView of a UITableView (not a section header). The height of this header will depend on the text of the label, which in turn depends on the width of the device. The sort of scenario autolayout should be great at.

I have found and attempted many many solutions to get this working, but to no avail. Some of the things I've tried:

setting a preferredMaxLayoutWidth on each label during layoutSubviews

defining an intrinsicContentSize

attempting to figure out the required size for the view and setting the tableHeaderView's frame manually.

adding a width constraint to the view when the header is set

a bunch of other things

Some of the various failures I've encountered:

label extends beyond the width of the view, doesn't wrap

frame's height is 0

app crashes with exception Auto Layout still required after executing -layoutSubviews

The solution (or solutions, if necessary) should work for both iOS 7 and iOS 8. Note that all of this is being done programmatically. I've set up a small sample project in case you want to hack on it to see the issue. I've reset my efforts to the following start point:

SCAMessageView *header = [[SCAMessageView alloc] init];
header.titleLabel.text = @"Warning";
header.subtitleLabel.text = @"This is a message with enough text to span multiple lines. This text is set at runtime and might be short or long.";
self.tableView.tableHeaderView = header;

What am I missing?

Body:
For anyone still looking for a solution, this is for Swift 3 & iOS 9+. Here is one using only AutoLayout. It also updates correctly on device rotation.

extension UITableView {
    // 1.
    func setTableHeaderView(headerView: UIView) {
        headerView.translatesAutoresizingMaskIntoConstraints = false

        self.tableHeaderView = headerView

        // ** Must setup AutoLayout after set tableHeaderView.
        headerView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        headerView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        headerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    }

    // 2.
    func shouldUpdateHeaderViewFrame() -> Bool {
        guard let headerView = self.tableHeaderView else { return false }
        let oldSize = headerView.bounds.size
        // Update the size
        headerView.layoutIfNeeded()
        let newSize = headerView.bounds.size
        return oldSize != newSize
    }
}

To use:

override func viewDidLoad() {
    ...

    // 1.
    self.tableView.setTableHeaderView(headerView: customView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // 2. Reflect the latest size in tableHeaderView
    if self.tableView.shouldUpdateHeaderViewFrame() {

        // **This is where table view's content (tableHeaderView, section headers, cells)
        // frames are updated to account for the new table header size.
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    }
}

The gist is that you should let tableView manage the frame of tableHeaderView the same way as table view cells. This is done through tableView's beginUpdates/endUpdates.

The thing is that tableView doesn't care about AutoLayout when it updates the children frames. It uses the current tableHeaderView's size to determine where the first cell/section header should be.

1) Add a width constraint so that the tableHeaderView uses this width whenever we call layoutIfNeeded(). Also add centerX and top constraints to position it correctly relative to the tableView.

2) To let the tableView knows about the latest size of tableHeaderView, e.g., when the device is rotated, in viewDidLayoutSubviews we can call layoutIfNeeded() on tableHeaderView. Then, if the size is changed, call beginUpdates/endUpdates.

Note that I don't include beginUpdates/endUpdates in one function, as we might want to defer the call to later.

Check out a sample project


问:
How to call a user defined function with NULL values for one of its input parameter?
My UDF's body has the following HAVING class.

```<code>HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = @CustomerType
</code>```

I tried to call this by this following syntax.

```<code>SELECT * FROM FunctionName('ABC_Company',NULL)
</code>```

And also tried to set default value as NULL for @CustomerType parameter. And called the function by

```<code>SELECT * FROM FunctionName('ABC_Company',default)
</code>```

答:
you can use NULL as parameter and then:

```<code>HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = isnull(@CustomerType,'')
</code>```

provided you don't need to differenciate between NULL and empty string

Body:
My UDF's body has the following HAVING class.

HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = @CustomerType

I tried to call this by this following syntax.

SELECT * FROM FunctionName('ABC_Company',NULL)

And also tried to set default value as NULL for @CustomerType parameter. And called the function by

SELECT * FROM FunctionName('ABC_Company',default)

Body:
you can use NULL as parameter and then:

HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = isnull(@CustomerType,'')

provided you don't need to differenciate between NULL and empty string


问:
Translation in odoo 10
i need to add translation for following modules, purchase, sales and accounting for Arabic. I found Arabic translation in odoo, but its not completed. I have exported *.pot file for purchase module. and placed it in my custom module  mymodule/i18n/purchase.po(i replaced extension as *.po). And added msgstr in *.po file.
Now is the problem. i don't know how to use this modified *.po file. Pls help.

答:
For add translation in custom module following these steps:

Load a Translation (Settings >> Translation)

Open: Translated Terms

Search and Update terms in Odoo Front-End.

Export Translation : While export select your module in "Apps To Export"

Download po file and add into your module.

Hope this helps

Title: Translation in odoo 10


问:
Ionic 3 - Cannot build Google Maps after update
I've been stuck for some time now with the Google Maps plugin for Ionic. Until now, it worked perfectly fine on Android and iOS, but since I updated my app form Ionic 2 to 3 I cannot build it for iOS.

I've tried removing all npm modules and all plugins and platforms and reinstalling them again, I've been looking and googling for a solution for hours now and I'm starting to desperate. In android I have no problem building or running the app.

I'm building the app using xcode (opening the workspace's file, not the project's), but there are always two related errors:

/.../platforms/ios/appname/Plugins/com.googlemaps.ios/GoogleMaps.framework/Headers/GMSPolyline.h:11:9: 'UIKit/UIKIt.h' file not found

which causes the next error:

/.../platforms/ios/appname/Plugins/cordova-plugin-googlemaps/GoogleMaps.h:10:9: Could not build module 'GoogleMaps'

This is the maps plugin tag at config.xml:

```<code><plugin name="cordova-plugin-googlemaps" spec="~1.4.0">
    <variable name="API_KEY_FOR_ANDROID" value="myapikeyforandroid" />
    <variable name="API_KEY_FOR_IOS" value="myapikeyforios" />
    <variable name="NSLOCATIONWHENINUSEUSAGEDESCRIPTION" value="Show your location on the map" />
    <variable name="NSLOCATIONALWAYSUSAGEDESCRIPTION" value="Trace your location on the map" />
</plugin>
</code>```

In the package.json I have these dependences:

```<code>"dependencies": {
    "@angular/common": "4.1.2",
    "@angular/compiler": "4.1.2",
    "@angular/compiler-cli": "4.1.2",
    "@angular/core": "4.1.2",
    "@angular/forms": "4.1.2",
    "@angular/http": "4.1.2",
    "@angular/platform-browser": "4.1.2",
    "@angular/platform-browser-dynamic": "4.1.2",
    "@ionic-native/background-geolocation": "^3.12.1",
    "@ionic-native/background-mode": "^3.12.1",
    "@ionic-native/barcode-scanner": "^3.12.1",
    "@ionic-native/core": "3.11.0",
    "@ionic-native/geolocation": "^3.12.1",
    "@ionic-native/google-maps": "^3.12.1",
    "@ionic-native/local-notifications": "^3.12.1",
    "@ionic-native/push": "^3.12.1",
    "@ionic-native/secure-storage": "^3.12.1",
    "@ionic-native/social-sharing": "^3.12.1",
    "@ionic-native/splash-screen": "^3.12.1",
    "@ionic-native/status-bar": "^3.11.0",
    "@ionic-native/streaming-media": "^3.12.1",
    "@ionic-native/video-player": "^3.12.1",
    "@ionic/storage": "2.0.1",
    "angular2-jwt": "^0.2.3",
    "ionic-angular": "3.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "socket.io-client": "^1.7.2",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.11"
  }
</code>```

Let me know if I can provide any more clues...

Thanks in advance for the help.

EDIT: I've tried adding the UIKit Library and reinstalling XCode, but nothing works. If I remove the google maps plugin, the app builds just fine, so it seems to be related to cordova-plugin-googlemaps I'm trying now other versions to determine whether this is a version issue.

EDIT 2: Changing the google maps version didn't have any effects...

EDIT 3: I've found this thread, which seems similar to this one, but there wasn't any answer either.

答:
It sounds like your error may be similar to the one mentioned at this answer.

Try it and report back!

Body:
I've been stuck for some time now with the Google Maps plugin for Ionic. Until now, it worked perfectly fine on Android and iOS, but since I updated my app form Ionic 2 to 3 I cannot build it for iOS.

I've tried removing all npm modules and all plugins and platforms and reinstalling them again, I've been looking and googling for a solution for hours now and I'm starting to desperate. In android I have no problem building or running the app.

I'm building the app using xcode (opening the workspace's file, not the project's), but there are always two related errors:

/.../platforms/ios/appname/Plugins/com.googlemaps.ios/GoogleMaps.framework/Headers/GMSPolyline.h:11:9: 'UIKit/UIKIt.h' file not found

which causes the next error:

/.../platforms/ios/appname/Plugins/cordova-plugin-googlemaps/GoogleMaps.h:10:9: Could not build module 'GoogleMaps'

This is the maps plugin tag at config.xml:

<plugin name="cordova-plugin-googlemaps" spec="~1.4.0">
    <variable name="API_KEY_FOR_ANDROID" value="myapikeyforandroid" />
    <variable name="API_KEY_FOR_IOS" value="myapikeyforios" />
    <variable name="NSLOCATIONWHENINUSEUSAGEDESCRIPTION" value="Show your location on the map" />
    <variable name="NSLOCATIONALWAYSUSAGEDESCRIPTION" value="Trace your location on the map" />
</plugin>

In the package.json I have these dependences:

"dependencies": {
    "@angular/common": "4.1.2",
    "@angular/compiler": "4.1.2",
    "@angular/compiler-cli": "4.1.2",
    "@angular/core": "4.1.2",
    "@angular/forms": "4.1.2",
    "@angular/http": "4.1.2",
    "@angular/platform-browser": "4.1.2",
    "@angular/platform-browser-dynamic": "4.1.2",
    "@ionic-native/background-geolocation": "^3.12.1",
    "@ionic-native/background-mode": "^3.12.1",
    "@ionic-native/barcode-scanner": "^3.12.1",
    "@ionic-native/core": "3.11.0",
    "@ionic-native/geolocation": "^3.12.1",
    "@ionic-native/google-maps": "^3.12.1",
    "@ionic-native/local-notifications": "^3.12.1",
    "@ionic-native/push": "^3.12.1",
    "@ionic-native/secure-storage": "^3.12.1",
    "@ionic-native/social-sharing": "^3.12.1",
    "@ionic-native/splash-screen": "^3.12.1",
    "@ionic-native/status-bar": "^3.11.0",
    "@ionic-native/streaming-media": "^3.12.1",
    "@ionic-native/video-player": "^3.12.1",
    "@ionic/storage": "2.0.1",
    "angular2-jwt": "^0.2.3",
    "ionic-angular": "3.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "socket.io-client": "^1.7.2",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.11"
  }

Let me know if I can provide any more clues...

Thanks in advance for the help.

EDIT: I've tried adding the UIKit Library and reinstalling XCode, but nothing works. If I remove the google maps plugin, the app builds just fine, so it seems to be related to cordova-plugin-googlemaps I'm trying now other versions to determine whether this is a version issue.

EDIT 2: Changing the google maps version didn't have any effects...

EDIT 3: I've found this thread, which seems similar to this one, but there wasn't any answer either.


问:
Tensorflow Serving Batching parameters
How to do performance tuning of batching using max_batch_size, batch_timeout_micros, num_batch_threads and other parameters? Tried using these parameters with the Query client, it doesn't work.

In the below example I have 100 images and I want to batch in size of 10. The query runs for all images instead of 10.

bazel-bin/tensorflow_serving/example/demo_batch --server=localhost:9000 --max_batch_size=10
```

Also, for batch scheduling how to make it run every 10 secs after the first batch is done? Thanks.

答:
I have met the same problem like you.

And I checked the source code of tf-serving, these parameters are in an protobuf file which defined in:

```<code>serving/tensorflow_serving/servables/tensorflow/session_bundle_config.proto
</code>```

And I found the example conf file in:

```<code>serving/tensorflow_serving/servables/tensorflow/testdata/batching_config.txt
</code>```

And I believe you could follow the batching_config.txt format, the parameters config should be work.

Hope it helps.

```<code>max_batch_size { value: 1024 }
batch_timeout_micros { value: 0 }
max_enqueued_batches { value: 1000000 }
num_batch_threads { value: 8 }
allowed_batch_sizes : 1
allowed_batch_sizes : 2
allowed_batch_sizes : 8
allowed_batch_sizes : 32
allowed_batch_sizes : 128
allowed_batch_sizes : 256
allowed_batch_sizes : 512
allowed_batch_sizes : 1024
</code>```

Title: Tensorflow Serving Batching parameters

Body:
How to do performance tuning of batching using max_batch_size, batch_timeout_micros, num_batch_threads and other parameters? Tried using these parameters with the Query client, it doesn't work.

In the below example I have 100 images and I want to batch in size of 10. The query runs for all images instead of 10.

bazel-bin/tensorflow_serving/example/demo_batch --server=localhost:9000 --max_batch_size=10

Also, for batch scheduling how to make it run every 10 secs after the first batch is done? Thanks.

Body:
I have met the same problem like you.

And I checked the source code of tf-serving, these parameters are in an protobuf file which defined in:

serving/tensorflow_serving/servables/tensorflow/session_bundle_config.proto

And I found the example conf file in:

serving/tensorflow_serving/servables/tensorflow/testdata/batching_config.txt

And I believe you could follow the batching_config.txt format, the parameters config should be work.

Hope it helps.

max_batch_size { value: 1024 }
batch_timeout_micros { value: 0 }
max_enqueued_batches { value: 1000000 }
num_batch_threads { value: 8 }
allowed_batch_sizes : 1
allowed_batch_sizes : 2
allowed_batch_sizes : 8
allowed_batch_sizes : 32
allowed_batch_sizes : 128
allowed_batch_sizes : 256
allowed_batch_sizes : 512
allowed_batch_sizes : 1024


问:
Expert R users, what's in your .Rprofile?
I have always found startup profile files of other people both useful and instructive about the language. Moreover, while I have some customization for Bash and Vim, I have nothing for R.

For example, one thing I always wanted is different colors for input and output text in a window terminal, and maybe even syntax highlighting.

答:
Here's mine, including some of the mentioned ideas.

Two things you might want to look at:

.set.width() / w() update your print width to the one of the terminal. Unfortunately I did not find a way to do this automatically on terminal resize - R documentation mentions this is done by some R interpreters.

history is saved every time together with a timestamp and the working directory

.

```<code>.set.width <- function() {
  cols <- as.integer(Sys.getenv("COLUMNS"))
  if (is.na(cols) || cols > 10000 || cols < 10)
    options(width=100)
  options(width=cols)
}

.First <- function() {
  options(digits.secs=3)              # show sub-second time stamps
  options(max.print=1000)             # do not print more than 1000 lines
  options("report" = c(CRAN="http://cran.at.r-project.org"))
  options(prompt="R> ", digits=4, show.signif.stars=FALSE)
}

# aliases
w <- .set.width

.Last <- function() {
  if (!any(commandArgs()=='--no-readline') && interactive()){
    timestamp(,prefix=paste("##------ [",getwd(),"] ",sep=""))
    try(savehistory("~/.Rhistory"))
   }
}
</code>```

Body:
Here's mine, including some of the mentioned ideas.

Two things you might want to look at:

.set.width() / w() update your print width to the one of the terminal. Unfortunately I did not find a way to do this automatically on terminal resize - R documentation mentions this is done by some R interpreters.

history is saved every time together with a timestamp and the working directory

.

.set.width <- function() {
  cols <- as.integer(Sys.getenv("COLUMNS"))
  if (is.na(cols) || cols > 10000 || cols < 10)
    options(width=100)
  options(width=cols)
}

.First <- function() {
  options(digits.secs=3)              # show sub-second time stamps
  options(max.print=1000)             # do not print more than 1000 lines
  options("report" = c(CRAN="http://cran.at.r-project.org"))
  options(prompt="R> ", digits=4, show.signif.stars=FALSE)
}

# aliases
w <- .set.width

.Last <- function() {
  if (!any(commandArgs()=='--no-readline') && interactive()){
    timestamp(,prefix=paste("##------ [",getwd(),"] ",sep=""))
    try(savehistory("~/.Rhistory"))
   }
}


问:
How to get height of div which contains dynamically added image?
I have a little script that add images to some columns. I would like it to add images to the smallest column. But when I try to get the height of the columns it always return 30px (surely because the images are not loaded yet)

Here is some code :

```<code><div id="diaporama-col1" class="col-xs-4">

</div>
<div id="diaporama-col2" class="col-xs-4">

</div>
<div id="diaporama-col3" class="col-xs-4">

</div>
</code>```

.

```<code>var listImgDiaporama=["resources/img/img-1.jpg", "resources/img/img-2.jpg", "resources/img/img-3.jpg", "resources/img/img-4.jpg", "resources/img/img-5.jpg", "resources/img/img-6.jpg", "resources/img/img-7.jpg", "resources/img/img-8.jpg", "resources/img/img-9.jpg", "resources/img/img-10.jpg", "resources/img/img-11.jpg"];
function addImgToDiaporama() {

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

        var col1Height = $("#diaporama-col1").height();
        var col2Height = $("#diaporama-col2").height();
        var col3Height = $("#diaporama-col3").height();

        if (col1Height <= col2Height && col1Height <= col3Height) {
            $("#diaporama-col1").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        } else if (col2Height <= col1Height && col2Height <= col3Height) {
            $("#diaporama-col2").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        } else {
            $("#diaporama-col3").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        }
    }
}
</code>```

Is there a way to make this work ?

答:
If your images are all being added in one js call (e.g. its just looping through an array of images, rather than on click of a button)

I have added a delay between each image just for demo purposes, feel free to remove it for live.

https://jsfiddle.net/g6L7mbp7/3/

$numberOfImages = 5

// Create an array of varying sized images
$images = [];
i = 0;
while (i < $numberOfImages ){
 $images[i] = getRandImage();
  i++;
}

// click button to bein inserting images
$('#addImage').click(function(){

 $($images).each(function(index,image){

    //remove the timeout bit for live, just here to demonstrate that its adding the images to the right columns
    setTimeout(function () {

      $shortest_column = getShortestColumn();
        $($shortest_column).append(image);

    }, index*500);

 });

});

function addImage($image){
  $shortest_column = getShortestColumn();
  $($shortest_column).append($image);
}

function getShortestColumn(){

  var shortest_column = null;
  var shortest = 999999999;
  $(".column").each(function(){
    var height = $(this).height();
    if(height < shortest){
       shortest = height;
       shortest_column = $(this);
    }
  });

  return shortest_column;
}

   function getRandImage(){
   $rn = Math.floor(Math.random() * 10) + 1
   if ($rn % 2){$image = "";}
   else {$image = "";}

   return $image;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.column {
  width:30%;
  margin-left:1%;
  margin-right:1%;
  float:left;
  background: #222;
  text-align: center;
}
img {
  max-width:100%;
}</code>```

  <button id="addImage">Add Images</button>

```

Body:
I have a little script that add images to some columns. I would like it to add images to the smallest column. But when I try to get the height of the columns it always return 30px (surely because the images are not loaded yet)

Here is some code :

.

var listImgDiaporama=["resources/img/img-1.jpg", "resources/img/img-2.jpg", "resources/img/img-3.jpg", "resources/img/img-4.jpg", "resources/img/img-5.jpg", "resources/img/img-6.jpg", "resources/img/img-7.jpg", "resources/img/img-8.jpg", "resources/img/img-9.jpg", "resources/img/img-10.jpg", "resources/img/img-11.jpg"];
function addImgToDiaporama() {

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

        var col1Height = $("#diaporama-col1").height();
        var col2Height = $("#diaporama-col2").height();
        var col3Height = $("#diaporama-col3").height();

        if (col1Height <= col2Height && col1Height <= col3Height) {
            $("#diaporama-col1").append("")
        } else if (col2Height <= col1Height && col2Height <= col3Height) {
            $("#diaporama-col2").append("")
        } else {
            $("#diaporama-col3").append("")
        }
    }
}

Is there a way to make this work ?

Body:
If your images are all being added in one js call (e.g. its just looping through an array of images, rather than on click of a button)

I have added a delay between each image just for demo purposes, feel free to remove it for live.

https://jsfiddle.net/g6L7mbp7/3/

$numberOfImages = 5

// Create an array of varying sized images
$images = [];
i = 0;
while (i < $numberOfImages ){
 $images[i] = getRandImage();
  i++;
}

// click button to bein inserting images
$('#addImage').click(function(){

 $($images).each(function(index,image){

    //remove the timeout bit for live, just here to demonstrate that its adding the images to the right columns
    setTimeout(function () {

      $shortest_column = getShortestColumn();
        $($shortest_column).append(image);

    }, index*500);

 });

});

function addImage($image){
  $shortest_column = getShortestColumn();
  $($shortest_column).append($image);
}

function getShortestColumn(){

  var shortest_column = null;
  var shortest = 999999999;
  $(".column").each(function(){
    var height = $(this).height();
    if(height < shortest){
       shortest = height;
       shortest_column = $(this);
    }
  });

  return shortest_column;
}

   function getRandImage(){
   $rn = Math.floor(Math.random() * 10) + 1
   if ($rn % 2){$image = "<img src='http://lorempixel.com/200/100/'>";}
   else {$image = "<img src='http://lorempixel.com/200/200/'>";}

   return $image;
}

.column {
  width:30%;
  margin-left:1%;
  margin-right:1%;
  float:left;
  background: #222;
  text-align: center;
}
img {
  max-width:100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>
  <center><button id="addImage">Add Images</button></center>
</div>
<hr>
<div class="column" id="column1">
  <img src="http://lorempixel.com/200/100/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column2">
  <img src="http://lorempixel.com/200/150/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column3">
  <img src="http://lorempixel.com/200/150/" alt="">
  <img src="http://lorempixel.com/200/100/" alt="">
</div>


问:
how to get character position in pytesseract
I am trying to get character position of image files using pytesseract library .

```<code>import pytesseract
from PIL import Image
print pytesseract.image_to_string(Image.open('5.png'))
</code>```

Is there any library for getting each position of character

答:
Using pytesseract doesn't seem the best idea to have the position but you can do this : </p>

```<code>from pytesseract import pytesseract
pytesseract.run_tesseract('image.png', 'output', lang=None, boxes=False, config="hocr")
</code>```

Body:
I am trying to get character position of image files using pytesseract library .

import pytesseract
from PIL import Image
print pytesseract.image_to_string(Image.open('5.png'))

Is there any library for getting each position of character

Body:
Using pytesseract doesn't seem the best idea to have the position but you can do this :

from pytesseract import pytesseract
pytesseract.run_tesseract('image.png', 'output', lang=None, boxes=False, config="hocr")


问:
WPF: ItemContainerGenerator.Status = not started
I have a datagrid where every column has a combobox as header. Each combobox has its source binded to an observable collection of string. I've made all of this by code behind, since the number of columns of the datagrid are unknown at design time.

When the user choose an item, in each combobox, that item should be disabled after the selection changed. So i tried to do a loop like this:

```<code>private void Test_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (vm.myArray == null)
        { vm.myArray = new string[myGrid.Columns.Count]; }
        ComboBox cb = sender as ComboBox;
        DataGridColumnHeader parent = cb.Parent as DataGridColumnHeader;
        int index = parent.Column.DisplayIndex;
        string value = cb.SelectedItem as string;
        vm.mYArray[index] = value;
        foreach(DataGridColumn c in griglia.Columns)
        {
            foreach(string s in vm.myArray)
            {
                if(s != null && s != string.Empty)
                {
                    ComboBox dg = c.Header as ComboBox;
                    for (int i = 0; i < dg.Items.Count; i++)
                    {
                        ComboBoxItem it = (ComboBoxItem)dg.ItemContainerGenerator.ContainerFromIndex(i);
                        if ((string)it.Content == s)
                            it.IsEnabled = false;
                        else
                            it.IsEnabled = true;
                    }
                }
            }
        }
    }
</code>```

The problem is that when the loop on the columns reach the second iteration, my code raise an exception. After a deep look into my local variables, i noticed that ItemContainerGenerator.Status is NotStarted everywhere except for the combobox in the first column. Can you provide me an help on how to solve this problem?

答:
It seems that I've found a solution. I needed to add this piece of code in the inner loop:

```<code>if(dg.ItemContainerGenerator.Status == GeneratorStatus.NotStarted)
{
    dg.IsDropDownOpen = true;
    this.UpdateLayout();
    dg.IsDropDownOpen = false;
}
</code>```

It seems the problem was that the ItemContainerGenerator is not generated until every ComboBoxItem is not generated. To do this you should trick the UI to believe that each ComboBox was opened at least once.

If you know better answer please let me know.

Body:
I have a datagrid where every column has a combobox as header. Each combobox has its source binded to an observable collection of string. I've made all of this by code behind, since the number of columns of the datagrid are unknown at design time.

When the user choose an item, in each combobox, that item should be disabled after the selection changed. So i tried to do a loop like this:

private void Test_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (vm.myArray == null)
        { vm.myArray = new string[myGrid.Columns.Count]; }
        ComboBox cb = sender as ComboBox;
        DataGridColumnHeader parent = cb.Parent as DataGridColumnHeader;
        int index = parent.Column.DisplayIndex;
        string value = cb.SelectedItem as string;
        vm.mYArray[index] = value;
        foreach(DataGridColumn c in griglia.Columns)
        {
            foreach(string s in vm.myArray)
            {
                if(s != null && s != string.Empty)
                {
                    ComboBox dg = c.Header as ComboBox;
                    for (int i = 0; i < dg.Items.Count; i++)
                    {
                        ComboBoxItem it = (ComboBoxItem)dg.ItemContainerGenerator.ContainerFromIndex(i);
                        if ((string)it.Content == s)
                            it.IsEnabled = false;
                        else
                            it.IsEnabled = true;
                    }
                }
            }
        }
    }

The problem is that when the loop on the columns reach the second iteration, my code raise an exception. After a deep look into my local variables, i noticed that ItemContainerGenerator.Status is NotStarted everywhere except for the combobox in the first column. Can you provide me an help on how to solve this problem?

Body:
It seems that I've found a solution. I needed to add this piece of code in the inner loop:

if(dg.ItemContainerGenerator.Status == GeneratorStatus.NotStarted)
{
    dg.IsDropDownOpen = true;
    this.UpdateLayout();
    dg.IsDropDownOpen = false;
}

It seems the problem was that the ItemContainerGenerator is not generated until every ComboBoxItem is not generated. To do this you should trick the UI to believe that each ComboBox was opened at least once.

If you know better answer please let me know.


答:
Yes, we can use like below code, and in primary constructor for data class should have min one parameter. </p>

```<code>data class SampleData(val name: String, val age: Int) {
    constructor(name: String, age: Int, email: String) : this(name, age) {

    }
}
</code>```

Title: Can Kotlin data class have more than one constructor?

Body:
I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age: Int)

Is it possible to declare a second constructor for that data class?

Body:
Yes, we can use like below code, and in primary constructor for data class should have min one parameter.

data class SampleData(val name: String, val age: Int) {
    constructor(name: String, age: Int, email: String) : this(name, age) {

    }
}


问:
Floating exponent exponentiation algorithm
I must to write a algorithm that exponentiates a base (integer or float) in a integer or float argument. I wrote this algorithm for Deluge (zoho.com), but it can only use integer exponents:

```<code>float math.potencia(float base, int expoente)
{
   if(expoente>0)
    {
    base = base * thisapp.math.potencia(base, (input.expoente  -  1));
    }
    else if (expoente == 0)
    {
    base = 1;
    }
    return base;
}
</code>```

(Deluge doesn't have a potentiation operator or function). Thanks!

答:
Well, more than 17 hours without a reply, finally I've found an answer to my own question:

In the simplest way, we can solve the problem using the value of "e" exponentiating to the logarithm of the number divided by the index:

e^(Log(number)/index)

where number is the radicand and index is the desired root.

Eg: The 10th root of the number 1024:
e^(Log(1024)/10) = 2.

PS: the base of the Log function is also "e".
the rounded value for "e" is: 2.718281828459045

I hope this technique may be usefull for you.

Body:
I must to write a algorithm that exponentiates a base (integer or float) in a integer or float argument. I wrote this algorithm for Deluge (zoho.com), but it can only use integer exponents:

float math.potencia(float base, int expoente)
{
   if(expoente>0)
    {
    base = base * thisapp.math.potencia(base, (input.expoente  -  1));
    }
    else if (expoente == 0)
    {
    base = 1;
    }
    return base;
}

(Deluge doesn't have a potentiation operator or function). Thanks!


问:
Why some methods in JavaScript make a copy of the object invoked?
In JavaScript, some methods make a copy of the object that invoked it while others do not.

For example:

```<code>var numbers = [1, 2, 3, 4, 5];
numbers.map(function(x) { return x + 1 });
console.log(numbers); // [1, 2, 3, 4, 5];
</code>```

It makes a copy of "numbers" that you have to set to another variable.

Whereas:

```<code>var numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1];
</code>```

It changes the "numbers" directly. Could anyone please explain why?

答:
This is due to the difference in time of incorporation of methods into the JavaScript.

Method reverse was there from the first version of ECMAScript.

The map was added relatively recently in the 5th version.

There is a trend to be more functional nowadays among languages. One of the main principles in functional languages is immutability of data. Therefore, these new methods of the array (namely map, filter etc) are functional and do not the change source array.

Body:
In JavaScript, some methods make a copy of the object that invoked it while others do not.

For example:

var numbers = [1, 2, 3, 4, 5];
numbers.map(function(x) { return x + 1 });
console.log(numbers); // [1, 2, 3, 4, 5];

It makes a copy of "numbers" that you have to set to another variable.

Whereas:

var numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1];

It changes the "numbers" directly. Could anyone please explain why?