答:
Here you go with the solution https://jsfiddle.net/mcvsbsdy/2/

$(document).ready(function(){

  $('.trailerdiv').each(function() {
   $($(this).children()[2]).nextAll().addClass('hide');
   $($(this).children()[2]).after('....Show More');
  })
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $(this).nextAll().removeClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide
{
  display:none;
}</code>```

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

```

Title: "Show More" Link for buttons inside div (multiple show more buttons)

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

$(document).ready(function(){

  $('.trailerdiv').each(function() {
   $($(this).children()[2]).nextAll().addClass('hide');
   $($(this).children()[2]).after('<a href="" id="particular">....Show More</a>');
  })
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $(this).nextAll().removeClass('hide');
});

.hide
{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>div1</p>
<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

<p>div2</p>

<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

<p>div3</p>

<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>


来源: stackexchange

问:
"Show More" Link for buttons inside div (multiple show more buttons)
Here is the fiddle And this is my code here:

$(document).ready(function(){
  $( "button.playtrailer" ).eq(2).after('....Show More');//add a unique id to link
  $( "button.playtrailer:gt(2)" ).addClass('hide');
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $('button.playtrailer').removeClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide
{
  display:none;
}</code>```

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

```

What I want?

In this code, There is only 1 Show More Link for all buttons inside a div.

I want different show more buttons for each div, something like this:

div1

Trailer 1   Trailer 2   Trailer HD...Show more

div2

Trailer 1   Trailer 2   Trailer HD...Show more

div3

Trailer 1   Trailer 2   Trailer HD...Show more

I want to do this without changing the class (both in div and button). What changes should, I make in my Jquery code?

答:
Isolate instances inside the parent trailerdiv. Use the parent as the start point and use find() or children() to look only inside that parent instance.

Also need to change the #particular to a class since ID's must be unique

```<code>$(document).ready(function() {
  $('.trailerdiv').each(function() {
    // "this" is the instance of "trailerdiv"
    var $btns = $(this).find("button.playtrailer");
    $btns.eq(2).after('<a href="" class="show-more">....Show More</a>'); //add a unique id to link
    $btns.filter(':gt(2)').addClass('hide');
  });
});

$(document).on('click', 'a.show-more', function(e) {
  e.preventDefault();
  // only remove hide class from this button instance's siblings
  $(this).addClass('hide').siblings().removeClass('hide');

});
</code>```

DEMO

ContentLicense: CC BY-SA 3.0

Body:
Here is the fiddle And this is my code here:

$(document).ready(function(){
  $( "button.playtrailer" ).eq(2).after('....Show More');//add a unique id to link
  $( "button.playtrailer:gt(2)" ).addClass('hide');
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $('button.playtrailer').removeClass('hide');
});

.hide
{
  display:none;
}

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

What I want?

In this code, There is only 1 Show More Link for all buttons inside a div.

I want different show more buttons for each div, something like this:

div1

Trailer 1   Trailer 2   Trailer HD...Show more

div2

Trailer 1   Trailer 2   Trailer HD...Show more

div3

Trailer 1   Trailer 2   Trailer HD...Show more

I want to do this without changing the class (both in div and button). What changes should, I make in my Jquery code?

Body:
Isolate instances inside the parent trailerdiv. Use the parent as the start point and use find() or children() to look only inside that parent instance.

Also need to change the #particular to a class since ID's must be unique

$(document).ready(function() {
  $('.trailerdiv').each(function() {
    // "this" is the instance of "trailerdiv"
    var $btns = $(this).find("button.playtrailer");
    $btns.eq(2).after('<a href="" class="show-more">....Show More</a>'); //add a unique id to link
    $btns.filter(':gt(2)').addClass('hide');
  });
});

$(document).on('click', 'a.show-more', function(e) {
  e.preventDefault();
  // only remove hide class from this button instance's siblings
  $(this).addClass('hide').siblings().removeClass('hide');

});

DEMO


问:
Layout missed up on 3.5" Screen iPhone 4
I have developed my App on XCODE 8  which by default removes iPhone 4 emulator and I didn't notice that until I finished my app, and I used Auto layout to make the UI fits all iPhone screens and that what happened (the layout was good on iPhone 7,6,5) the problem is when I additionally installed iPhone 4 emulator I found that the layout is totally missed up and unreadable/usable.

So what options do I have to solve this and make it fit the iPhone 4 screen too with Auto-Layout with missing up the other sizes ?

Here is screen shot of my Login screen on iPhone 6 (4.7") vs iPhone 4 (3.5")

答: You must always give constraints with respect to other alternative buttons or a view, it should not be hard coded. Try making views programatically, it will be more easy and helpful to you.</p>


问:
Paypal and asp.net on IIS with TLS1.2
I am trying to deploy PayPal application to IIS.

I cannot connect to PayPal due to issue with TLS1.2

I did all changes to the registry and using .Net 4.6.1

If I use this code on console application

```<code>        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        using (var response = WebRequest.Create("https://tlstest.paypal.com/").GetResponse())
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            Console.WriteLine(streamReader.ReadToEnd());
        }
</code>```

it works.

Same code put in asp.net application and deployed to IIS on the same server does not work.

Any ideas why console application is working and asp.net application deployed on IIS is not?

Error:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 104.75.235.58:443
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 104.75.235.58:443

Source Error:

Line 16:             System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12  | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Line 17:
Line 18:             using (var response = WebRequest.Create("https://tlstest.paypal.com/").GetResponse())
Line 19:             using (var streamReader = new StreamReader(response.GetResponseStream()))
Line 20:             {

Source File:  C:\WebApplication2\WebApplication2\WebForm1.aspx.cs    Line:  18

Stack Trace:

[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 104.75.235.58:443]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +185
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +506

[WebException: Unable to connect to the remote server]
   System.Net.HttpWebRequest.GetResponse() +1390
   WebApplication2.WebForm1.Page_Load(Object sender, EventArgs e) in C:\Temp\Razno\PPtest\WebApplication2\WebApplication2\WebForm1.aspx.cs:18
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678

答:
You are getting a socket error and not a ssl issue.

A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond

Your application is not able to connect to the said address https://tlstest.paypal.com/. This may be due to proxy setting where your console application will be working under your credential and going on the default proxy setup but IIS(w3wp.exe ) is not able to. Please try and add the proxy settings. Refer this as well

Also this SO post discuss the same

Title: Paypal and asp.net on IIS with TLS1.2

Body:
I am trying to deploy PayPal application to IIS.

I cannot connect to PayPal due to issue with TLS1.2

I did all changes to the registry and using .Net 4.6.1

If I use this code on console application

        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        using (var response = WebRequest.Create("https://tlstest.paypal.com/").GetResponse())
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            Console.WriteLine(streamReader.ReadToEnd());
        }

it works.

Same code put in asp.net application and deployed to IIS on the same server does not work.

Any ideas why console application is working and asp.net application deployed on IIS is not?

Error:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 104.75.235.58:443
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 104.75.235.58:443

Source Error:

Line 16:             System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12  | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Line 17:
Line 18:             using (var response = WebRequest.Create("https://tlstest.paypal.com/").GetResponse())
Line 19:             using (var streamReader = new StreamReader(response.GetResponseStream()))
Line 20:             {

Source File:  C:\WebApplication2\WebApplication2\WebForm1.aspx.cs    Line:  18

Stack Trace:

[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 104.75.235.58:443]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +185
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +506

[WebException: Unable to connect to the remote server]
   System.Net.HttpWebRequest.GetResponse() +1390
   WebApplication2.WebForm1.Page_Load(Object sender, EventArgs e) in C:\Temp\Razno\PPtest\WebApplication2\WebApplication2\WebForm1.aspx.cs:18
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678


问:
Chain vim yank and paste?
Is it possible to chain yank move and paste? Something like :10,20y | 30 | p? Goal is to yank line 10 to 20 and paste at line 30 and the cursor is at line 25 (preferably without the move part to avoid moving the cursor)?

答:
This could be done with ex commands, specifically the normal command, like so:

```<code>:10,20yank | normal! 30G | normal! p
</code>```

30G means move to line 30, and pasting can be done with normal! again. I use normal with a ! here so that any bindings you may be using make no impact.

You could also use a register to avoid clobbering the default register,

```<code>:10,20yank a | normal! 30G | normal! "ap
</code>```

This should work in both neovim and normal vim.

Title: Chain vim yank and paste?

Body:
This could be done with ex commands, specifically the normal command, like so:

:10,20yank | normal! 30G | normal! p

30G means move to line 30, and pasting can be done with normal! again. I use normal with a ! here so that any bindings you may be using make no impact.

You could also use a register to avoid clobbering the default register,

:10,20yank a | normal! 30G | normal! "ap

This should work in both neovim and normal vim.


问:
How to merge PNGS with alpha channels into one larger image?
I am trying to layer these:

into this:

But what I keep getting is this:

This is the relevant code, Im not sure what Im missing:

```<code>    $sig_background = imagecreatefrompng("sanctum-signature.png");
imagealphablending($sig_background, false);
imagesavealpha($sig_background, true);
$sig_gamertile = imagecreatefrompng($gamertile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
$sig_gametile = imagecreatefrompng($gametile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
imagecopymerge($sig_background, $sig_gamertile, 175, 2, 0, 0, 64, 64, 100);
imagecopymerge($sig_background, $sig_gametile, 342, 20, 0, 0, 64, 64, 100);
</code>```

If any more information is missing, please let me know and Ill try to fill in the blanks. Thank you for your time.

edit - here are links to the files (hosted on photobucket)
gamertile
gametile

答:
The line:

```<code>imagealphablending($im, false);
</code>```

disables alpha blending. Use true instead of false.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to layer these:

into this:

But what I keep getting is this:

This is the relevant code, Im not sure what Im missing:

    $sig_background = imagecreatefrompng("sanctum-signature.png");
imagealphablending($sig_background, false);
imagesavealpha($sig_background, true);
$sig_gamertile = imagecreatefrompng($gamertile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
$sig_gametile = imagecreatefrompng($gametile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
imagecopymerge($sig_background, $sig_gamertile, 175, 2, 0, 0, 64, 64, 100);
imagecopymerge($sig_background, $sig_gametile, 342, 20, 0, 0, 64, 64, 100);

If any more information is missing, please let me know and Ill try to fill in the blanks. Thank you for your time.

edit - here are links to the files (hosted on photobucket)
gamertile
gametile

Body:
The line:

imagealphablending($im, false);

disables alpha blending. Use true instead of false.


问:
PLS regression coefficients in MATLAB and C# (Accord.NET)
I'm trying to perform a partial least square regression analysis in C#. The pls technique performed in MATLAB uses SIMPLS algorithm which provides the beta (matrix of regression coefficients).

I do not understand why the matrices are different in both cases, is there some mistake in the way I pass input to the C# version?

Also, the inputs are same for both and are in reference to the paper that is included here.

Minimal working example:

MATLAB: following the small example by Hervé Abdi (Hervé Abdi, Partial Least Square Regression). References: PDF

```<code>clear all;
clc;
inputs = [7, 7, 13, 7; 4, 3, 14, 7; 10, 5, 12, 5; 16, 7, 11, 3; 13, 3, 10, 3];
outputs = [14, 7, 8; 10, 7, 6; 8, 5, 5; 2, 4,7; 6, 2, 4];
[XL,yl,XS,YS,beta,PCTVAR] = plsregress(inputs,outputs, 1);
disp 'beta'
beta
disp 'beta size'
size(beta)
yfit = [ones(size(inputs,1),1) inputs]*beta;
residuals = outputs - yfit;

% stem(residuals)
% xlabel('Observation');
% ylabel('Residual');

beta =

   1.0484e+01   6.1899e+00   6.2841e+00
  -6.3488e-01  -3.0405e-01  -7.2608e-02
   2.1949e-02   1.0512e-02   2.5102e-03
   1.9226e-01   9.2078e-02   2.1988e-02
   2.8948e-01   1.3864e-01   3.3107e-02
</code>```

Accord.NET:

```<code>double[][] inputs = new double[][]
    {
        //      Wine | Price | Sugar | Alcohol | Acidity
        new double[] {   7,     7,      13,        7 },
        new double[] {   4,     3,      14,        7 },
        new double[] {  10,     5,      12,        5 },
        new double[] {  16,     7,      11,        3 },
        new double[] {  13,     3,      10,        3 },
    };

double[][] outputs = new double[][]
    {
        //             Wine | Hedonic | Goes with meat | Goes with dessert
        new double[] {           14,          7,                 8 },
        new double[] {           10,          7,                 6 },
        new double[] {            8,          5,                 5 },
        new double[] {            2,          4,                 7 },
        new double[] {            6,          2,                 4 },
    };

var pls = new PartialLeastSquaresAnalysis()
        {
            Method = AnalysisMethod.Center,
            Algorithm = PartialLeastSquaresAlgorithm.NIPALS
        };

var regression = pls.Learn(inputs, outputs);

double[][] coeffs = regression.Weights;
>>
-1.69811320754717 -0.0566037735849056   0.0707547169811322
1.27358490566038   0.29245283018868     0.571933962264151
-4                 1                    0.5
1.17924528301887   0.122641509433962    0.159198113207547
</code>```

答:
I think there are at least three discrepancies between the way the MATLAB and Accord.NET versions of PLS are being called.

As you mention, MATLAB is using SIMPLS. However, Accord.NET is being told to use NIPALS.

The MATLAB version is being called as plsregress(inputs, outputs, 1), meaning the regression is being computed considering only 1 latent component in PLS, but you Accord.NET has not been instructed to do the same.

Accord.NET returns a MultivariateLinearRegression object that contains both a matrix of weights as well as a vector of intercepts, whereas and MATLAB returns the intercepts as the first column of the weights matrix.

Once all these are taken in consideration, it is possible to generate exact the same results as the MATLAB version:

```<code>double[][] inputs = new double[][]
{
    //      Wine | Price | Sugar | Alcohol | Acidity
    new double[] {   7,     7,      13,        7 },
    new double[] {   4,     3,      14,        7 },
    new double[] {  10,     5,      12,        5 },
    new double[] {  16,     7,      11,        3 },
    new double[] {  13,     3,      10,        3 },
};

double[][] outputs = new double[][]
{
    //             Wine | Hedonic | Goes with meat | Goes with dessert
    new double[] {           14,          7,                 8 },
    new double[] {           10,          7,                 6 },
    new double[] {            8,          5,                 5 },
    new double[] {            2,          4,                 7 },
    new double[] {            6,          2,                 4 },
};

// Create the Partial Least Squares Analysis
var pls = new PartialLeastSquaresAnalysis()
{
    Method = AnalysisMethod.Center,
    Algorithm = PartialLeastSquaresAlgorithm.SIMPLS, // First change: use SIMPLS
};

// Learn the analysis
pls.Learn(inputs, outputs);

// Second change: Use just 1 latent factor/component
var regression = pls.CreateRegression(factors: 1);

// Third change: present results as in MATLAB
double[][] w = regression.Weights.Transpose();
double[] b = regression.Intercepts;

// Add the intercepts as the first column of the matrix of
// weights and transpose it as in the way MATLAB presents it
double[][] coeffs = (w.InsertColumn(b, index: 0)).Transpose();

// Show results in MATLAB format
string str = coeffs.ToOctave();
</code>```

With those changes, the coeffs matrix above should become

```<code>[ 10.4844779770616    6.18986077674717    6.28413863347486    ;
  -0.634878923091644 -0.304054829845448  -0.0726082626993539  ;
   0.0219492754418065 0.0105118991463605  0.00251024045589416 ;
   0.192261724966225  0.0920775662006966  0.0219881135215502  ;
   0.289484835410222  0.13863944631343    0.033107085796122   ]
</code>```

Body:
I'm trying to perform a partial least square regression analysis in C#. The pls technique performed in MATLAB uses SIMPLS algorithm which provides the beta (matrix of regression coefficients).

I do not understand why the matrices are different in both cases, is there some mistake in the way I pass input to the C# version?

Also, the inputs are same for both and are in reference to the paper that is included here.

Minimal working example:

MATLAB: following the small example by Hervé Abdi (Hervé Abdi, Partial Least Square Regression). References: PDF

clear all;
clc;
inputs = [7, 7, 13, 7; 4, 3, 14, 7; 10, 5, 12, 5; 16, 7, 11, 3; 13, 3, 10, 3];
outputs = [14, 7, 8; 10, 7, 6; 8, 5, 5; 2, 4,7; 6, 2, 4];
[XL,yl,XS,YS,beta,PCTVAR] = plsregress(inputs,outputs, 1);
disp 'beta'
beta
disp 'beta size'
size(beta)
yfit = [ones(size(inputs,1),1) inputs]*beta;
residuals = outputs - yfit;

% stem(residuals)
% xlabel('Observation');
% ylabel('Residual');

beta =

   1.0484e+01   6.1899e+00   6.2841e+00
  -6.3488e-01  -3.0405e-01  -7.2608e-02
   2.1949e-02   1.0512e-02   2.5102e-03
   1.9226e-01   9.2078e-02   2.1988e-02
   2.8948e-01   1.3864e-01   3.3107e-02

Accord.NET:

double[][] inputs = new double[][]
    {
        //      Wine | Price | Sugar | Alcohol | Acidity
        new double[] {   7,     7,      13,        7 },
        new double[] {   4,     3,      14,        7 },
        new double[] {  10,     5,      12,        5 },
        new double[] {  16,     7,      11,        3 },
        new double[] {  13,     3,      10,        3 },
    };

double[][] outputs = new double[][]
    {
        //             Wine | Hedonic | Goes with meat | Goes with dessert
        new double[] {           14,          7,                 8 },
        new double[] {           10,          7,                 6 },
        new double[] {            8,          5,                 5 },
        new double[] {            2,          4,                 7 },
        new double[] {            6,          2,                 4 },
    };

var pls = new PartialLeastSquaresAnalysis()
        {
            Method = AnalysisMethod.Center,
            Algorithm = PartialLeastSquaresAlgorithm.NIPALS
        };

var regression = pls.Learn(inputs, outputs);

double[][] coeffs = regression.Weights;
>>
-1.69811320754717 -0.0566037735849056   0.0707547169811322
1.27358490566038   0.29245283018868     0.571933962264151
-4                 1                    0.5
1.17924528301887   0.122641509433962    0.159198113207547

Body:
I think there are at least three discrepancies between the way the MATLAB and Accord.NET versions of PLS are being called.

As you mention, MATLAB is using SIMPLS. However, Accord.NET is being told to use NIPALS.

The MATLAB version is being called as plsregress(inputs, outputs, 1), meaning the regression is being computed considering only 1 latent component in PLS, but you Accord.NET has not been instructed to do the same.

Accord.NET returns a MultivariateLinearRegression object that contains both a matrix of weights as well as a vector of intercepts, whereas and MATLAB returns the intercepts as the first column of the weights matrix.

Once all these are taken in consideration, it is possible to generate exact the same results as the MATLAB version:

double[][] inputs = new double[][]
{
    //      Wine | Price | Sugar | Alcohol | Acidity
    new double[] {   7,     7,      13,        7 },
    new double[] {   4,     3,      14,        7 },
    new double[] {  10,     5,      12,        5 },
    new double[] {  16,     7,      11,        3 },
    new double[] {  13,     3,      10,        3 },
};

double[][] outputs = new double[][]
{
    //             Wine | Hedonic | Goes with meat | Goes with dessert
    new double[] {           14,          7,                 8 },
    new double[] {           10,          7,                 6 },
    new double[] {            8,          5,                 5 },
    new double[] {            2,          4,                 7 },
    new double[] {            6,          2,                 4 },
};

// Create the Partial Least Squares Analysis
var pls = new PartialLeastSquaresAnalysis()
{
    Method = AnalysisMethod.Center,
    Algorithm = PartialLeastSquaresAlgorithm.SIMPLS, // First change: use SIMPLS
};

// Learn the analysis
pls.Learn(inputs, outputs);

// Second change: Use just 1 latent factor/component
var regression = pls.CreateRegression(factors: 1);

// Third change: present results as in MATLAB
double[][] w = regression.Weights.Transpose();
double[] b = regression.Intercepts;

// Add the intercepts as the first column of the matrix of
// weights and transpose it as in the way MATLAB presents it
double[][] coeffs = (w.InsertColumn(b, index: 0)).Transpose();

// Show results in MATLAB format
string str = coeffs.ToOctave();

With those changes, the coeffs matrix above should become

[ 10.4844779770616    6.18986077674717    6.28413863347486    ;
  -0.634878923091644 -0.304054829845448  -0.0726082626993539  ;
   0.0219492754418065 0.0105118991463605  0.00251024045589416 ;
   0.192261724966225  0.0920775662006966  0.0219881135215502  ;
   0.289484835410222  0.13863944631343    0.033107085796122   ]


答:
This indicates a "corrupted" XML file somewhere in your local Maven repository, and as suggested on https://stackoverflow.com/a/43637902/421602, the simplest solution when you hit this is to just wipe your ~/.m2/repository folder.

.

Title: Maven Error 9723

Body:
I am new to java and maven, below is the build output of maven in Eclipse, please help.

[INFO] Scanning for projects...

  [INFO]

  [INFO] ------------------------------------------------------------------------

  [INFO] Building DudyScheduleManager 1.0.0-BUILD-SNAPSHOT

  [INFO] ------------------------------------------------------------------------

  [INFO] ------------------------------------------------------------------------

  [INFO] BUILD FAILURE

  [INFO] ------------------------------------------------------------------------

  [INFO] Total time: 0.919 s

  [INFO] Finished at: 2017-06-18T18:59:57+08:00

  [INFO] Final Memory: 8M/245M

  [INFO] ------------------------------------------------------------------------

  [ERROR] 9723

  ****[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.****


问:
Check if password field is empty
In my XAML I have:

```<code><PasswordBox PlaceholderText="Password" Name="login_password" Width="350" />
</code>```

Am trying to check if the PasswordBox is empty via:

```<code>if(login_password.Text == "") //this returns an error
{
    //show message box
}
</code>```

How can I check if the PasswordBox is empty?

答:
The PasswordBox has the Password property. So you should check for Password property instead of Text:

```<code>if(login_password.Password == "")
</code>```

Title: Check if password field is empty

Body:
In my XAML I have:

<PasswordBox PlaceholderText="Password" Name="login_password" Width="350" />

Am trying to check if the PasswordBox is empty via:

if(login_password.Text == "") //this returns an error
{
    //show message box
}

How can I check if the PasswordBox is empty?

Body:
The PasswordBox has the Password property. So you should check for Password property instead of Text:

if(login_password.Password == "")


问:
Meaning of suffix "x" in intrinsics like "_mm256_set1_epi64x"
In some intrinsics they use suffix x like _mm256_set1_epi64x . What's the meaning of it? For reference, _mm256_set1_epi32 comes without this suffix.

答:
TL:DR: MMX->SSE2 conversion intrinsics took the non-x _mm_set/set1_epi64 names.

This is all guesswork based on current function names, known history, and some compiler behaviour:

The first Intel SIMD intrinsics were for MMX.  __m64 is the MMX equivalent of SSE2 __m128i and AVX2 __m256i.  There were no 64-bit x86 CPUs at the time, so the widest set intrinsic was __m64 _mm_set_pi32 (int e1, int e0).  According to the intrinsic-finder, there still isn't any intrinsic for movq mm0, rax.  I think you can/should just cast int64_t to __m64.  (Although last time I experimented in the last year or so, gcc or clang (I forget which) did a poor job optimizing the MMX asm.  Aging compiler support is yet another reason to avoid MMX for new projects.)

When SSE2 was introduced in 2001, AMD64 / x86-64 still wasn't released yet, and wouldn't be supported by Intel for a few years.  (At that time they were hoping that IA-64 / Itanium would be the future and replace x86).  I haven't checked old manuals, but I guess that

__m128i _mm_set1_epi64 (__m64 a) was available back then and

__m128i _mm_set1_epi64x (__int64 a) probably wasn't.  (Notice that __int64 is not int64_t from <stdint.h>.  But it is a 64-bit integer type and is nothing to worry about.)

The epi stands for Extended(?) Packed Integer.  epi instead of pi tells you it's an SSE intrinsic, not an MMX intrinsic.  For intrinsics that convert from one element width to another, the intrinsics use the source width if that unambiguously identifies the operation (at least for the ones I looked at).  e.g. _mm_packs_epi32 (packssdw) or _mm_unpackhi_epi16 (punpckhwd).  PMOVZX needs both numbers, because there's _mm_cvtepu8_epi32 (pmovzxbd), _mm_cvtepu8_epi64 (pmovzxbq, etc.

Compilers did of course support 64-bit integers in 32-bit mode, so it would have made sense for Intel to include intrinsics for working with them.  But IIRC, in some compilers the 64x intrinsics are only available when compiling 64-bit code.  The 64x is only relevant for converting to/from scalar 64-bit integers, so you won't find an x version of _mm_add_epi64 or anything like that.

This only-in-64bit thing may still exist for _mm256_set1_epi64x depending on the compiler, but either way that history explains why 64x but not 32x.

(Sorry I'm lazy and didn't put together an experiment on Godbolt to check for current compilers with -m32.  It might be interesting to see what kind of asm you get from casting int64_t to __m64 and using a _mm_set intrinsic in 32-bit code.)


问:
What is the rationale behind the behavior of constructor pointer in JavaScript?
Considering the simplistic scenario:

```
function Base() {}
function Child() {}
Child.prototype = new Base;
```

I wonder why would an instance of Child have constructor property set to Base and not to Child?

答:
```<code>function Base() {}
//Base.prototype.constructor === Base
function Child() {}
//Child.prototype.constructor === Child;
var b = new Base;
//b.constructor = Base;
Child.prototype = b;
//Child.prototype.constructor === Base
</code>```

basically, any property of the prototype becomes a property of the instance, including "constructor"

when you reassign the whole prototype property to a new object, you're replacing the old constructor property with the new one.

if you don't want this to happen, you have to assign properties to the prototype object one by one, instead of assigning the whole prototype property to a new object at once. Or replace the old constructor property afterward.

Much better idea: don't rely on the constructor property for anything important.

OwnerDisplayName: Sergey Ilinsky

Body:
Considering the simplistic scenario:

function Base() {}
function Child() {}
Child.prototype = new Base;

I wonder why would an instance of Child have constructor property set to Base and not to Child?

LastEditorDisplayName: PhiLho

Body:
function Base() {}
//Base.prototype.constructor === Base
function Child() {}
//Child.prototype.constructor === Child;
var b = new Base;
//b.constructor = Base;
Child.prototype = b;
//Child.prototype.constructor === Base

basically, any property of the prototype becomes a property of the instance, including "constructor"

when you reassign the whole prototype property to a new object, you're replacing the old constructor property with the new one.

if you don't want this to happen, you have to assign properties to the prototype object one by one, instead of assigning the whole prototype property to a new object at once. Or replace the old constructor property afterward.

Much better idea: don't rely on the constructor property for anything important.

OwnerDisplayName: Breton


答:
you can add show more after 3 links inside every .trailerdiv. Also when a show more link is clicked look for hidden buttons inside its parent and show them, instead of showing all hidden buttons.

$(document).ready(function(){
  $( ".trailerdiv" ).each(function(){
      $(this).children(".playtrailer").eq(2).after('....Show More');//add a unique id to link
      $(this).children(".playtrailer:gt(2)" ).addClass('hide');
  });
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $(this).parent().children('button.playtrailer').removeClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide
{
  display:none;
}</code>```

div1

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div2

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

div3

<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>

```

Body:
you can add show more after 3 links inside every .trailerdiv. Also when a show more link is clicked look for hidden buttons inside its parent and show them, instead of showing all hidden buttons.

$(document).ready(function(){
  $( ".trailerdiv" ).each(function(){
      $(this).children(".playtrailer").eq(2).after('<a href="" id="particular">....Show More</a>');//add a unique id to link
      $(this).children(".playtrailer:gt(2)" ).addClass('hide');
  });
});

$(document).on('click','a#particular',function(e){
  e.preventDefault();
  $(this).addClass('hide');
  $(this).parent().children('button.playtrailer').removeClass('hide');
});

.hide
{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>div1</p>
<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

<p>div2</p>

<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>

<p>div3</p>

<div class="trailerdiv">
<button class="playtrailer">Trailer 1 </button>
<button class="playtrailer">Trailer 2 </button>
<button class="playtrailer">Trailer HD </button>
<button class="playtrailer">Trailer 5 </button>
<button class="playtrailer">Trailer 8 </button>
<button class="playtrailer">Video 3 </button>
</div>


问:
collation conflict SQL Server varchar stored procedure parameters
I'm using REXTESTER to write a piece of SQL Server code.

It says it's SQL Server 2014 Express Edition that's being used...

Here's the minimal code to cause the message.

```<code>CREATE PROCEDURE #CONVERT_TIME_TO_24_HR
(
  @TIME_STRING varchar(4)
)
AS
BEGIN
  DECLARE @AMPM as varchar(2);
  SET @AMPM = RIGHT(@TIME_STRING,2);
  IF @AMPM = 'am'
    SELECT 2
END
GO
</code>```

Here's the error:

```<code>Error(s), warning(s):
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation.
</code>```

If the @TIME_STRING is just declared and not a parameter to the stored procedure I don't have an issue. Since I have no control over the SQL Server instance, how do I work around this?

Here's a forked version when it's not a parameter - no issues

```<code>DECLARE @TIME_STRING varchar(4);
DECLARE @AMPM as varchar(2);
SET @AMPM = RIGHT(@TIME_STRING,2);
  IF @AMPM = 'am'
    SELECT 2
</code>```

答:
This would occur because the collation for the server/database/column has different values (probably the server and the database).  You can fix it by explicitly adding in the collation:

```<code>CREATE PROCEDURE #CONVERT_TIME_TO_24_HR (
  @TIME_STRING varchar(4)
) AS
BEGIN
  DECLARE @AMPM as varchar(2);
  SET @AMPM = RIGHT(@TIME_STRING,2);
  IF @AMPM = 'am' COLLATE SQL_Latin1_General_CP1_CI_AS ;
  SELECT 2;
END;
</code>```

I admit that this is not a common column.  On your own system, the default collations would probably all match.  I have no idea why the designers of Rextester would have different default collations.

Body:
I'm using REXTESTER to write a piece of SQL Server code.

It says it's SQL Server 2014 Express Edition that's being used...

Here's the minimal code to cause the message.

CREATE PROCEDURE #CONVERT_TIME_TO_24_HR
(
  @TIME_STRING varchar(4)
)
AS
BEGIN
  DECLARE @AMPM as varchar(2);
  SET @AMPM = RIGHT(@TIME_STRING,2);
  IF @AMPM = 'am'
    SELECT 2
END
GO

Here's the error:

Error(s), warning(s):
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation.

If the @TIME_STRING is just declared and not a parameter to the stored procedure I don't have an issue. Since I have no control over the SQL Server instance, how do I work around this?

Here's a forked version when it's not a parameter - no issues

DECLARE @TIME_STRING varchar(4);
DECLARE @AMPM as varchar(2);
SET @AMPM = RIGHT(@TIME_STRING,2);
  IF @AMPM = 'am'
    SELECT 2

Body:
This would occur because the collation for the server/database/column has different values (probably the server and the database).  You can fix it by explicitly adding in the collation:

CREATE PROCEDURE #CONVERT_TIME_TO_24_HR (
  @TIME_STRING varchar(4)
) AS
BEGIN
  DECLARE @AMPM as varchar(2);
  SET @AMPM = RIGHT(@TIME_STRING,2);
  IF @AMPM = 'am' COLLATE SQL_Latin1_General_CP1_CI_AS ;
  SELECT 2;
END;

I admit that this is not a common column.  On your own system, the default collations would probably all match.  I have no idea why the designers of Rextester would have different default collations.


问:
HTML Javascript dynamic changes to a button
Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:

var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
    validUser = true;
    document.getElementById("btnSignIn").outerHTML = "Sign out";
    document.getElementById("btnSignIn").style.backgroundColor = "pink";
    document.getElementById("results").innnerHTML = "Welcome " + user +"!";
    document.getElementById("txtUserName").style.visibility = "hidden";
    document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
  validUser = false;
}
}

function signin() {

if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

    validUser = false;
    document.getElementById("btnSignIn").innerHTML = "Sign in";
    document.getElementById("btnSignIn").style.backgroundColor = "orange";
    document.getElementById("results").innerHTML = "Welcome stranger";
    document.getElementById("txtUserName").style.visibility = "visible";
    document.getElementById("txtPassword").style.visibility = "visible";
    setCookie("txtUserName", null, "txtPassword", null, 365);
}
else {
    var user = document.getElementById("txtUserName").value;
    var pwd = document.getElementById("txtPassword").value;
    if (user.text === "" && user === null &&
        pwd.text === "" && pwd === null) {
        validUser = false;
    }

    else if (user === "john@me.com" && pwd === "snow") {
        validUser = true;
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("btnSignIn").outerHTML = "Sign out";
        document.getElementById("results").innerHTML = "Welcome "+ user      + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
        var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
        if (!myCookie) {
             validUser = false;
        }
    }
    return false;
}
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = uname + "=" + uvalue + "; " + expires;
    document.cookie = pname + "=" + pvalue + "; " + expires;
    return true;
}
else {
    return false;
}
}

function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
   var user = getCookie("username");
   if (user !== "") {
    return user;
   }else {
        return false;
    }
}
else {
    return false;
}
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav navbar-nav navbar-right">
                <li>
                    <form id="loginform" class="navbar-form navbar-right">
                        <div class="form-group">
                            <input type="text"  id="txtUserName" placeholder="Email" class="form-control">
                        </div>
                        <div class="form-group">
                            <input type="password" id="txtPassword" placeholder="Password" class="form-control">
                        </div>
                        <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();"  >Sign in</button>
                    </form>
                </li>
            </ul></code>```

The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.

答:
Yes, as Michael Coker answer, the problem was replacing the whole html element wit the "sign out" text.
I just wanted to add that that example code must be just for testing dinamicaly dom changes, if you wanna practice login/validation  DONT ever do that. I mean, the validation logic. </p>

Body:
Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:

var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
    validUser = true;
    document.getElementById("btnSignIn").outerHTML = "Sign out";
    document.getElementById("btnSignIn").style.backgroundColor = "pink";
    document.getElementById("results").innnerHTML = "Welcome " + user +"!";
    document.getElementById("txtUserName").style.visibility = "hidden";
    document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
  validUser = false;
}
}

function signin() {

if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

    validUser = false;
    document.getElementById("btnSignIn").innerHTML = "Sign in";
    document.getElementById("btnSignIn").style.backgroundColor = "orange";
    document.getElementById("results").innerHTML = "Welcome stranger";
    document.getElementById("txtUserName").style.visibility = "visible";
    document.getElementById("txtPassword").style.visibility = "visible";
    setCookie("txtUserName", null, "txtPassword", null, 365);
}
else {
    var user = document.getElementById("txtUserName").value;
    var pwd = document.getElementById("txtPassword").value;
    if (user.text === "" && user === null &&
        pwd.text === "" && pwd === null) {
        validUser = false;
    }

    else if (user === "john@me.com" && pwd === "snow") {
        validUser = true;
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("btnSignIn").outerHTML = "Sign out";
        document.getElementById("results").innerHTML = "Welcome "+ user      + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
        var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
        if (!myCookie) {
             validUser = false;
        }
    }
    return false;
}
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = uname + "=" + uvalue + "; " + expires;
    document.cookie = pname + "=" + pvalue + "; " + expires;
    return true;
}
else {
    return false;
}
}

function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
   var user = getCookie("username");
   if (user !== "") {
    return user;
   }else {
        return false;
    }
}
else {
    return false;
}
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}

                    <form id="loginform" class="navbar-form navbar-right">

                            <input type="text"  id="txtUserName" placeholder="Email" class="form-control">

                            <input type="password" id="txtPassword" placeholder="Password" class="form-control">

                        <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();"  >Sign in</button>
                    </form>

The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.


问:
Robot Framework: am I implementing the Page Object Pattern the right way?
I've read a few articles and examples but I'm still unsure about how to organize my test suites.

Let's say I'll be testing a company website, with a home page that has a menu taking the user to pages like "about", "products", "contact us".

This is what I've come up with so far to structure my project, but I'm not sure it's the best way in terms of scalability and maintainability:

/src/test/robotframework/acceptance contains a GeneralResources.robot file and one folder per website page.

GeneralResources.robot file contains a "Settings" section with Library references that will be used by all tests (e.g.: Selenium2Library)

/home folder contains 4 files:

__init__.robot with Test Setup and Test Teardown for all the home page tests.

Resources.robot with global variables (like ${home_url} or ${home_title}) and higher level keywords that the home page tests will use.

PageObjects.robot with variables that store locators for all the objects that will be tested in the home page (e.g.: main logo, main menu, page footer, etc.).

tests.robot with all tests I will perform in the home page. The Settings section invokes the other files (except for init which is automatically detected) like this:

Resource  Resources.robot

Resource  PageObjects.robot

Resource  ../GeneralResources.robot

/about folder will also contain 4 files, organized the same way as the /home folder.

/products folder will also contain 4 files, organized the same way as the /home folder.

/contactus folder will also contain 4 files, organized the same way as the /home folder.

I'm not exactly sure this is the right way to go, as 4 files per page seem like quite an overhead. I'd like to know if I'm overlooking something, or if maybe some of the files I'm using should be merged into one.

答:
The Page Object model is a good way of abstracting the application UI from your test logic on a per-page basis.

In the event that your application is structured in separate elements that are reused across several pages then the per-page approach may be less effective.

For an application I work with the ID generation is predictable that the abstraction I chose mirrors the structure of the application and thus per-page I just re-use the basic building blocks that represent the application functionality.


问:
How to check Django version
I have to use Python and Django for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. But how do I make sure whether Django uses the 2.6 or 2.7 version and what version of modules Django uses?</p>

答:
```<code>django-admin --version
python manage.py --version
pip freeze | grep django
</code>```

Title: How to check Django version


问:
How to convert unicode accented characters to pure ascii without accents?
I'm trying to download some content from a dictionary site like http://dictionary.reference.com/browse/apple?s=t

The problem I'm having is that the original paragraph has all those squiggly lines, and reverse letters, and such, so when I read the local files I end up with those funny escape characters like \x85, \xa7, \x8d, etc.

My question is, is there any way i can convert all those escape characters into their respective UTF-8 characters, eg if there is an 'à' how do i convert that into a standard 'a' ?

Python calling code:

```<code>import os
word = 'apple'
os.system(r'wget.lnk --directory-prefix=G:/projects/words/dictionary/urls/ --output-document=G:\projects\words\dictionary\urls/' + word + '-dict.html http://dictionary.reference.com/browse/' + word)
</code>```

I'm using wget-1.11.4-1 on a Windows 7 system (don't kill me Linux people, it was a client requirement), and the wget exe is being fired off with a Python 2.6 script file.

答:
I needed something like this but to remove only accented characters, ignoring special ones and I did this small function:

```<code># ~*~ coding: utf-8 ~*~
import re

def remove_accents(string):
    if type(string) is not unicode:
        string = unicode(string, encoding='utf-8')

    string = re.sub(u"[àáâãäå]", 'a', string)
    string = re.sub(u"[èéêë]", 'e', string)
    string = re.sub(u"[ìíîï]", 'i', string)
    string = re.sub(u"[òóôõö]", 'o', string)
    string = re.sub(u"[ùúûü]", 'u', string)
    string = re.sub(u"[ýÿ]", 'y', string)

    return string
</code>```

I like that function because you can customize it in case you need to ignore other characters

Body:
I'm trying to download some content from a dictionary site like http://dictionary.reference.com/browse/apple?s=t

The problem I'm having is that the original paragraph has all those squiggly lines, and reverse letters, and such, so when I read the local files I end up with those funny escape characters like \x85, \xa7, \x8d, etc.

My question is, is there any way i can convert all those escape characters into their respective UTF-8 characters, eg if there is an 'à' how do i convert that into a standard 'a' ?

Python calling code:

import os
word = 'apple'
os.system(r'wget.lnk --directory-prefix=G:/projects/words/dictionary/urls/ --output-document=G:\projects\words\dictionary\urls/' + word + '-dict.html http://dictionary.reference.com/browse/' + word)

I'm using wget-1.11.4-1 on a Windows 7 system (don't kill me Linux people, it was a client requirement), and the wget exe is being fired off with a Python 2.6 script file.

Body:
I needed something like this but to remove only accented characters, ignoring special ones and I did this small function:

# ~*~ coding: utf-8 ~*~
import re

def remove_accents(string):
    if type(string) is not unicode:
        string = unicode(string, encoding='utf-8')

    string = re.sub(u"[àáâãäå]", 'a', string)
    string = re.sub(u"[èéêë]", 'e', string)
    string = re.sub(u"[ìíîï]", 'i', string)
    string = re.sub(u"[òóôõö]", 'o', string)
    string = re.sub(u"[ùúûü]", 'u', string)
    string = re.sub(u"[ýÿ]", 'y', string)

    return string

I like that function because you can customize it in case you need to ignore other characters


问:
How to fill two arc in xamarin android
I have drawn two arcs as path like below,

```<code> Path path = new Path();
 path.ArcTo(rc, (float)startArc, (float)(angle1 - startArc));
 path.ArcTo(innerrc,  (float)(angle - startArc), (float)startArc);
 canvas.DrawPath(path, paint);
</code>```

Now i need to fill those two arcs.

Any idea about this? !

答:
Finally got it and this works fine for me !</p>

```<code> Path path = new Path();
 paint.SetStyle(Paint.Style.Fill);
 path.MoveTo((float)xnew, (float)ynew);
 path.ArcTo(rc, (float)startArc, (float)(angle1 - startArc));
 path.LineTo((float)xnew1, (float)ynew1);
 path.ArcTo(innerrc,  (float)(angle - startArc), (float)startArc);
 path.LineTo((float)xnew, (float)ynew);
 canvas.DrawPath(path, paint);
</code>```

Title: How to fill two arc in xamarin android

Body:
I have drawn two arcs as path like below,

 Path path = new Path();
 path.ArcTo(rc, (float)startArc, (float)(angle1 - startArc));
 path.ArcTo(innerrc,  (float)(angle - startArc), (float)startArc);
 canvas.DrawPath(path, paint);

Now i need to fill those two arcs.

Any idea about this? !

Body:
Finally got it and this works fine for me !

 Path path = new Path();
 paint.SetStyle(Paint.Style.Fill);
 path.MoveTo((float)xnew, (float)ynew);
 path.ArcTo(rc, (float)startArc, (float)(angle1 - startArc));
 path.LineTo((float)xnew1, (float)ynew1);
 path.ArcTo(innerrc,  (float)(angle - startArc), (float)startArc);
 path.LineTo((float)xnew, (float)ynew);
 canvas.DrawPath(path, paint);


问:
Domain object validation vs view model validation
I am using ASP.NET MVC 3 and I am using FluentValidation to validate my view models.  I am just a little concerned that I might not be on the correct track.  As far as what I know, model validation should be done on the domain object.  Now with MVC you might have multiple view models that are similar that needs validation.  What happens if a property from a domain object occurs in more than one view model?  Now you are validating the same property twice, and they might not even be in sync.  So if I have a User domain object then I would like to do validation on this object.  Now what happens if I have UserAViewModel and UserBViewModel, so now it is multiple validations that needs to be done.

In my News class I have a property called Title, which is a required field. On my view model I also have a Title property, I use AutoMapper to map the News and NewsViewModel. So this validation is happening twice. When does domain model validation occur and when does view model validation occur?

The scenario above is just an example, so please don't critise on it.

答: It's a subtle distinction but the validation on your view model is to validate correct user input and forms an anti-corruption layer for your domain model, whereas the "validation" on your domain model enforces business rules.  It is perfectly normal and you should have validation on both layers.  In fact it may be feasible that UserAViewModel has slightly different input validation from UserBViewModel.  As for your question, generally I try to avoid exposing domain objects through my ViewModel and instead map between them (often using something like AutoMapper), that way your ViewModels truly are anticorruption layers rather than property bags of domain models.  Hope that helps.</p>


问:
A better method to implement the alpha synapse function in MATLAB
I have implemented a leaky integrate and fire neuron system that gives output in the form of an alpha function alpha = t/tau * exp(1 - (t/tau)). However, the piece of code that I use to implement it takes up atleast 80% of the runtime (approximately 4s out of the total 5s). During the course of the program this prt gets called at least 30000 times while the computealphasynapseoutput function gets called at least 1.5 million times. So I want to reduce the runtime of this part. I have tried using arrayfun to implement it but that takes up a lot more time than this.

Can anyone suggest a more efficient implementation for this code??

To implement the alpha synapse I used the following piece of code:

```<code>% Get the identity of the currently active neurons
idAllActiveNeuron = idAllActiveNeuron > 0;
if any(idAllActiveNeuron) % Only run if atleast one neuron is active
    for iActiveNeuron = find(idAllActiveNeuron).' % run for each active neuron
        %% synapticOutputArray stores the synaptic output for each neuron for each time instant
        %% iIntegration is the time instant
        %% spikeTimesArray is a cell array that is composed of spike times for
        % each neuron. So if I have 5 neurons and neuron 4 spikes twice
        % while neuron 5 spikes once, spikeTimesArray would be something
        % like {[], [], [], [0.0023, 0.0034], [0.0675]}
        %% integrationInstant would be a time value like 0.0810
        %% tau_syn stores the value of tau for each neuron

        synapticOutputArray(iActiveNeuron, iIntegration) = computealphasynapseoutput(spikeTimesArray{iActiveNeuron}, integrationInstant, tau_syn(iActiveNeuron));

    end % iActiveNeuron
end
</code>```

The function computealphasynapse is implemented as follows:

```<code>function synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%%COMPUTEALPHASYNAPSEOUTPUT Calculates the synaptic output over all
%previous spikes of the neuron at a particular time instant using the
%alpha synapse function
%
% Usage:
%   synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%
% Inputs:
%           firingTime: vector of previous firing times (in seconds)
%   integrationInstant: current integration time instant (in seconds)
%               tauSyn: synaptic time constant of the neuron (in seconds)
%
% Output:
%   synapticOutput: Synaptic output of the neuron at current time summed
%                   over all firing instances
%

% Calculate the time difference of firing from current time
timeDifference = (integrationInstant - firingTime) / tauSyn;
% Calculate and sum the synaptic output for each spike
synapticOutput = sum(timeDifference .* exp(1 - timeDifference));

end % computealphasynapseoutput
</code>```

Edit:

I have finally awarded the bounty for this question to gnovice
  for his awesome answer. It helped me to shave off an entire 40 seconds
  from my simulation time (from 68 to 28 s). I hope it works for people
  in the future too. I would also like to acknowledge MrAzzaman and
  qbzenker for taking their time to answer the question and
  teaching me some cool new approaches. Also, others who commented and
  helped me. Thanks

答:
This code gives me a significant speed up under the right conditions (typically low max number of spike times for any given neuron at a given time and a number of neurons > 5). With a low number of neurons, it is similar to the performance of your code above.

Note that I haven't tested this code with your real inputs so you might have to do some tweaking in order to make it work. Also, it might actually be slower with your data than the dummy data I used. The idea behind the speedup is vectorization --
 essentially doing operations on the entire vector instead of splitting it up over a bunch of for loops.

This will require you to make spikeTimesArray a matrix with NaNs instead of missing values. So something like this:

```<code> spikeTimesArray={[], [], [], [0.0023, 0.0034], [0.0675]}
</code>```

would become

```<code>spikeTimesArray=[[NaN;NaN], [NaN;NaN], [NaN;NaN], [0.0023; 0.0034], [0.0675;NaN]]
</code>```

and instead of using for loops, you'd just do the entire vector operation:

```<code>idAllActiveNeuron = idAllActiveNeuron > 0;
if any(idAllActiveNeuron) % Only run if atleast one neuron is active
   % for iActiveNeuron = find(idAllActiveNeuron) % ELIMINATE THIS FOR LOOP

iActiveNeuron = find(idAllActiveNeuron);

timeDifference = (integrationInstant -spikeTimesArray2(:,iActiveNeuron))...
                  ./ tau_syn(iActiveNeuron);

synapticOutputArray(iActiveNeuron, iIntegration) = ...
                                sum(timeDifference .* exp(1 - timeDifference),'omitnan');
</code>```

Note that in this implementation I am assuming that spikeTimesArray2 is an NxM matrix where N corresponds to the number of maximal spikes for a given neuron and M is the total number of neurons. Also, tau_syn is a row vector.

Body:
I have implemented a leaky integrate and fire neuron system that gives output in the form of an alpha function alpha = t/tau * exp(1 - (t/tau)). However, the piece of code that I use to implement it takes up atleast 80% of the runtime (approximately 4s out of the total 5s). During the course of the program this prt gets called at least 30000 times while the computealphasynapseoutput function gets called at least 1.5 million times. So I want to reduce the runtime of this part. I have tried using arrayfun to implement it but that takes up a lot more time than this.

Can anyone suggest a more efficient implementation for this code??

To implement the alpha synapse I used the following piece of code:

% Get the identity of the currently active neurons
idAllActiveNeuron = idAllActiveNeuron > 0;
if any(idAllActiveNeuron) % Only run if atleast one neuron is active
    for iActiveNeuron = find(idAllActiveNeuron).' % run for each active neuron
        %% synapticOutputArray stores the synaptic output for each neuron for each time instant
        %% iIntegration is the time instant
        %% spikeTimesArray is a cell array that is composed of spike times for
        % each neuron. So if I have 5 neurons and neuron 4 spikes twice
        % while neuron 5 spikes once, spikeTimesArray would be something
        % like {[], [], [], [0.0023, 0.0034], [0.0675]}
        %% integrationInstant would be a time value like 0.0810
        %% tau_syn stores the value of tau for each neuron

        synapticOutputArray(iActiveNeuron, iIntegration) = computealphasynapseoutput(spikeTimesArray{iActiveNeuron}, integrationInstant, tau_syn(iActiveNeuron));

    end % iActiveNeuron
end

The function computealphasynapse is implemented as follows:

function synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%%COMPUTEALPHASYNAPSEOUTPUT Calculates the synaptic output over all
%previous spikes of the neuron at a particular time instant using the
%alpha synapse function
%
% Usage:
%   synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%
% Inputs:
%           firingTime: vector of previous firing times (in seconds)
%   integrationInstant: current integration time instant (in seconds)
%               tauSyn: synaptic time constant of the neuron (in seconds)
%
% Output:
%   synapticOutput: Synaptic output of the neuron at current time summed
%                   over all firing instances
%

% Calculate the time difference of firing from current time
timeDifference = (integrationInstant - firingTime) / tauSyn;
% Calculate and sum the synaptic output for each spike
synapticOutput = sum(timeDifference .* exp(1 - timeDifference));

end % computealphasynapseoutput

Edit:

I have finally awarded the bounty for this question to gnovice
  for his awesome answer. It helped me to shave off an entire 40 seconds
  from my simulation time (from 68 to 28 s). I hope it works for people
  in the future too. I would also like to acknowledge MrAzzaman and
  qbzenker for taking their time to answer the question and
  teaching me some cool new approaches. Also, others who commented and
  helped me. Thanks

Body:
This code gives me a significant speed up under the right conditions (typically low max number of spike times for any given neuron at a given time and a number of neurons > 5). With a low number of neurons, it is similar to the performance of your code above.

Note that I haven't tested this code with your real inputs so you might have to do some tweaking in order to make it work. Also, it might actually be slower with your data than the dummy data I used. The idea behind the speedup is vectorization --
 essentially doing operations on the entire vector instead of splitting it up over a bunch of for loops.

This will require you to make spikeTimesArray a matrix with NaNs instead of missing values. So something like this:

 spikeTimesArray={[], [], [], [0.0023, 0.0034], [0.0675]}

would become

spikeTimesArray=[[NaN;NaN], [NaN;NaN], [NaN;NaN], [0.0023; 0.0034], [0.0675;NaN]]

and instead of using for loops, you'd just do the entire vector operation:

idAllActiveNeuron = idAllActiveNeuron > 0;
if any(idAllActiveNeuron) % Only run if atleast one neuron is active
   % for iActiveNeuron = find(idAllActiveNeuron) % ELIMINATE THIS FOR LOOP

iActiveNeuron = find(idAllActiveNeuron);

timeDifference = (integrationInstant -spikeTimesArray2(:,iActiveNeuron))...
                  ./ tau_syn(iActiveNeuron);

synapticOutputArray(iActiveNeuron, iIntegration) = ...
                                sum(timeDifference .* exp(1 - timeDifference),'omitnan');

Note that in this implementation I am assuming that spikeTimesArray2 is an NxM matrix where N corresponds to the number of maximal spikes for a given neuron and M is the total number of neurons. Also, tau_syn is a row vector.


问:
why I can't use background mode in my app in swift 3?
I want to use background mode in my app so in the capabilities I ticked background fetch and notification But The problem is that just in the simulator every things are ok and in the real iPhone the app will freeze in the background</p>

答:
You can't fetch the the latest content from a server in background mode as Apple only allowed to fetch content in specific reasons eg.

Implementing Long-Running Tasks

For tasks that require more execution time to implement, you must
request specific permissions to run them in the background without
their being suspended. In iOS, only specific app types are allowed
to run in the background:

Apps that play audible content to the user while in the background,
such as a music player app

Apps that record audio content while in the background

Apps that keep users informed of their location at all times, such as
a navigation app

Apps that support Voice over Internet Protocol (VoIP)

Apps that need to download and process new content regularly

Apps that receive regular updates from external accessories

Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services. Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.

Instead of these you can fetch the content from server in short period of time eg. 1-2 mins depending of cpu usage

```<code>func doUpdate() {
    DispatchQueue.global(qos: .default).async(execute: {() -> Void in
        self.beginBackgroundUpdateTask()
        var response: URLResponse? = nil
        var error: Error? = nil
        let responseData: Data? = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: response)
        // Do something with the result
        self.endBackgroundUpdateTask()
    })
}

func beginBackgroundUpdateTask() {
    backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(withExpirationHandler: {() -> Void in
        self.endBackgroundUpdateTask()
    })
}

func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(backgroundUpdateTask)
    backgroundUpdateTask = UIBackgroundTaskInvalid
}
</code>```

Body:
You can't fetch the the latest content from a server in background mode as Apple only allowed to fetch content in specific reasons eg.

Implementing Long-Running Tasks

For tasks that require more execution time to implement, you must
request specific permissions to run them in the background without
their being suspended. In iOS, only specific app types are allowed
to run in the background:

Apps that play audible content to the user while in the background,
such as a music player app

Apps that record audio content while in the background

Apps that keep users informed of their location at all times, such as
a navigation app

Apps that support Voice over Internet Protocol (VoIP)

Apps that need to download and process new content regularly

Apps that receive regular updates from external accessories

Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services. Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.

Instead of these you can fetch the content from server in short period of time eg. 1-2 mins depending of cpu usage

func doUpdate() {
    DispatchQueue.global(qos: .default).async(execute: {() -> Void in
        self.beginBackgroundUpdateTask()
        var response: URLResponse? = nil
        var error: Error? = nil
        let responseData: Data? = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: response)
        // Do something with the result
        self.endBackgroundUpdateTask()
    })
}

func beginBackgroundUpdateTask() {
    backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(withExpirationHandler: {() -> Void in
        self.endBackgroundUpdateTask()
    })
}

func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(backgroundUpdateTask)
    backgroundUpdateTask = UIBackgroundTaskInvalid
}


问:
Alamofire error with JSON response
I have been struggling with Alamofire issue for days and I'm not sure if it's from the backend or the way I structure my code.

Here is the issue:

when I text my API with Postman I get the correct response if I hit the params button and add the parameters Notice the lower body is empty but the upper one is filled with parameters

However, when I use the lower parameters with the same info I get an error with no JSON. Also same error appears in Xcode when I try to call the API with the same link

this is Xcode Alamofire error

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

and here is Postman error

and finally this is my code to call API:

```<code>    let urlStr = "api/client/meal_add"
    let url = URL(string: urlStr)
    let para = ["meal_id": "31",
                "user_id": "2",
                "qty":"2"]

    let headers: HTTPHeaders = [
        "Auth": "Auth" // Edited for security
    ]

    Alamofire.request(url!, method: .post, parameters: para,encoding: URLEncoding.default, headers: headers).responseJSON { response in
        print(response)
        print(response.result.debugDescription)
        if let value : AnyObject = response.result.value as AnyObject {
</code>```

it used to work perfectly 5 days ago but I have no idea why it stoped. Also In other View Controllers I do HTTP calls to the same API and the responses have no issues, only this one.

答:
First, I want to talk about the difference between HTTP get and post request. Get request is putting parameters in url. They are appended to the url in this format

```<code>URL?key1=value1&key2=value2
</code>```

The RESTful hanlder for that URL will then parse the key value pair and use them. When you click on the param button in your postman, it actuall doing this append param to url thing. However this get into problem when you have lots of param. Usually, an url will have some problem if it exceeds length 8000. So a post request is actually nesting the parameters inside the request, not on the url. So normally in a post request, you will only see the URL, not the ?key1=value1&key2=value2 part.

Back to your problem, I have no idea how your server side handles this post request with parameters in url but since an empty post request with param in url works, in your swift code, you can simply append the param in your url and do a post request with no parameters.

```<code>let urlStr = "api/client/meal_add?meal_id=31&user_id=2&qty=2"
let url = URL(string: urlStr)

Alamofire.request(url!, method: .post, parameters: [],encoding: URLEncoding.default, headers: headers).responseJSON { response in
</code>```

Moving forward, I strongly recommand you to have a look at your server side to make sure your post request is written in the correct way

Title: Alamofire error with JSON response

Body:
I have been struggling with Alamofire issue for days and I'm not sure if it's from the backend or the way I structure my code.

Here is the issue:

when I text my API with Postman I get the correct response if I hit the params button and add the parameters Notice the lower body is empty but the upper one is filled with parameters

However, when I use the lower parameters with the same info I get an error with no JSON. Also same error appears in Xcode when I try to call the API with the same link

this is Xcode Alamofire error

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

and here is Postman error

and finally this is my code to call API:

    let urlStr = "api/client/meal_add"
    let url = URL(string: urlStr)
    let para = ["meal_id": "31",
                "user_id": "2",
                "qty":"2"]

    let headers: HTTPHeaders = [
        "Auth": "Auth" // Edited for security
    ]

    Alamofire.request(url!, method: .post, parameters: para,encoding: URLEncoding.default, headers: headers).responseJSON { response in
        print(response)
        print(response.result.debugDescription)
        if let value : AnyObject = response.result.value as AnyObject {

it used to work perfectly 5 days ago but I have no idea why it stoped. Also In other View Controllers I do HTTP calls to the same API and the responses have no issues, only this one.

Body:
First, I want to talk about the difference between HTTP get and post request. Get request is putting parameters in url. They are appended to the url in this format

URL?key1=value1&key2=value2

The RESTful hanlder for that URL will then parse the key value pair and use them. When you click on the param button in your postman, it actuall doing this append param to url thing. However this get into problem when you have lots of param. Usually, an url will have some problem if it exceeds length 8000. So a post request is actually nesting the parameters inside the request, not on the url. So normally in a post request, you will only see the URL, not the ?key1=value1&key2=value2 part.

Back to your problem, I have no idea how your server side handles this post request with parameters in url but since an empty post request with param in url works, in your swift code, you can simply append the param in your url and do a post request with no parameters.

let urlStr = "api/client/meal_add?meal_id=31&user_id=2&qty=2"
let url = URL(string: urlStr)

Alamofire.request(url!, method: .post, parameters: [],encoding: URLEncoding.default, headers: headers).responseJSON { response in

Moving forward, I strongly recommand you to have a look at your server side to make sure your post request is written in the correct way


问:
random row query optimization in innodb table
```<code>$offset = SELECT FLOOR(RAND() * COUNT(*)) FROM t_table
SELECT * FROM t_table WHERE LIMIT $offset,1
</code>```

This works great in myisam but i would like to change this table to innodb (all other db tables are innodb) to take advantages of foreign-keys and avoid table level locking.

The primaryId field of this table is a VARCHAR(10)

I can't "force" a numeric autoinc Id, because records are deleted/added all the time and a RANDOM(MIN(Id), MAX(Id)) prediction would probably miss rows lots of times.

how can i optimize this query to innodb?

Thanks in advance!

Arthur

答:
"SELECT * FROM t_table ORDER BY RAND() LIMIT 1 "

That will not work, because mySQL will check all the rows who match the condition (no condition here, so will take all the rows) they will copy the rows in a temporary table and then will select a random row

Body:
$offset = SELECT FLOOR(RAND() * COUNT(*)) FROM t_table
SELECT * FROM t_table WHERE LIMIT $offset,1

This works great in myisam but i would like to change this table to innodb (all other db tables are innodb) to take advantages of foreign-keys and avoid table level locking.

The primaryId field of this table is a VARCHAR(10)

I can't "force" a numeric autoinc Id, because records are deleted/added all the time and a RANDOM(MIN(Id), MAX(Id)) prediction would probably miss rows lots of times.

how can i optimize this query to innodb?

Thanks in advance!

Arthur


问:
Recombine capture groups in single regexp?
I am trying to handle input groups similar to:

'...A.B.' and want to output '.....AB'.

Another example:

'.C..Z..B.' ==> '......CZB'

I have been working with the following:

```<code>'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1")
</code>```

returns:

```<code>"....."
</code>```

and

```<code>'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")
</code>```

returns:

```<code>"AB"
</code>```

but

```<code>'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1$2")
</code>```

returns

```<code>"...A.B."
</code>```

Is there a way to return

```<code>"....AB"
</code>```

with a single regexp?

I have only been able to accomplish this with:

```<code>'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1") + '...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")
</code>```

==> ".....AB"

答:
If the goal is to move all of the . to the beginning and all of the A-Z to the end, then I believe the answer to

with a single regexp?

is "no."

Separately, I don't think there's a simpler, more efficient way than two replace calls — but not the two you've shown. Instead:

var str = "...A..B...C.";
var result = str.replace(/[A-Z]/g, "") + str.replace(/\./g, "");
console.log(result);```
</div>
</div>
</p>

<p>(I don't know what you want to do with non-<code>.</code>, non-<code>A-Z</code> characters, so I've ignored them.)</p>

<p>If you <em>really</em> want to do it with a single call to <code>replace</code> (e.g., a single pass through the string matters), you can, but I'm fairly sure you'd have to use the function callback and state variables:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = "...A..B...C.";
var dots = "";
var nondots = "";
var result = str.replace(/\.|[A-Z]|$/g, function(m) {
  if (!m) {
    // Matched the end of input; return the
    // strings we've been building up
    return dots + nondots;
  }
  // Matched a dot or letter, add to relevant
  // string and return nothing
  if (m === ".") {
    dots += m;
  } else {
    nondots += m;
  }
  return "";
});
console.log(result);</code>```

That is, of course, incredibly ugly. :-)

Body:
I am trying to handle input groups similar to:

'...A.B.' and want to output '.....AB'.

Another example:

'.C..Z..B.' ==> '......CZB'

I have been working with the following:

'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1")

returns:

"....."

and

'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")

returns:

"AB"

but

'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1$2")

returns

"...A.B."

Is there a way to return

"....AB"

with a single regexp?

I have only been able to accomplish this with:

'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1") + '...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")

==> ".....AB"

Body:
If the goal is to move all of the . to the beginning and all of the A-Z to the end, then I believe the answer to

with a single regexp?

is "no."

Separately, I don't think there's a simpler, more efficient way than two replace calls — but not the two you've shown. Instead:

var str = "...A..B...C.";
var result = str.replace(/[A-Z]/g, "") + str.replace(/\./g, "");
console.log(result);

(I don't know what you want to do with non-., non-A-Z characters, so I've ignored them.)

If you really want to do it with a single call to replace (e.g., a single pass through the string matters), you can, but I'm fairly sure you'd have to use the function callback and state variables:

var str = "...A..B...C.";
var dots = "";
var nondots = "";
var result = str.replace(/\.|[A-Z]|$/g, function(m) {
  if (!m) {
    // Matched the end of input; return the
    // strings we've been building up
    return dots + nondots;
  }
  // Matched a dot or letter, add to relevant
  // string and return nothing
  if (m === ".") {
    dots += m;
  } else {
    nondots += m;
  }
  return "";
});
console.log(result);

That is, of course, incredibly ugly. :-)


问:
div has as extra unwanted space on top inside pre
I can't understand why there is an empty space on the top. I haven't applied any styles to it

```
  <div class="codeBlock">
    <ol>
     <li>(function() {</li>
     <li>function $codeBlock() {</li>
     <li>return {};</li>
     </li>}</li>
    </ol>
  </div>
``````

答:
Ok so heres the thing. pre takes every character and interpret it in it's display, that mean it will litterally "show" a carriage return. Try to remove the spaces. Lets say you you twig, apply {% spaceless %}. If you use something else, use the proper function, but if you do it manually, do like i just did in the example below :) Cheers

```<div class="codeBlock"><ol><li>(function() {</li><li>function $codeBlock() {</li><li>return {};</li><li>}</li></ol></div>``````

Body:
I can't understand why there is an empty space on the top. I haven't applied any styles to it

(function() {

function $codeBlock() {

return {};

}

Body:
Ok so heres the thing. pre takes every character and interpret it in it's display, that mean it will litterally "show" a carriage return. Try to remove the spaces. Lets say you you twig, apply {% spaceless %}. If you use something else, use the proper function, but if you do it manually, do like i just did in the example below :) Cheers

<pre><div class="codeBlock"><ol><li>(function() {</li><li>function $codeBlock() {</li><li>return {};</li><li>}</li></ol></div></pre>


问:
Join two tables, where one is not uniqe
Hey everyone. I need to join two tables according to those parameters:

1) I need only data that are both in the first and in the second table

2) Data in the second table can have more rows attached to one row of the first table, but I need those rows displayed only once.

I tried this

```<code>SELECT * FROM table AS p
            JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
            ORDER BY p.id
</code>```

but I am getting duplicates, as mentioned.

Thanks

答:
Assuming you only care about the final output, use distinct:</p>

```<code>SELECT distinct * FROM table AS p
         JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
         ORDER BY p.id
</code>```

Title: Join two tables, where one is not uniqe

Body:
Hey everyone. I need to join two tables according to those parameters:

1) I need only data that are both in the first and in the second table

2) Data in the second table can have more rows attached to one row of the first table, but I need those rows displayed only once.

I tried this

SELECT * FROM table AS p
            JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
            ORDER BY p.id

but I am getting duplicates, as mentioned.

Thanks

Body:
Assuming you only care about the final output, use distinct:

SELECT distinct * FROM table AS p
         JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
         ORDER BY p.id


问:
Sleuth + Zipkins with Elasticsearch
Can anyone point me towards the required/working configuration to use Elasticsearch as a storage type with Zipkins with Sleuth?

pom.xml

'

```<code><description>Spring Boot Zipkin Server</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.7.RELEASE</version>
</parent>

<properties>
    <docker.image.prefix>springio</docker.image.prefix>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <sonar.skip>true</sonar.skip>
    <zipkin.version>1.6.0</zipkin.version>
    <elasticsearch.version>2.3.4</elasticsearch.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth-zipkin-stream</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
    </dependency>
    <!-- EXAMPLE FOR RABBIT BINDING -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <finalName>demo-zipkin-server</finalName>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

`

application.yml

server:
  port: 9411
spring:
  rabbitmq:
    host: ${RABBIT_HOST:localhost}
eureka:
 client:
  register-with-eureka: true
  service-url:
   defaultZone: http://localhost:8761/eureka/
zipkin:
 self-tracing:
  enabled: false
  storage:
    type: elasticsearch
    elasticsearch:
      cluster: ${ES_CLUSTER:elasticsearch}
      hosts: ${ES_HOSTS:localhost:9300}
      index: ${ES_INDEX:zipkin}
      index-shards: ${ES_INDEX_SHARDS:5}
      index-replicas: ${ES_INDEX_REPLICAS:1}

Application doesn't start up with these config. It throws
Caused by: java.lang.NoSuchMethodError: org.springframework.integration.amqp.support.DefaultAmqpHeaderMapper.inboundMappe

答: Use spring cloud stream collector http://cloud.spring.io/spring-cloud-sleuth/spring-cloud-sleuth.html#_spring_cloud_sleuth_stream_zipkin_collector with an elasticsearch data store https://github.com/openzipkin/zipkin/blob/master/zipkin-server/README.md#elasticsearch-storage</p>

Title: Sleuth + Zipkins with Elasticsearch

Body:
Can anyone point me towards the required/working configuration to use Elasticsearch as a storage type with Zipkins with Sleuth?

pom.xml

'

<description>Spring Boot Zipkin Server</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.7.RELEASE</version>
</parent>

<properties>
    <docker.image.prefix>springio</docker.image.prefix>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <sonar.skip>true</sonar.skip>
    <zipkin.version>1.6.0</zipkin.version>
    <elasticsearch.version>2.3.4</elasticsearch.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth-zipkin-stream</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <finalName>demo-zipkin-server</finalName>
            </configuration>
        </plugin>
    </plugins>
</build>

`

application.yml

server:
  port: 9411
spring:
  rabbitmq:
    host: ${RABBIT_HOST:localhost}
eureka:
 client:
  register-with-eureka: true
  service-url:
   defaultZone: http://localhost:8761/eureka/
zipkin:
 self-tracing:
  enabled: false
  storage:
    type: elasticsearch
    elasticsearch:
      cluster: ${ES_CLUSTER:elasticsearch}
      hosts: ${ES_HOSTS:localhost:9300}
      index: ${ES_INDEX:zipkin}
      index-shards: ${ES_INDEX_SHARDS:5}
      index-replicas: ${ES_INDEX_REPLICAS:1}

Application doesn't start up with these config. It throws
Caused by: java.lang.NoSuchMethodError: org.springframework.integration.amqp.support.DefaultAmqpHeaderMapper.inboundMappe