问:
How can I apply weights in this scipy least squares optimization routine?
I am trying to do a generalized least squares fit to find the best fitting line through some (x,y) data points. I was able to do this via scipy, but I am having trouble applying weights. I would like to get the weights from the residuals of the original fit and attempt a refitting via least squares using the weights. The weights should be the inverse of the residuals, but since -1 < residuals < 1 and this is just an example, I'm okay with using the residuals as the weights.

The (x,y) data points are calculated elsewhere, and the goal is to find an alpha (1/slope) and intercept for the best fitting line y = x/alpha + intercept.

My code is as follows:

```<code>import numpy as np
from scipy.optimize import least_squares

ydata = [9.7372923, 10.0587245, 10.3838510, 10.6931371, 10.9616260, 11.1833220, 11.3806770, 11.5248917, 11.7353000]
xdata = np.array([j+5 for j in range(len(ydata))])

def get_weights(resid):
    """
    This function calculates the weights per (x,y) by using the inverse of the squared residuals divided by the total sum of the inverse of the squared residuals.
    This might be incorrect but should work for the sake of example.
    """
    total = sum([abs(resid[i]) for i in range(len(resid))])
    fract = np.array([resid[i]/total for i in range(len(resid))])
    return fract

def get_least_squares_fit(xs, ys):
    """
    This function finds alpha (1/slope) and the y-intercept in the equation
    of a line y = x / alpha + intercept = mx + b
    """
    ## SPECIFY INITIAL GUESS OF OPTIMIZED PARAMETERS
    params_guess = [1/3, 9] ## ps = [alpha, intercept]
    ## DEFINE FITTING FUNCTIONS
    fit_func = lambda ps,x : x/ps[0] + ps[1]
    err_func = lambda ps,x,y : fit_func(ps,x) - y
    ## GET OPTIMIZED PARAMETERS, RESIDUALS & WEIGHTS
    res = least_squares(err_func, params_guess, args=(xs, ys))
    alpha, intercept, residuals = res.x[0], res.x[1], res.fun
    weights = get_weights(residuals)
    return alpha, intercept, residuals, weights

alpha, intercept, residuals, weights = get_least_squares_fit(xdata, ydata)

print(alpha, intercept)
>> 4.03378447722 8.6198247828

print(residuals)
>>  [ 0.12206326  0.04853721 -0.02868313 -0.09006308 -0.11064582 -0.08443567
-0.03388451  0.06980694  0.1073048 ]
</code>```

I get identical results using scipy curve_fit, which has sigma and absolute_sigma. I'm guessing this is the best way to proceed. I'm still trying to figure it out though.

答:
I believe this works correctly. The idea is that each residual should be multiplied with the corresponding weight. The function to minimize is the sum of these products. Rather than use an external module to do the least squares fitting, I used good ol' scipy.optimize.minimize, which gives identical results for the unweighted least squares fit (get_gls_fit(..., weights=None, ...)) and the results of the external modules.

```<code>import numpy as np
from scipy import optimize
## same xdata and ydata as stated in question

def guess_initial_parameters(xs, ys):
    """
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    """
    ## GUESS SLOPE
    slope = (ys[-1]-ys[0])/(xs[-1]-xs[0])
    alpha = 1/slope
    ## GUESS INTERCEPT
    intercept = np.mean([ys[-1] - xs[-1]/alpha, ys[0] - xs[0]/alpha])
    return [alpha, intercept]

def update_weights(residuals, power=1):
    """
    residuals   :   type<list> or type<array>
    power       :   type<float>
    """
    ## INVERT RESIDUALS
    invs = [1/residuals[idr] for idr in range(len(residuals))]
    ## NORMALIZE RESIDUALS
    invs = [abs(inv)**power for inv in invs]
    total = sum(invs)
    return [invs[idv]/total for idv in range(len(invs))]

def fit_func(ps, xs):
    """
    ps          :   [alpha, intercept]
    xs          :   type<list> or type<array>
    """
    ## FIT TO EQUATION OF LINE
    return [xs[idx]/ps[0] + ps[1] for idx in range(len(xs))] ## alpha = 1/slope

def get_residuals(ps, xs, ys):
    """
    ps          :   [alpha, intercept]
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    """
    ## GET LINEAR FIT
    ys_trial = fit_func(ps, xs)
    ## GET RESIDUALS
    residuals = [(ys[idx] -  ys_trial[idx])**2 for idx in range(len(ys))]
    return residuals

def err_func(ps, xs, ys, wts):
    """
    ps          :   [alpha, intercept]
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    wts         :   type<list> or type<array>
    """
    ## GET RESIDUALS
    residuals = get_residuals(ps, xs, ys)
    ## SUM WEIGHTED RESIDUALS
    return sum([wts[idr] * residuals[idr] for idr in range(len(residuals))])

def get_gls_fit(xs, ys, ps_init, weights=None, power=2, routine='Nelder-Mead'):
    """
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    ps_init     :   [alpha, intercept]
    weights     :   None or type<list> or type<array>
    power       :   type<float>
    routine     :   'Nelder-Mead'
    """
    ## GET INITIAL PARAMETER GUESS
    if type(ps_init) == (list or np.array):
        pass
    elif ps_init == 'estimate':
        ps_init = guess_initial_parameters(xs, ys)
    else:
        raise ValueError("ps_init = type<list> or type<array> or 'estimate'")
    ## GET WEIGHTS
    if weights is None:
        wts = np.ones(len(xs))
        print(">>>>>>>>>>>\nORDINARY LEAST SQUARES (OLS) FIT:")
    else:
        wts = weights[:]
        print(">>>>>>>>>>>\nGENERALIZED LEAST SQUARES (GLS) FIT:")
    ## MINIMIZE SUM OF WEIGHTED RESIDUALS
    ans = optimize.minimize(err_func, x0=ps_init, args=(xs, ys, wts,), method=routine)
    ## GET OPTIMIZED PARAMETERS
    alpha, intercept = ans.x[0], ans.x[1]
    ## GET RESIDUALS
    residuals = np.array(get_residuals([alpha, intercept], xs, ys))
    ## GET UPDATED WEIGHTS FOR REFITTING
    wts_upd = np.array(update_weights(residuals, power))
    ## PRINT & RETURN RESULTS
    print("\n   ALPHA = %.3f, INTERCEPT = %.3f" %(alpha, intercept))
    print("\n   RESIDUALS:  \n", residuals)
    print("\n   WEIGHTS (used): \n", wts)
    print("\n   WEIGHTS (updated):  \n", wts_upd, "\n\n")
    return [alpha, intercept], residuals, wts_upd
</code>```

Output:

```<code>[alpha_og, intercept_og], residuals_og, wts_og = get_gls_fit(xdata, ydata, ps_init='estimate')
[alpha_up, intercept_up], residuals_up, wts_up = get_gls_fit(xdata, ydata, ps_init=[alpha_og, intercept_og], weights=wts_og)

>>>>>>>>>>>
ORDINARY LEAST SQUARES (OLS) FIT:

   ALPHA = 4.034, INTERCEPT = 8.620

   RESIDUALS:
 [ 0.01489916  0.00235566  0.00082289  0.00811204  0.01224353  0.00713032
  0.0011486   0.00487199  0.01151256]

   WEIGHTS (used):
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.]

   WEIGHTS (updated):
 [ 0.00179424  0.07177589  0.58819594  0.00605264  0.002657    0.00783406
  0.3019051   0.01678001  0.00300511]

>>>>>>>>>>>
GENERALIZED LEAST SQUARES (GLS) FIT:

   ALPHA = 3.991, INTERCEPT = 8.621

   RESIDUALS:
 [  1.86965273e-02   4.34039033e-03   7.51041961e-05   4.53922546e-03
   7.27337443e-03   3.18112777e-03   1.00990091e-05   1.06473505e-02
   2.05510268e-02]

   WEIGHTS (used):
 [ 0.00179424  0.07177589  0.58819594  0.00605264  0.002657    0.00783406
  0.3019051   0.01678001  0.00300511]

   WEIGHTS (updated):
 [  2.86578120e-07   5.31749819e-06   1.77597366e-02   4.86184846e-06
   1.89362088e-06   9.89925930e-06   9.82216884e-01   8.83653134e-07
   2.37190819e-07]
</code>```

Body:
I am trying to do a generalized least squares fit to find the best fitting line through some (x,y) data points. I was able to do this via scipy, but I am having trouble applying weights. I would like to get the weights from the residuals of the original fit and attempt a refitting via least squares using the weights. The weights should be the inverse of the residuals, but since -1 < residuals < 1 and this is just an example, I'm okay with using the residuals as the weights.

The (x,y) data points are calculated elsewhere, and the goal is to find an alpha (1/slope) and intercept for the best fitting line y = x/alpha + intercept.

My code is as follows:

import numpy as np
from scipy.optimize import least_squares

ydata = [9.7372923, 10.0587245, 10.3838510, 10.6931371, 10.9616260, 11.1833220, 11.3806770, 11.5248917, 11.7353000]
xdata = np.array([j+5 for j in range(len(ydata))])

def get_weights(resid):
    """
    This function calculates the weights per (x,y) by using the inverse of the squared residuals divided by the total sum of the inverse of the squared residuals.
    This might be incorrect but should work for the sake of example.
    """
    total = sum([abs(resid[i]) for i in range(len(resid))])
    fract = np.array([resid[i]/total for i in range(len(resid))])
    return fract

def get_least_squares_fit(xs, ys):
    """
    This function finds alpha (1/slope) and the y-intercept in the equation
    of a line y = x / alpha + intercept = mx + b
    """
    ## SPECIFY INITIAL GUESS OF OPTIMIZED PARAMETERS
    params_guess = [1/3, 9] ## ps = [alpha, intercept]
    ## DEFINE FITTING FUNCTIONS
    fit_func = lambda ps,x : x/ps[0] + ps[1]
    err_func = lambda ps,x,y : fit_func(ps,x) - y
    ## GET OPTIMIZED PARAMETERS, RESIDUALS & WEIGHTS
    res = least_squares(err_func, params_guess, args=(xs, ys))
    alpha, intercept, residuals = res.x[0], res.x[1], res.fun
    weights = get_weights(residuals)
    return alpha, intercept, residuals, weights

alpha, intercept, residuals, weights = get_least_squares_fit(xdata, ydata)

print(alpha, intercept)
>> 4.03378447722 8.6198247828

print(residuals)
>>  [ 0.12206326  0.04853721 -0.02868313 -0.09006308 -0.11064582 -0.08443567
-0.03388451  0.06980694  0.1073048 ]

I get identical results using scipy curve_fit, which has sigma and absolute_sigma. I'm guessing this is the best way to proceed. I'm still trying to figure it out though.

Body:
I believe this works correctly. The idea is that each residual should be multiplied with the corresponding weight. The function to minimize is the sum of these products. Rather than use an external module to do the least squares fitting, I used good ol' scipy.optimize.minimize, which gives identical results for the unweighted least squares fit (get_gls_fit(..., weights=None, ...)) and the results of the external modules.

import numpy as np
from scipy import optimize
## same xdata and ydata as stated in question

def guess_initial_parameters(xs, ys):
    """
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    """
    ## GUESS SLOPE
    slope = (ys[-1]-ys[0])/(xs[-1]-xs[0])
    alpha = 1/slope
    ## GUESS INTERCEPT
    intercept = np.mean([ys[-1] - xs[-1]/alpha, ys[0] - xs[0]/alpha])
    return [alpha, intercept]

def update_weights(residuals, power=1):
    """
    residuals   :   type<list> or type<array>
    power       :   type<float>
    """
    ## INVERT RESIDUALS
    invs = [1/residuals[idr] for idr in range(len(residuals))]
    ## NORMALIZE RESIDUALS
    invs = [abs(inv)**power for inv in invs]
    total = sum(invs)
    return [invs[idv]/total for idv in range(len(invs))]

def fit_func(ps, xs):
    """
    ps          :   [alpha, intercept]
    xs          :   type<list> or type<array>
    """
    ## FIT TO EQUATION OF LINE
    return [xs[idx]/ps[0] + ps[1] for idx in range(len(xs))] ## alpha = 1/slope

def get_residuals(ps, xs, ys):
    """
    ps          :   [alpha, intercept]
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    """
    ## GET LINEAR FIT
    ys_trial = fit_func(ps, xs)
    ## GET RESIDUALS
    residuals = [(ys[idx] -  ys_trial[idx])**2 for idx in range(len(ys))]
    return residuals

def err_func(ps, xs, ys, wts):
    """
    ps          :   [alpha, intercept]
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    wts         :   type<list> or type<array>
    """
    ## GET RESIDUALS
    residuals = get_residuals(ps, xs, ys)
    ## SUM WEIGHTED RESIDUALS
    return sum([wts[idr] * residuals[idr] for idr in range(len(residuals))])

def get_gls_fit(xs, ys, ps_init, weights=None, power=2, routine='Nelder-Mead'):
    """
    xs          :   type<list> or type<array>
    ys          :   type<list> or type<array>
    ps_init     :   [alpha, intercept]
    weights     :   None or type<list> or type<array>
    power       :   type<float>
    routine     :   'Nelder-Mead'
    """
    ## GET INITIAL PARAMETER GUESS
    if type(ps_init) == (list or np.array):
        pass
    elif ps_init == 'estimate':
        ps_init = guess_initial_parameters(xs, ys)
    else:
        raise ValueError("ps_init = type<list> or type<array> or 'estimate'")
    ## GET WEIGHTS
    if weights is None:
        wts = np.ones(len(xs))
        print(">>>>>>>>>>>\nORDINARY LEAST SQUARES (OLS) FIT:")
    else:
        wts = weights[:]
        print(">>>>>>>>>>>\nGENERALIZED LEAST SQUARES (GLS) FIT:")
    ## MINIMIZE SUM OF WEIGHTED RESIDUALS
    ans = optimize.minimize(err_func, x0=ps_init, args=(xs, ys, wts,), method=routine)
    ## GET OPTIMIZED PARAMETERS
    alpha, intercept = ans.x[0], ans.x[1]
    ## GET RESIDUALS
    residuals = np.array(get_residuals([alpha, intercept], xs, ys))
    ## GET UPDATED WEIGHTS FOR REFITTING
    wts_upd = np.array(update_weights(residuals, power))
    ## PRINT & RETURN RESULTS
    print("\n   ALPHA = %.3f, INTERCEPT = %.3f" %(alpha, intercept))
    print("\n   RESIDUALS:  \n", residuals)
    print("\n   WEIGHTS (used): \n", wts)
    print("\n   WEIGHTS (updated):  \n", wts_upd, "\n\n")
    return [alpha, intercept], residuals, wts_upd

Output:

[alpha_og, intercept_og], residuals_og, wts_og = get_gls_fit(xdata, ydata, ps_init='estimate')
[alpha_up, intercept_up], residuals_up, wts_up = get_gls_fit(xdata, ydata, ps_init=[alpha_og, intercept_og], weights=wts_og)

>>>>>>>>>>>
ORDINARY LEAST SQUARES (OLS) FIT:

   ALPHA = 4.034, INTERCEPT = 8.620

   RESIDUALS:
 [ 0.01489916  0.00235566  0.00082289  0.00811204  0.01224353  0.00713032
  0.0011486   0.00487199  0.01151256]

   WEIGHTS (used):
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.]

   WEIGHTS (updated):
 [ 0.00179424  0.07177589  0.58819594  0.00605264  0.002657    0.00783406
  0.3019051   0.01678001  0.00300511]

>>>>>>>>>>>
GENERALIZED LEAST SQUARES (GLS) FIT:

   ALPHA = 3.991, INTERCEPT = 8.621

   RESIDUALS:
 [  1.86965273e-02   4.34039033e-03   7.51041961e-05   4.53922546e-03
   7.27337443e-03   3.18112777e-03   1.00990091e-05   1.06473505e-02
   2.05510268e-02]

   WEIGHTS (used):
 [ 0.00179424  0.07177589  0.58819594  0.00605264  0.002657    0.00783406
  0.3019051   0.01678001  0.00300511]

   WEIGHTS (updated):
 [  2.86578120e-07   5.31749819e-06   1.77597366e-02   4.86184846e-06
   1.89362088e-06   9.89925930e-06   9.82216884e-01   8.83653134e-07
   2.37190819e-07]


来源: stackexchange

问:
Oracle Data Type for text file?
I need to create a table in Oracle that will store a series of large text files.  After looking at the Oracle datatype's it is unclear what type I should use to store the files.

The limits on the text specific types like VARCHAR2 seem very small (32K).  The other types don't seem to be the right match for a text file (e.g. BFILE).

Does anyone have an opinion on the right type to use?

答:
The LOB datatypes for character data are CLOB and NCLOB.
They can store up to 8 terabytes of character data (CLOB) or national character set data (NCLOB).

Later Oracle recommends that you convert existing LONG RAW columns to LOB columns. LOB columns are subject to far fewer restrictions than LONG columns. Further, LOB functionality is enhanced in every release, whereas LONG RAW functionality has been static for several releases.

ContentLicense: CC BY-SA 2.5

Title: Oracle Data Type for text file?


问:
fetch all elements dom jquery
I have 2 classes and I want to fetch them all in the DOM of a page to compare their content text with jQuery. I believe that in JS it is something like:

function myFonction() {
  var item = document.getElementsByClassName("title")[0];
  if (item) {
    for (var i = 0; i < document.getElementsByClassName("title2").length; i++) {
      var content = document.getElementsByClassName("title2")[i].innerHTML.trim();
      if (content == item.innerHTML.trim()) {
        console.log("OK");
      }
    }
  }
}
myFonction();```

答:
Since you have tagged jQuery in your answer, I will provide a jQuery-based solution. Things are a little more straightforward because you don't need to make messy for loops.

What you want to do is:

Cache/store the inner HTML of the first occurring .title element

If the .title element exists, iterate through all .title2 elements and compare their inner HTML against the cached one in point #1

I have provided a proof-of-concept example below. Matching elements are highlighted in yellow simply for visual indication.

$(function() {
  var compareTitle = function() {
    var $title = $('.title').first(),
        titleContent = $title.html().trim();

    if ($title.length) {
      $('.title2').each(function() {
        if ($(this).html().trim() === titleContent) {
          console.log('OK');
          $(this).css('background-color', 'yellow');
        }
      });
    }
  }
  compareTitle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div></code>```

If you want it in native JS, that is also not a problem. It's just a bit hairier when doing the for loops ;) also, you can always leverage document.querySelectorAll().

var compareTitle = function() {
  var title = document.querySelectorAll('.title')[0],
      titleContent = title.innerHTML.trim();

  if (title) {
    var title2 = document.querySelectorAll('.title2');
    for (var i=0; i<title2.length; i++) {
      if (title2[i].innerHTML.trim() === titleContent) {
        console.log('OK');
        title2[i].style.backgroundColor = 'yellow';
      }
    }
  }
}
compareTitle();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="title">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div></code>```

ContentLicense: CC BY-SA 3.0

Title: fetch all elements dom jquery

Body:
Since you have tagged jQuery in your answer, I will provide a jQuery-based solution. Things are a little more straightforward because you don't need to make messy for loops.

What you want to do is:

Cache/store the inner HTML of the first occurring .title element

If the .title element exists, iterate through all .title2 elements and compare their inner HTML against the cached one in point #1

I have provided a proof-of-concept example below. Matching elements are highlighted in yellow simply for visual indication.

$(function() {
  var compareTitle = function() {
    var $title = $('.title').first(),
        titleContent = $title.html().trim();

    if ($title.length) {
      $('.title2').each(function() {
        if ($(this).html().trim() === titleContent) {
          console.log('OK');
          $(this).css('background-color', 'yellow');
        }
      });
    }
  }
  compareTitle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>

If you want it in native JS, that is also not a problem. It's just a bit hairier when doing the for loops ;) also, you can always leverage document.querySelectorAll().

var compareTitle = function() {
  var title = document.querySelectorAll('.title')[0],
      titleContent = title.innerHTML.trim();

  if (title) {
    var title2 = document.querySelectorAll('.title2');
    for (var i=0; i<title2.length; i++) {
      if (title2[i].innerHTML.trim() === titleContent) {
        console.log('OK');
        title2[i].style.backgroundColor = 'yellow';
      }
    }
  }
}
compareTitle();

<div class="title">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>
<div class="title2">This is not a title.</div>


问:
Sort array items and preserve order of same elements
Suppose I have this array:

```<code>var array = [
  { name: "border-color", value: "#CCCCCC" },
  { name: "color", value: "#FFFFFF" },
  { name: "background-color", value: "rgb(0, 0, 0)" },
  { name: "background-color", value: "rgba(0, 0, 0, .5)" }
];
</code>```

And this function to sort the array by name:

```<code>array.sort(function(a, b) {
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
});
</code>```

And ECMAScript language specifications that tell me that:

The sort is not necessarily stable (that is, elements that compare
  equal do not necessarily remain in their original order).

So, after sorting, the two items with name = background color could appear in any order i.e.:

```<code>[
  { name: "background-color", value: "rgb(0, 0, 0)" },
  { name: "background-color", value: "rgba(0, 0, 0, .5)" },
  ...
]
</code>```

Or

```<code>[
  { name: "background-color", value: "rgba(0, 0, 0, .5)" },
  { name: "background-color", value: "rgb(0, 0, 0)" },
  ...
]
</code>```

How can I sort the array so that items with same name maintain their relative order? I would rather not hardcode anything.

答:
Since the array contains reference type objet, the index of the element can be determined in the sort function. So we avoid the map before and after the sort.</p>

```<code>sortArray.sort((function(a, b) {
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return this.indexOf(a) - this.indexOf(b);
}).bind(sortArray));
</code>```

Body:
Suppose I have this array:

var array = [
  { name: "border-color", value: "#CCCCCC" },
  { name: "color", value: "#FFFFFF" },
  { name: "background-color", value: "rgb(0, 0, 0)" },
  { name: "background-color", value: "rgba(0, 0, 0, .5)" }
];

And this function to sort the array by name:

array.sort(function(a, b) {
  if (a.name  b.name) return 1;
  return 0;
});

And ECMAScript language specifications that tell me that:

The sort is not necessarily stable (that is, elements that compare
  equal do not necessarily remain in their original order).

So, after sorting, the two items with name = background color could appear in any order i.e.:

[
  { name: "background-color", value: "rgb(0, 0, 0)" },
  { name: "background-color", value: "rgba(0, 0, 0, .5)" },
  ...
]

Or

[
  { name: "background-color", value: "rgba(0, 0, 0, .5)" },
  { name: "background-color", value: "rgb(0, 0, 0)" },
  ...
]

How can I sort the array so that items with same name maintain their relative order? I would rather not hardcode anything.

Body:
Since the array contains reference type objet, the index of the element can be determined in the sort function. So we avoid the map before and after the sort.

sortArray.sort((function(a, b) {
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return this.indexOf(a) - this.indexOf(b);
}).bind(sortArray));


问:
Output by number in a for loop
What is the right syntax of this? I want to output not every result, but I want to output by number. For example from 1 to 20 of results etc. Or only 1st,3rd and 5th numbers of results. Can I make an array of the results?</p>

```<code>for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}
</code>```

答:
You can use foreach instead for and after you put conditions to get out what index you want.</p>

```<code>//If you need an array of results
$results = [];
foreach ($_FILES['file']['name'] as $index => $file) {
  $ext = explode('.', basename($file))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

    //here you can put your conditions
    //example:
    //if you need only index < 20
    if($index < 20){

     //if yo need only odd index: (0,2,4,6 ...)
      if ($index % 2 == 1) {

        //if you need to save only file
        $results[] = $file;

        //if you need to save only index
        $results[] = $index;

        //if you need both (index and file)
        $results[] = [$index,$file];

        //same for your variable $target_path
        //Don't forget: If you use one of above examples you need to comment the others what you don't need.

      }else{
        //here you can do idem as above but for even index (1,3,5 ... etc)
      }
    }

}
</code>```

Title: Output by number in a for loop

Body:
What is the right syntax of this? I want to output not every result, but I want to output by number. For example from 1 to 20 of results etc. Or only 1st,3rd and 5th numbers of results. Can I make an array of the results?

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}

Body:
You can use foreach instead for and after you put conditions to get out what index you want.

//If you need an array of results
$results = [];
foreach ($_FILES['file']['name'] as $index => $file) {
  $ext = explode('.', basename($file))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

    //here you can put your conditions
    //example:
    //if you need only index < 20
    if($index < 20){

     //if yo need only odd index: (0,2,4,6 ...)
      if ($index % 2 == 1) {

        //if you need to save only file
        $results[] = $file;

        //if you need to save only index
        $results[] = $index;

        //if you need both (index and file)
        $results[] = [$index,$file];

        //same for your variable $target_path
        //Don't forget: If you use one of above examples you need to comment the others what you don't need.

      }else{
        //here you can do idem as above but for even index (1,3,5 ... etc)
      }
    }

}


问:
istio: ingress with grpc and http
I have a service listening on two ports; one is http, the other is grpc.
I would like to set up an ingress that can route to both these port, with the same host.

The load balancer would redirect to the http port if http/1.1 is used, and to the grpc port if h2 is used.

Is there a way to do that with istio ?

I made a hello world demonstrating what I am trying to achieve :

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hello-world
  namespace: dev
spec:
  replicas: 1
  template:
    metadata:
      annotations:
        alpha.istio.io/sidecar: injected
        pod.beta.kubernetes.io/init-containers: '[{"args":["-p","15001","-u","1337","-i","172.20.0.0/16"],"image":"docker.io/istio/init:0.1","imagePullPolicy":"Always","name":"init","securityContext":{"capabilities":{"add":["NET_ADMIN"]}}}]'
      labels:
        app: hello-world
    spec:
      containers:
      - name: grpc-server
        image: aguilbau/hello-world-grpc:latest
        ports:
        - name: grpc
          containerPort: 50051
      - name: http-server
        image: nginx:1.7.9
        ports:
        - name: http
          containerPort: 80
      - name: istio-proxy
        args:
        - proxy
        - sidecar
        - -v
        - "2"
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        image: docker.io/istio/proxy:0.1
        imagePullPolicy: Always
        resources: {}
        securityContext:
          runAsUser: 1337
---
apiVersion: v1
kind: Service
metadata:
  name: hello-world
  namespace: dev
spec:
  ports:
  - name: grpc
    port: 50051
  - name: http
    port: 80
  selector:
    app: hello-world
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: hello-world-http
  namespace: dev
  annotations:
    kubernetes.io/ingress.class: "istio"
spec:
  rules:
  - host: hello-world
    http:
      paths:
      - backend:
          serviceName: hello-world
          servicePort: 80
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: hello-world-grpc
  namespace: dev
  annotations:
    kubernetes.io/ingress.class: "istio"
spec:
  rules:
  - host: hello-world
    http:
      paths:
      - backend:
          serviceName: hello-world
          servicePort: 50051
---
</code>```

答: You may be able to do something like that if you move the grpc-server and http-server containers into different pods with unique labels (i.e., different versions of the service, so to speak) and then using Istio route rules, behind the Ingress, split the traffic. A rule with a match for header Upgrade: h2 could send traffic to the grpc version and a default rule would send the rest of the traffic to http one.

Title: istio: ingress with grpc and http

Body:
I have a service listening on two ports; one is http, the other is grpc.
I would like to set up an ingress that can route to both these port, with the same host.

The load balancer would redirect to the http port if http/1.1 is used, and to the grpc port if h2 is used.

Is there a way to do that with istio ?

I made a hello world demonstrating what I am trying to achieve :

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hello-world
  namespace: dev
spec:
  replicas: 1
  template:
    metadata:
      annotations:
        alpha.istio.io/sidecar: injected
        pod.beta.kubernetes.io/init-containers: '[{"args":["-p","15001","-u","1337","-i","172.20.0.0/16"],"image":"docker.io/istio/init:0.1","imagePullPolicy":"Always","name":"init","securityContext":{"capabilities":{"add":["NET_ADMIN"]}}}]'
      labels:
        app: hello-world
    spec:
      containers:
      - name: grpc-server
        image: aguilbau/hello-world-grpc:latest
        ports:
        - name: grpc
          containerPort: 50051
      - name: http-server
        image: nginx:1.7.9
        ports:
        - name: http
          containerPort: 80
      - name: istio-proxy
        args:
        - proxy
        - sidecar
        - -v
        - "2"
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        image: docker.io/istio/proxy:0.1
        imagePullPolicy: Always
        resources: {}
        securityContext:
          runAsUser: 1337
---
apiVersion: v1
kind: Service
metadata:
  name: hello-world
  namespace: dev
spec:
  ports:
  - name: grpc
    port: 50051
  - name: http
    port: 80
  selector:
    app: hello-world
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: hello-world-http
  namespace: dev
  annotations:
    kubernetes.io/ingress.class: "istio"
spec:
  rules:
  - host: hello-world
    http:
      paths:
      - backend:
          serviceName: hello-world
          servicePort: 80
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: hello-world-grpc
  namespace: dev
  annotations:
    kubernetes.io/ingress.class: "istio"
spec:
  rules:
  - host: hello-world
    http:
      paths:
      - backend:
          serviceName: hello-world
          servicePort: 50051
---


问:
Is it possible to detect the time difference between the moment an epoll is generated by the kernel and the moment the Sun JVM reads it?
i.e. Time A = voltage hits the NIC; Time B = Selector from Java NIO package is able to select socket channel for I/O.</p>

答:
Use SO_TIMESTAMP and find a NIC that actually supports timestamps and one that supports timestamps with better than millisecond resolution.  Then you should have a chance if you can get Java to read incoming cmsg ancillary data.

Without good hardware support the packets are going to be tagged by the kernel with most likely a low resolution unstable timer.

(edit #1) Example code in C requiring 2.6.30 or newer kernel I think:

http://www.mjmwired.net/kernel/Documentation/networking/timestamping/timestamping.c

(edit #2) Example code to determine kernel to user-space latency in C:

http://vilimpoc.org/research/ku-latency/

(edit #3) I recommend following the J-OWAMP project which is dependent upon high resolution timers and packet latency testing.  The OWAMP team have been pushing the Linux kernel team for better SO_TIMESTAMP support.

http://www.av.it.pt/jowamp/


问:
Join JSX with JSX
I've got a situation where I have several labels, with separator arrows in between them - sort of like breadcrumbs.

The last label has no arrow after it.

This seems like a perfect situation for .join(), for example:

```<code>[1,2,3,4].join('->');  // "1->2->3->4"
</code>```

But, the labels are JSX, and the join delimiter is JSX as well.

Since .join() expects a string delimiter and converts array elements to strings, it ends up like this:

```<code>[<div />, <div />].join(<hr />); // "[object Object][object Object][object Object]"
</code>```

I've explored the .reduce() solution detailed in other answers but it doesn't seem to work quite right either.  Does anyone have any tips?

答:
Here is a nice way that you can solve it with reduce:</p>

```<code>React.createClass({
  render() {
     <div>
        this.props.data
        .map(t => <div/>)
        .reduce((accu, elem) => {
            return accu === null ? [elem] : [...accu, <hr />, elem]
        }, null)
     </div>
  }
})
</code>```

Title: Join JSX with JSX

Body:
I've got a situation where I have several labels, with separator arrows in between them - sort of like breadcrumbs.

The last label has no arrow after it.

This seems like a perfect situation for .join(), for example:

[1,2,3,4].join('->');  // "1->2->3->4"

But, the labels are JSX, and the join delimiter is JSX as well.

Since .join() expects a string delimiter and converts array elements to strings, it ends up like this:

[
,
].join(
); // "[object Object][object Object][object Object]"

I've explored the .reduce() solution detailed in other answers but it doesn't seem to work quite right either.  Does anyone have any tips?

Body:
Here is a nice way that you can solve it with reduce:

React.createClass({
  render() {
     <div>
        this.props.data
        .map(t => <div/>)
        .reduce((accu, elem) => {
            return accu === null ? [elem] : [...accu, <hr />, elem]
        }, null)
     </div>
  }
})


问:
How to speed up Ionic 2 apps booting time when running on device
I am currently doing an app with ionic 2 angular2 and Typescript. ANd i have a big problem when it comes to launching speed of my app. When i build the app for dev or prod  environment and install it on any device, it takes a lot of time to load.

when i launch the app it displays a white screen that stays for so long which is really annoying considering users won't wait that long.

I did delete the splashscreen cordova plugin and i changed the splashscreen delay to 0 in config.xml but it still take so much time to load.

when starting up my app only does couple of Get requests that is all.
Here is my current Config.xml

```<code><widget id="com.ionicframework.comvltapp596066" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>com.vlt.app</name>
    <description>An awesome Ionic/Cordova app.</description>
    <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="http://ionic.local/*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="2" />
    <preference name="SplashShowOnlyFirstTime" value="true" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="0" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
    </platform>
    <engine name="android" spec="^6.2.3" />
    <engine name="browser" spec="^4.1.0" />
    <plugin name="cordova-plugin-console" spec="1.0.5" />
    <plugin name="cordova-plugin-device" spec="1.1.4" />
    <plugin name="cordova-plugin-googlemaps" spec="^1.4.0">
        <variable name="API_KEY_FOR_ANDROID" value="AIzaSyALRGE9KkSD9Qpng8XR7vUaVNj1teJGhw4" />
    </plugin>
    <plugin name="cordova-plugin-inappbrowser" spec="^1.7.1" />
    <plugin name="cordova-plugin-statusbar" spec="2.2.2" />
    <plugin name="cordova-plugin-whitelist" spec="1.3.1" />
    <plugin name="cordova-sqlite-storage" spec="^2.0.4" />
    <plugin name="ionic-plugin-keyboard" spec="~2.2.1" />
</widget>
</code>```

Please help!

答:
I agree with @Emeka Obianom after many time spent on these launch problems at work with my team. We still have a long start up.

It's a bit less boring with a loading screen on the index.html

You will improve a bit if you minify your javascript.

You can use tools like https://www.guardsquare.com/en/proguard
on android. You can find a free solution for apple too on the web.

Body:
I am currently doing an app with ionic 2 angular2 and Typescript. ANd i have a big problem when it comes to launching speed of my app. When i build the app for dev or prod  environment and install it on any device, it takes a lot of time to load.

when i launch the app it displays a white screen that stays for so long which is really annoying considering users won't wait that long.

I did delete the splashscreen cordova plugin and i changed the splashscreen delay to 0 in config.xml but it still take so much time to load.

when starting up my app only does couple of Get requests that is all.
Here is my current Config.xml

<widget id="com.ionicframework.comvltapp596066" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>com.vlt.app</name>
    <description>An awesome Ionic/Cordova app.</description>
    <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="http://ionic.local/*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="2" />
    <preference name="SplashShowOnlyFirstTime" value="true" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="0" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
    </platform>
    <engine name="android" spec="^6.2.3" />
    <engine name="browser" spec="^4.1.0" />
    <plugin name="cordova-plugin-console" spec="1.0.5" />
    <plugin name="cordova-plugin-device" spec="1.1.4" />
    <plugin name="cordova-plugin-googlemaps" spec="^1.4.0">
        <variable name="API_KEY_FOR_ANDROID" value="AIzaSyALRGE9KkSD9Qpng8XR7vUaVNj1teJGhw4" />
    </plugin>
    <plugin name="cordova-plugin-inappbrowser" spec="^1.7.1" />
    <plugin name="cordova-plugin-statusbar" spec="2.2.2" />
    <plugin name="cordova-plugin-whitelist" spec="1.3.1" />
    <plugin name="cordova-sqlite-storage" spec="^2.0.4" />
    <plugin name="ionic-plugin-keyboard" spec="~2.2.1" />
</widget>

Please help!


问:
The forked VM terminated without saying properly goodbye. VM crash or System.exit called
Please help me to solve this issue. I do not exactly understand what the error in the log means.</p>

```<code>[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 21.749s
[INFO] Finished at: Thu Apr 24 10:10:20 IST 2014
[INFO] Final Memory: 15M/37M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.15:test (default-test) on project samples.simpleforwarding: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.15:test failed: The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?
[ERROR] Command wascmd.exe /X /C ""C:\Program Files\Java\jdk1.7.0_55\jre\bin\java" -Xmx1024m -XX:MaxPermSize=256m -jar E:\OpenDayLight\controller\opendaylight\samples\simpleforwarding\target\surefire\surefirebooter53410321571238933.jar E:\OpenDayLight\controller\opendaylight\samples\simpleforwarding\target\surefire\surefire86076271125218001tmp E:\OpenDayLight\controller\opendaylight\samples\simpleforwarding\target\surefire\surefire_01846991116135903536tmp"
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
</code>```

答:
This could also happen due to a totally different issue. For example in my case our Jenkins build was failing intermittently while executing tests without any reason.

I sifted through our tests to find any occurrence of System.exit() but there was none.

After more digging I found out that this could be happening because of a JDK bug which could have caused this regression.

JDK-6675699

I am still working on making this fix in our builds, will come back and update the thread again.

Body:
Please help me to solve this issue. I do not exactly understand what the error in the log means.

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 21.749s
[INFO] Finished at: Thu Apr 24 10:10:20 IST 2014
[INFO] Final Memory: 15M/37M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.15:test (default-test) on project samples.simpleforwarding: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.15:test failed: The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?
[ERROR] Command wascmd.exe /X /C ""C:\Program Files\Java\jdk1.7.0_55\jre\bin\java" -Xmx1024m -XX:MaxPermSize=256m -jar E:\OpenDayLight\controller\opendaylight\samples\simpleforwarding\target\surefire\surefirebooter53410321571238933.jar E:\OpenDayLight\controller\opendaylight\samples\simpleforwarding\target\surefire\surefire86076271125218001tmp E:\OpenDayLight\controller\opendaylight\samples\simpleforwarding\target\surefire\surefire_01846991116135903536tmp"
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException


问:
mysql automatically prevent redundant inserts
I have a table like

```<code>create table adjacencies(
  relationId int not null primary key auto_increment,
  parent int not null,
  child int not null,
  pathLen int not null
) ;
</code>```

I'm inserting large amounts of entries like

```<code>insert into adjacencies( parent, child, pathLen )
select a, b, c from something where condition ;
</code>```

So sometimes when I run my insert query, its possible that a (parent,child) relation will already exist and be duplicated.  Bad news.

I don't want to create a primary key on ( parent, child ) because that results in a hard fail (query failure).

What I want is a soft fail if there is an attempt to insert a (parent, child) pair that already exists in the table (i.e only that pair gets ignored, and the rest of the query proceeds normally).

What's the best way to do this in MySQL?

(* Wondering why is there a relationId member in this table?)

答:
Use

```<code>INSERT IGNORE ...
</code>```

and create unique index/primary key

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

(c) http://dev.mysql.com/doc/refman/5.1/en/insert.html

Body:
I have a table like

create table adjacencies(
  relationId int not null primary key auto_increment,
  parent int not null,
  child int not null,
  pathLen int not null
) ;

I'm inserting large amounts of entries like

insert into adjacencies( parent, child, pathLen )
select a, b, c from something where condition ;

So sometimes when I run my insert query, its possible that a (parent,child) relation will already exist and be duplicated.  Bad news.

I don't want to create a primary key on ( parent, child ) because that results in a hard fail (query failure).

What I want is a soft fail if there is an attempt to insert a (parent, child) pair that already exists in the table (i.e only that pair gets ignored, and the rest of the query proceeds normally).

What's the best way to do this in MySQL?

(* Wondering why is there a relationId member in this table?)

Body:
Use

INSERT IGNORE ...

and create unique index/primary key

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

(c) http://dev.mysql.com/doc/refman/5.1/en/insert.html


问:
gcc shows 0 for a struct's property but clang shows a different value
Consider this code:

```<code>#include <iostream>
using namespace std;

struct Z
{
    Z() { cout << "ctor Z" << endl; }
};

struct A
{
    A() = default;
    A(int xx) : x(xx) {}
    int x;
    Z z;
};

int main()
{
    A a;
    cout << "a.x = " << a.x << endl;
}
</code>```

Compiled with newest GCC it prints:

```<code>ctor Z
a.x = 0
</code>```

But compiled with newest Clang it prints:

```<code>ctor Z
a.x = 4198800
</code>```

Why? Can someone explain this?
Does GCC initiates the 'x' prinitive value while it doesn't have to do it? Or, maybe Clang doesn't initiante the 'x' with 0, while it should do it?

The same happens when I remove my constructors from the "A" struct, so it is not a matter of the constructor being marked as 'default' or something like that. To put this simply - one compiler generates code which calls constructors of its members being class objects, and also members being primitives. The other compiler runs constructor of only the class objects members.

Why?

答:
You need to initialize x in every constructor, not just one of them. Using the default constructor leaves it uninitialized. GCC might zero it out, or it might be zeroed out when the process is launched. clang is doing it right here by having garbage data; it shows there's a bug.

You could fix this with:

```<code>A(int xx = 0) : x(xx) {}
</code>```

Where the other constructor is no longer required since you've provided a default value.

Body:
Consider this code:

#include <iostream>
using namespace std;

struct Z
{
    Z() { cout << "ctor Z" << endl; }
};

struct A
{
    A() = default;
    A(int xx) : x(xx) {}
    int x;
    Z z;
};

int main()
{
    A a;
    cout << "a.x = " << a.x << endl;
}

Compiled with newest GCC it prints:

ctor Z
a.x = 0

But compiled with newest Clang it prints:

ctor Z
a.x = 4198800

Why? Can someone explain this?
Does GCC initiates the 'x' prinitive value while it doesn't have to do it? Or, maybe Clang doesn't initiante the 'x' with 0, while it should do it?

The same happens when I remove my constructors from the "A" struct, so it is not a matter of the constructor being marked as 'default' or something like that. To put this simply - one compiler generates code which calls constructors of its members being class objects, and also members being primitives. The other compiler runs constructor of only the class objects members.

Why?

Body:
You need to initialize x in every constructor, not just one of them. Using the default constructor leaves it uninitialized. GCC might zero it out, or it might be zeroed out when the process is launched. clang is doing it right here by having garbage data; it shows there's a bug.

You could fix this with:

A(int xx = 0) : x(xx) {}

Where the other constructor is no longer required since you've provided a default value.


问:
ElasticBeanstalk nodejs.log can't find module 'hogan.js'
I have a simple node.js app that is using "hogan": "^1.0.2" (from packages.json under "dependencies").

It has been failing to deploy, and looking in the logs, I am seeing (multiple times):

Error: Cannot find module 'hogan.js'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)

I'm fairly new to node.js on EB, and have just been following http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_express.html with a pre-existing Express app.

Assuming EB runs npm install for me (is that a safe assumption?), what might the issue be?

答:
For what it's worth, I also had an issue similar to this and determined that it was due to file case issues.  In the node EB container, the OS is case-sensitive, and because I was ignoring file case changes in git, it didn't update the file casing in the repository.

You should run git config core.ignorecase false if this is the issue.


问:
Decrease version number
I'm creating a while loop which stops when it reaches a specific version.
The issue is that if I have version 1.1.4 and want to go down to 1.0.9, my awk command that I've found on this forum doesn't do well.

I'm using something like this:

```<code>while compare versions; do

    current version=

    if [[ actual version != current version ]]; then

        currentver=

        previous version=`echo $ current version | awk -F. -v OFS=. \
              'NF==1{print ++$NF};
               NF>1{if(length($NF+1)>length($NF))$(NF-1)++;
               $NF=sprintf("%0*d", length($NF), ($NF-1)%(10^length($NF)));
               print}'`

        Go back to $ previous version

        do something
</code>```

What I get is:

```<code>Go back to 1.1.4

Go back to 1.1.3

Go back to 1.1.2

Go back to 1.1.1

Go back to 1.1.0

Go back to 1.1.-1

Go back to 1.1.-2
</code>```

I want the version number to go to 1.0.9.

How can I change the awk command not to go below 0?

答:
Your question isn't clear so if this isn't what you want:

```<code>$ cat tst.awk
function decrement(old,        n,parts) {
    n = split(old,parts,/\./)
    if ( parts[n] == 0 ) {
        parts[n--] = 9
    }
    parts[n]--
    return (parts[1] "." parts[2] "." parts[3])
}
BEGIN {
    val = "1.1.4"
    while ( val != "1.0.9" ) {
        print val
        val = decrement(val)
    }
    print val
}

$ awk -f tst.awk
1.1.4
1.1.3
1.1.2
1.1.1
1.1.0
1.0.9
</code>```

then edit your question to clarify what you're trying to do and provide testable sample input/output.

Title: Decrease version number

Body:
I'm creating a while loop which stops when it reaches a specific version.
The issue is that if I have version 1.1.4 and want to go down to 1.0.9, my awk command that I've found on this forum doesn't do well.

I'm using something like this:

while compare versions; do

    current version=

    if [[ actual version != current version ]]; then

        currentver=

        previous version=`echo $ current version | awk -F. -v OFS=. \
              'NF==1{print ++$NF};
               NF>1{if(length($NF+1)>length($NF))$(NF-1)++;
               $NF=sprintf("%0*d", length($NF), ($NF-1)%(10^length($NF)));
               print}'`

        Go back to $ previous version

        do something

What I get is:

Go back to 1.1.4

Go back to 1.1.3

Go back to 1.1.2

Go back to 1.1.1

Go back to 1.1.0

Go back to 1.1.-1

Go back to 1.1.-2

I want the version number to go to 1.0.9.

How can I change the awk command not to go below 0?

Body:
Your question isn't clear so if this isn't what you want:

$ cat tst.awk
function decrement(old,        n,parts) {
    n = split(old,parts,/\./)
    if ( parts[n] == 0 ) {
        parts[n--] = 9
    }
    parts[n]--
    return (parts[1] "." parts[2] "." parts[3])
}
BEGIN {
    val = "1.1.4"
    while ( val != "1.0.9" ) {
        print val
        val = decrement(val)
    }
    print val
}

$ awk -f tst.awk
1.1.4
1.1.3
1.1.2
1.1.1
1.1.0
1.0.9

then edit your question to clarify what you're trying to do and provide testable sample input/output.


问:
What does {0} mean when found in a key-value pair in C# config file?
I have run into the use of {0} in the App.config of a project I'm working on and I can't find anything on how it works. The only other question on it I found is the this question which explains how composite formatting works but nothing about its use in the .config file</p>

```<code><?xml version="1.0" encoding="utf-8"?>
  <configuration>
    <appSettings>
      <add key="UriUpdateProfile" value="{0}/profiles/{1}" />
      ...
    </appSettings>
  </configuration>
</code>```

答: It doesn't mean anything in the config file. In the code, this literal string "{0}/profiles/{1}" will be acquired from the configuration. This string will then be used in a composite formatting function such as String.Format or Console.WriteLine. In the code, where those functions are called, you'll find the arguments that fill in the "{0}" and "{1}" placeholders.

Body:
I have run into the use of {0} in the App.config of a project I'm working on and I can't find anything on how it works. The only other question on it I found is the this question which explains how composite formatting works but nothing about its use in the .config file

<?xml version="1.0" encoding="utf-8"?>
  <configuration>
    <appSettings>
      <add key="UriUpdateProfile" value="{0}/profiles/{1}" />
      ...
    </appSettings>
  </configuration>


问:
Segmentation fault core dumped 2d array
I'm trying to compile a c code under linux using gcc-4.9 (tried also 5.4) while so, I faced a segmentation fault error.

```<code>Program received signal SIGSEGV, Segmentation fault.
0x080492e6 in dot (p1=0x8d9e6c0 <permy>, p2=0x3d77ca7c) at autrq.h:135
135     j = p2[i];
</code>```

this is the part of code where the problem exists:

```<code>#define N 239
#define K 120

void dot(int p1[N], int p2[N]) {
    int p3[N], i, j; //printf("\n debut dot ");

    for (i = 0; i < N; i++){
        p3[i] = p1[i];
    }

    for (i = 0; i < N; i++) {
        j = p2[i];
        if(j>=N){
           printf("Too large\n");
        }
        else{

           p1[i]=p3[j];
        }
    } //printf("\n fin dot ");
}

void GenAut(int permy[N]) {
    int i, j, c, f;
    //printf("\n debut GenAUT ");
    int inf[K], mo[N], mi[N];

    for (i = 0; i < N; i++){
        permy[i] = i;
    }

    j = GenIdex(1, 100);

    for (c = 0; c < j; c++) {
        f = GenIdex(0, pos);
        //printf("\n pos: %d et f %d ",pos,f);
        dot(permy, automorf[f]);
    }
}
</code>```

automorf is an array n x n long (int automorf[n][n])

Can you please help correcting the problem?

答:
Try this and see output

we have not p3[3]; and trying to access make error or undefined behavior.

```<code>#include <stdio.h>
#define N 3

void dot(int p1[N], int p2[N]) {
    int p3[N], i, j; //printf("\n debut dot ");

    for (i = 0; i < N; i++){
        p3[i] = p1[i];
    }

   for (i = 0; i < N; i++) {
        printf("i:%d p3[i]%d\n", i,p3[i]) ;
   }

    printf("\n") ;

    for (i = 0; i < N; i++) {

        j = p2[i];

        printf("i:%d j:%d p3[%d]:%d\n", i, j, j, p3[j]) ;

        p1[i]=p3[j];

    }

    //printf("\n fin dot ");
}

int
main(){

    int x[N]={10,20,30};
    int y[N]={1,2,3};

    dot(x, y);

    printf("\n");
    return 0;
}
</code>```

Title: Segmentation fault core dumped 2d array

Body:
I'm trying to compile a c code under linux using gcc-4.9 (tried also 5.4) while so, I faced a segmentation fault error.

Program received signal SIGSEGV, Segmentation fault.
0x080492e6 in dot (p1=0x8d9e6c0 <permy>, p2=0x3d77ca7c) at autrq.h:135
135     j = p2[i];

this is the part of code where the problem exists:

#define N 239
#define K 120

void dot(int p1[N], int p2[N]) {
    int p3[N], i, j; //printf("\n debut dot ");

    for (i = 0; i < N; i++){
        p3[i] = p1[i];
    }

    for (i = 0; i < N; i++) {
        j = p2[i];
        if(j>=N){
           printf("Too large\n");
        }
        else{

           p1[i]=p3[j];
        }
    } //printf("\n fin dot ");
}

void GenAut(int permy[N]) {
    int i, j, c, f;
    //printf("\n debut GenAUT ");
    int inf[K], mo[N], mi[N];

    for (i = 0; i < N; i++){
        permy[i] = i;
    }

    j = GenIdex(1, 100);

    for (c = 0; c < j; c++) {
        f = GenIdex(0, pos);
        //printf("\n pos: %d et f %d ",pos,f);
        dot(permy, automorf[f]);
    }
}

automorf is an array n x n long (int automorf[n][n])

Can you please help correcting the problem?

Body:
Try this and see output

we have not p3[3]; and trying to access make error or undefined behavior.

#include <stdio.h>
#define N 3

void dot(int p1[N], int p2[N]) {
    int p3[N], i, j; //printf("\n debut dot ");

    for (i = 0; i < N; i++){
        p3[i] = p1[i];
    }

   for (i = 0; i < N; i++) {
        printf("i:%d p3[i]%d\n", i,p3[i]) ;
   }

    printf("\n") ;

    for (i = 0; i < N; i++) {

        j = p2[i];

        printf("i:%d j:%d p3[%d]:%d\n", i, j, j, p3[j]) ;

        p1[i]=p3[j];

    }

    //printf("\n fin dot ");
}

int
main(){

    int x[N]={10,20,30};
    int y[N]={1,2,3};

    dot(x, y);

    printf("\n");
    return 0;
}


问:
Java identifiers difference in errors
When we put # in the identifier name then it says illegal character but when we put other symbol such as !,@etc it says- '}' expected in java.Why is it so?</p>

答:
The Parser can only give sensible error messages on what is there and stops as soon as possible.

It is sure that # is not allowed, so if it sees # it can just say: "stop it, this cant be correct" aka "illegal character".

Other characters might be correct, depending on whats coming after. When it says "} expected" then this could be a way to complete your sourcecode in a way that at least the parser is fine with it.

Title: Java identifiers difference in errors


问:
Cutting and fading ts segment with ffmpeg?
I'm trying to cut a ts segment and apply a fade from white at the initial point of the cut segment. This is used in a situation where I need to "crop" some material from the beginning of a video and apply a fade for a smoother entry. In my test, I am cutting an 8 second segment at the 5.5s mark to yield a 2.5 second segment that will fade from white over the first second.

The cut command by itself works fine:

```<code>ffmpeg  -i test.ts  -ss 5.5 -c:v libx264 -profile:v baseline -c:a aac -map 0 -mpegts_copyts 1  -preset ultrafast -f ssegment -initial_offset 5.5 -segment_format mpegts   ~/Desktop/cut%d.ts
</code>```

I've successfully used this fade filter syntax before:

```<code>-filter:v fade=t=in:st=0:d=1:color=0xffffff
</code>```

But I can't seem to make the whole thing work:

```<code>ffmpeg  -i test.ts  -filter:v fade=t=in:st=5.5:d=1:color=0xffffff  -ss 5.5 -c:v libx264 -profile:v baseline -c:a aac -map 0 -mpegts_copyts 1  -preset ultrafast -f ssegment -initial_offset 5.5 -segment_format mpegts   ~/Desktop/cut%d.ts
</code>```

I'm getting the following error:

x264 [error]: baseline profile doesn't support 4:4:4

[libx264 @ 0x7fd9db002400] Error setting profile baseline.

[libx264 @ 0x7fd9db002400] Possible profiles: baseline main high high10
high422 high444

Error initializing output stream 0:1 -- Error while opening encoder for output stream #0:1 - maybe incorrect parameters such as bit_rate, rate, width or height

[aac @ 0x7fd9db001200] Qavg: nan

Conversion failed!

My knowledge of ffmpeg just isn't deep enough to figure out why this is happening. Any thoughts?

Thanks,
Matt

答:
Getting rid of -profile:v baseline will 'solve' it but the resulting video won't be playable in many players since ffmpeg will have autoselected profile high444 for you.

Instead, use

```<code>ffmpeg -i test.ts
-vf fade=t=in:st=5.5:d=1:color=0xffffff,format=yuv420p
-ss 5.5 -c:v libx264 -profile:v baseline -c:a aac -map 0 -preset ultrafast
-mpegts_copyts 1 -f ssegment -initial_offset 5.5 -segment_format mpegts ~/Desktop/cut%d.ts
</code>```

Baseline profile only supports YUV 4:2:0 planar pixel format.

Body:
I'm trying to cut a ts segment and apply a fade from white at the initial point of the cut segment. This is used in a situation where I need to "crop" some material from the beginning of a video and apply a fade for a smoother entry. In my test, I am cutting an 8 second segment at the 5.5s mark to yield a 2.5 second segment that will fade from white over the first second.

The cut command by itself works fine:

ffmpeg  -i test.ts  -ss 5.5 -c:v libx264 -profile:v baseline -c:a aac -map 0 -mpegts_copyts 1  -preset ultrafast -f ssegment -initial_offset 5.5 -segment_format mpegts   ~/Desktop/cut%d.ts

I've successfully used this fade filter syntax before:

-filter:v fade=t=in:st=0:d=1:color=0xffffff

But I can't seem to make the whole thing work:

ffmpeg  -i test.ts  -filter:v fade=t=in:st=5.5:d=1:color=0xffffff  -ss 5.5 -c:v libx264 -profile:v baseline -c:a aac -map 0 -mpegts_copyts 1  -preset ultrafast -f ssegment -initial_offset 5.5 -segment_format mpegts   ~/Desktop/cut%d.ts

I'm getting the following error:

x264 [error]: baseline profile doesn't support 4:4:4

[libx264 @ 0x7fd9db002400] Error setting profile baseline.

[libx264 @ 0x7fd9db002400] Possible profiles: baseline main high high10
high422 high444

Error initializing output stream 0:1 -- Error while opening encoder for output stream #0:1 - maybe incorrect parameters such as bit_rate, rate, width or height

[aac @ 0x7fd9db001200] Qavg: nan

Conversion failed!

My knowledge of ffmpeg just isn't deep enough to figure out why this is happening. Any thoughts?

Thanks,
Matt

Body:
Getting rid of -profile:v baseline will 'solve' it but the resulting video won't be playable in many players since ffmpeg will have autoselected profile high444 for you.

Instead, use

ffmpeg -i test.ts
-vf fade=t=in:st=5.5:d=1:color=0xffffff,format=yuv420p
-ss 5.5 -c:v libx264 -profile:v baseline -c:a aac -map 0 -preset ultrafast
-mpegts_copyts 1 -f ssegment -initial_offset 5.5 -segment_format mpegts ~/Desktop/cut%d.ts

Baseline profile only supports YUV 4:2:0 planar pixel format.


答:
Create a composite unique key around the parent and child columns.  Then issue a query like this instead:

```<code>insert ignore into adjacencies( parent, child, pathLen )
select a, b, c from something where condition ;
</code>```

The IGNORE clause will turn duplicate key errors into warnings.

Title: mysql automatically prevent redundant inserts

Body:
Create a composite unique key around the parent and child columns.  Then issue a query like this instead:

insert ignore into adjacencies( parent, child, pathLen )
select a, b, c from something where condition ;

The IGNORE clause will turn duplicate key errors into warnings.


问:
How to run two python application in docker
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

```<code>exec python __server_code.py &
exec python server_time_test.py &
</code>```

in dockerfile, I am trying to run these two python application

```<code>RUN ["chmod", "+x", "./serverRun.sh"]
</code>```

It did not work. Any idea?

答:
You must have one process in foreground. So remove the last &. And don't use exec

```<code>cd /rfk-thrift/nlp_search
python __server_code.py &
python server_time_test.py
</code>```

And this in Dockerfile:

```<code>RUN chmod +x ./serverRun.sh
CMD ./serverRun.sh
</code>```

Body:
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

exec python __server_code.py &
exec python server_time_test.py &

in dockerfile, I am trying to run these two python application

RUN ["chmod", "+x", "./serverRun.sh"]

It did not work. Any idea?

Body:
You must have one process in foreground. So remove the last &. And don't use exec

cd /rfk-thrift/nlp_search
python __server_code.py &
python server_time_test.py

And this in Dockerfile:

RUN chmod +x ./serverRun.sh
CMD ./serverRun.sh


问:
Excel VBA error - Workbook does not respond when code runs with other macro-enabled workbooks open

Background

I have a dilemma. There is a workbook I have been working on for about a month. I have many named ranges, three queries, and several tables. One of the tables, (TABLE_Syteline_JobBills) is constructed from another table which is a query from a database. I refresh this other table (TABLE_Syteline_SingleLevel), 3 times, each time appending the data to the JobBills table.

The Problem

The code only works if no other Macro-Enabled Workbooks are open. If a Macro-Enabled Workbook is open, I get the error

Runtime Error - Automation Error - The object invoked has disconnected from its clients.

It occurs on the line:

```<code>.ListRows.Add(AlwaysInsert = True).Range = Row.Value
</code>```

The code works without any error until a macro-enabled workbook is opened. A regular workbook does not cause the code to error. There will be no error when this is the only macro-enabled workbook open. Depending on which macro-enabled workbook you have open, the error might not happen until the third time through the nested for loop.

The Code

Here it is...the sub that causes the issue

```<code>'Option Explicit

Sub UpdatingTableJobBills()
'--------------------------------------------------------------------------------
'Programmer's Notes
'--------------------------------------------------------------------------------
'Copies three sets of data one at a time to one big table refreshing each time
'--------------------------------------
'Variable Declarations
'--------------------------------------
Dim JobNumber As String 'Variable Job Number
Dim RowCount As Integer 'Number of rows in table
Dim BOMSuffixes As Variant
Dim BOMSuffix As Variant
Dim Row As Range 'Used to loop through the different rows in the SingleLevel table we are going to insert into the JobBill table

'--------------------------------------
'Variable Definitions
'--------------------------------------
BOMSuffixes = Array("-conv", "-devices", "-electrical")
JobNumber = ThisWorkbook.Worksheets("Cost Analysis").Range("JobNumber").Value 'job number - read from named cell

'--------------------------------------
'Delete any old data
'--------------------------------------
WipeOutBillData '---this function simply deletes 3 table databodyranges if they aren't empty already

'--------------------------------------
'Loop through each query and copy the query results to the JobBills table
'--------------------------------------
For Each BOMSuffix In BOMSuffixes
    ThisWorkbook.Worksheets("BOM Query").Range("PartNumber").Value = JobNumber & BOMSuffix 'Changes part number to prepare for refresh
    ThisWorkbook.Connections("Syteline_Query_BOM").Refresh 'Refreshes specific connection to syteline
    With ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills")
        If WorksheetFunction.CountA(ThisWorkbook.Worksheets("BOM Query").Range("TABLE_Syteline_SingleLevel")) <> 0 Then
            For Each Row In ThisWorkbook.Worksheets("BOM Query").ListObjects("TABLE_Syteline_SingleLevel").DataBodyRange.Rows
                .ListRows.Add(AlwaysInsert:=True).Range = Row.Value  '******** The row behind the trouble *********
            Next Row
        End If
    End With
Next BOMSuffix

Set Row = Nothing

With ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills")
    If IsEmpty(ThisWorkbook.Worksheets("Job Data").Range("TABLE_Syteline_JobBills[Child]")) Then
        Call MsgBox("No data has been returned for job number: " & JobNumber, vbSystemModal, "No Data Returned")
        Exit Sub
    End If
    .DataBodyRange.Cells(2, .ListColumns("Extended Cost").index).Value = "=[Qty]*[Cost]" 'Redefines the value of column "Extended Cost"
End With

'--------------------------------------
'Sorts the table JobBills by descending Ext Cost
'--------------------------------------
ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills"). _
    Sort.SortFields.Clear
ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills"). _
    Sort.SortFields.Add Key:=Range( _
"TABLE_Syteline_JobBills[[#All],[Extended Cost]]"), SortOn:=xlSortOnValues, _
    Order:=xlDescending, DataOption:=xlSortNormal
With ThisWorkbook.Worksheets("Job Data").ListObjects( _
    "TABLE_Syteline_JobBills").Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

'--------------------------------------
'Deletes rows with an Extended Cost of Zero
'--------------------------------------

Dim Description As String
Dim RowMover As Integer
Dim ExtRowCounter As Integer

ExtRowCounter = 2

Do While Not IsEmpty(ThisWorkbook.Worksheets("Job Data").Cells(ExtRowCounter, ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills").ListColumns("Extended Cost").index))
    If ThisWorkbook.Worksheets("Job Data").Cells(ExtRowCounter, ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills").ListColumns("Extended Cost").index).Value = 0 Then
        ThisWorkbook.Worksheets("Job Data").Cells(ExtRowCounter, ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills").ListColumns("Extended Cost").index).EntireRow.Delete
        ExtRowCounter = ExtRowCounter - 1
    End If
    ExtRowCounter = ExtRowCounter + 1
Loop
End Sub
</code>```

If anyone can offer any possible explanation or solution to this error I am getting, it would be greatly appreciated. I just can't understand why the code wouldn't work with another macro-enabled workbook open. I made sure that I was specifically referencing "thisworkbook...". Perhaps there is a setting which I have selected within excel that causes the macro-enabled workbooks to work against each other.

Anyway - Thank you in advance for any advice!

答:
This part seems fishy to me:

```<code>With ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills")
        If WorksheetFunction.CountA(ThisWorkbook.Worksheets("BOM Query").Range("TABLE_Syteline_SingleLevel")) <> 0 Then
            For Each Row In ThisWorkbook.Worksheets("BOM Query").ListObjects("TABLE_Syteline_SingleLevel").DataBodyRange.Rows
                .ListRows.Add(AlwaysInsert:=True).Range = Row.Value  '******** The row behind the trouble *********
            Next Row
        End If
    End With
</code>```

Reduntant With block, try to use explicit object address? Same line, you access a Range object and assign a Range.Value to it.

Try:

```<code> ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills") _
.ListRows.Add(AlwaysInsert:=True).Range.Value = Row.Value
</code>```

Another idea is to try using Workbooks("wbName") instead of ThisWorkbook to make sure the correct Workbook is processed.

Update:
Try commenting out Set Row = Nothing

Body:
Background

I have a dilemma. There is a workbook I have been working on for about a month. I have many named ranges, three queries, and several tables. One of the tables, (TABLE_Syteline_JobBills) is constructed from another table which is a query from a database. I refresh this other table (TABLE_Syteline_SingleLevel), 3 times, each time appending the data to the JobBills table.

The Problem

The code only works if no other Macro-Enabled Workbooks are open. If a Macro-Enabled Workbook is open, I get the error

Runtime Error - Automation Error - The object invoked has disconnected from its clients.

It occurs on the line:

.ListRows.Add(AlwaysInsert = True).Range = Row.Value

The code works without any error until a macro-enabled workbook is opened. A regular workbook does not cause the code to error. There will be no error when this is the only macro-enabled workbook open. Depending on which macro-enabled workbook you have open, the error might not happen until the third time through the nested for loop.

The Code

Here it is...the sub that causes the issue

'Option Explicit

Sub UpdatingTableJobBills()
'--------------------------------------------------------------------------------
'Programmer's Notes
'--------------------------------------------------------------------------------
'Copies three sets of data one at a time to one big table refreshing each time
'--------------------------------------
'Variable Declarations
'--------------------------------------
Dim JobNumber As String 'Variable Job Number
Dim RowCount As Integer 'Number of rows in table
Dim BOMSuffixes As Variant
Dim BOMSuffix As Variant
Dim Row As Range 'Used to loop through the different rows in the SingleLevel table we are going to insert into the JobBill table

'--------------------------------------
'Variable Definitions
'--------------------------------------
BOMSuffixes = Array("-conv", "-devices", "-electrical")
JobNumber = ThisWorkbook.Worksheets("Cost Analysis").Range("JobNumber").Value 'job number - read from named cell

'--------------------------------------
'Delete any old data
'--------------------------------------
WipeOutBillData '---this function simply deletes 3 table databodyranges if they aren't empty already

'--------------------------------------
'Loop through each query and copy the query results to the JobBills table
'--------------------------------------
For Each BOMSuffix In BOMSuffixes
    ThisWorkbook.Worksheets("BOM Query").Range("PartNumber").Value = JobNumber & BOMSuffix 'Changes part number to prepare for refresh
    ThisWorkbook.Connections("Syteline_Query_BOM").Refresh 'Refreshes specific connection to syteline
    With ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills")
        If WorksheetFunction.CountA(ThisWorkbook.Worksheets("BOM Query").Range("TABLE_Syteline_SingleLevel")) <> 0 Then
            For Each Row In ThisWorkbook.Worksheets("BOM Query").ListObjects("TABLE_Syteline_SingleLevel").DataBodyRange.Rows
                .ListRows.Add(AlwaysInsert:=True).Range = Row.Value  '******** The row behind the trouble *********
            Next Row
        End If
    End With
Next BOMSuffix

Set Row = Nothing

With ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills")
    If IsEmpty(ThisWorkbook.Worksheets("Job Data").Range("TABLE_Syteline_JobBills[Child]")) Then
        Call MsgBox("No data has been returned for job number: " & JobNumber, vbSystemModal, "No Data Returned")
        Exit Sub
    End If
    .DataBodyRange.Cells(2, .ListColumns("Extended Cost").index).Value = "=[Qty]*[Cost]" 'Redefines the value of column "Extended Cost"
End With

'--------------------------------------
'Sorts the table JobBills by descending Ext Cost
'--------------------------------------
ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills"). _
    Sort.SortFields.Clear
ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills"). _
    Sort.SortFields.Add Key:=Range( _
"TABLE_Syteline_JobBills[[#All],[Extended Cost]]"), SortOn:=xlSortOnValues, _
    Order:=xlDescending, DataOption:=xlSortNormal
With ThisWorkbook.Worksheets("Job Data").ListObjects( _
    "TABLE_Syteline_JobBills").Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

'--------------------------------------
'Deletes rows with an Extended Cost of Zero
'--------------------------------------

Dim Description As String
Dim RowMover As Integer
Dim ExtRowCounter As Integer

ExtRowCounter = 2

Do While Not IsEmpty(ThisWorkbook.Worksheets("Job Data").Cells(ExtRowCounter, ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills").ListColumns("Extended Cost").index))
    If ThisWorkbook.Worksheets("Job Data").Cells(ExtRowCounter, ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills").ListColumns("Extended Cost").index).Value = 0 Then
        ThisWorkbook.Worksheets("Job Data").Cells(ExtRowCounter, ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills").ListColumns("Extended Cost").index).EntireRow.Delete
        ExtRowCounter = ExtRowCounter - 1
    End If
    ExtRowCounter = ExtRowCounter + 1
Loop
End Sub

If anyone can offer any possible explanation or solution to this error I am getting, it would be greatly appreciated. I just can't understand why the code wouldn't work with another macro-enabled workbook open. I made sure that I was specifically referencing "thisworkbook...". Perhaps there is a setting which I have selected within excel that causes the macro-enabled workbooks to work against each other.

Anyway - Thank you in advance for any advice!

Body:
This part seems fishy to me:

With ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills")
        If WorksheetFunction.CountA(ThisWorkbook.Worksheets("BOM Query").Range("TABLE_Syteline_SingleLevel")) <> 0 Then
            For Each Row In ThisWorkbook.Worksheets("BOM Query").ListObjects("TABLE_Syteline_SingleLevel").DataBodyRange.Rows
                .ListRows.Add(AlwaysInsert:=True).Range = Row.Value  '******** The row behind the trouble *********
            Next Row
        End If
    End With

Reduntant With block, try to use explicit object address? Same line, you access a Range object and assign a Range.Value to it.

Try:

 ThisWorkbook.Worksheets("Job Data").ListObjects("TABLE_Syteline_JobBills") _
.ListRows.Add(AlwaysInsert:=True).Range.Value = Row.Value

Another idea is to try using Workbooks("wbName") instead of ThisWorkbook to make sure the correct Workbook is processed.

Update:
Try commenting out Set Row = Nothing


问:
Trying to understand power function, C Programming Language, 2e, 27
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

```<code>int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}
</code>```

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

答: The variable p is never incremented. It is multiplied by a factor of base each time the loop runs.  The return value contains the desired power.

Body:
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?


问:
Using sed to extract element content of an XML file
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<Header>
<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>
</Header>
<Body>
</Body>
</Envelope>
</code>```

so i want to get

```<code><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</code>```

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

```<code>sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt
</code>```

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

答:
Via sed, you can try the following :

```<code>sed -n '/<Transport_key>/,/<\/Transport_key>/p' test1.xml | sed -e '/Transport_key/d'
</code>```

The first command takes everything between the Transport_key tags. Since this also prints the Transport_key tags, the second command deletes the lines containing the Transport_key tags.

Body:
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

<?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>

</Envelope>

so i want to get

<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

Body:
Via sed, you can try the following :

sed -n '/<Transport_key>/,/<\/Transport_key>/p' test1.xml | sed -e '/Transport_key/d'

The first command takes everything between the Transport_key tags. Since this also prints the Transport_key tags, the second command deletes the lines containing the Transport_key tags.