问:
Javascript recursion problem
I am trying to write a function that will change between an array of images. What I have makes sense to me, but when I run it as it is below then the first image loads, then the second image loads at some point (the transparency doesn't change) and then nothing happens. Here is the javascript code:

```<code>        var image1 = new Image();var image2 = new Image(); var image3 = new Image();
        image1.src = "images/website6.jpg"; image2.src = "images/website7.jpg"; image3.src = "images/sunset.jpg";
        var images = new Array("images/website6.jpg","images/website7.jpg","images/sunset.jpg");
        /*document.slide.style.opacity = 1;
        document.slide.stylebg.opacity = 0;*/
        setTimeout(function() { fade(images,0); }, 2000);
        function delay(arr,num)
        {
            document.slide.src = arr[num % 3];
            document.slide.style.opacity = 1;
            document.slidebg.style.opacity = 0;
            document.slidebg.src = arr[(num+1)%3];
            var number = num + 1;
            setTimeout(function() { fade(arr,number); }, 2000);
        }
        function fade(arr,num)
        {
            /*alert('fadebefore ' + (document.slide.style.opacity).toString())*/
            document.slide.style.opacity -= 0.1
            /*alert('fade')*/
            document.slide.stylebg.opacity += 0.1
            if (document.slide.style.opacity == 0)
            {
                setTimeout(function() { delay(arr,num); }, 150);
            }
            else
            {
                setTimeout(function() { fade(arr,num); }, 1500);
            }
        }
</code>```

The HTML is simple. I have two classes; style and stylebg. style sits in front of stylebg and then I change opacities and images as needed. The javascript seems logical to me, but it doesn't work as expected. Also worth noting is there are 3 comments. The first comment (line 3-4) is attemping to set the opacities to what they should be at the beginning. However, if I do this then I get even less progress than above: the first image loads and nothing else happens. The second two comments are used for debugging purposes. If I uncomment these then the image change occurs between the two alerts, which would seem to say the image change is caused by the opacity change.

So can anybody explain why it isn't doing what I expect it to? Thanks.

EDIT: Some more code:

HTML (This is the only part being affected):

```<code><div style="position: relative;">
<img src="images/sunset.jpg" id="slide" />
<img src="images/website6.jpg" id="slidebg" />
</div>
</code>```

CSS:

```#slide{
    display:block;
    margin-left:5;
    margin-right:auto;
    border: 1px solid black;
    z-index: 1;
    top: 0px;
    position: relative;
}
#slidebg{
    display:block;
    margin-left:auto;
    margin-right:auto;
    border: 1px solid black;
    z-index: 0;
    top: 0px;
    position: absolute;
}```

答:
EDIT2

It works for me (chromium)

```<code>var images = new Array ();
images[0] = new Image();
images[0].src = "images/website6.jpg";
images[1] = new Image();
images[1].src = "images/website7.jpg";
images[2] = new Image();
images[2].src = "images/sunset.jpg";

function delay ( arr, num )
{
  slide.src = arr[num % 3].src;
  slide.style.opacity = 1;
  slidebg.style.opacity = 0;
  slidebg.src = arr[(num+1)%3].src;
  var number = num + 1;
  setTimeout(function() { fade(arr,number); }, 2000);
}

function fade(arr, num)
{
  if ( slide.style.opacity == 0 )
  setTimeout(function (){ delay(arr, num); }, 150);
  else
  {
    slide.style.opacity = (slide.style.opacity*10 - 1)/10 ;
    slidebg.style.opacity -= -0.1;
    setTimeout ( function(){fade(arr,num);}, 1500 );
  }
}
fade (images, 0);
</code>```

AHA!

 we can get by document.img_id, even in chromium

OK, OK, removed links to this WE TEACH YOU TO FAIL AT WEB DEV site..

Title: Javascript recursion problem

Body:
I am trying to write a function that will change between an array of images. What I have makes sense to me, but when I run it as it is below then the first image loads, then the second image loads at some point (the transparency doesn't change) and then nothing happens. Here is the javascript code:

        var image1 = new Image();var image2 = new Image(); var image3 = new Image();
        image1.src = "images/website6.jpg"; image2.src = "images/website7.jpg"; image3.src = "images/sunset.jpg";
        var images = new Array("images/website6.jpg","images/website7.jpg","images/sunset.jpg");
        /*document.slide.style.opacity = 1;
        document.slide.stylebg.opacity = 0;*/
        setTimeout(function() { fade(images,0); }, 2000);
        function delay(arr,num)
        {
            document.slide.src = arr[num % 3];
            document.slide.style.opacity = 1;
            document.slidebg.style.opacity = 0;
            document.slidebg.src = arr[(num+1)%3];
            var number = num + 1;
            setTimeout(function() { fade(arr,number); }, 2000);
        }
        function fade(arr,num)
        {
            /*alert('fadebefore ' + (document.slide.style.opacity).toString())*/
            document.slide.style.opacity -= 0.1
            /*alert('fade')*/
            document.slide.stylebg.opacity += 0.1
            if (document.slide.style.opacity == 0)
            {
                setTimeout(function() { delay(arr,num); }, 150);
            }
            else
            {
                setTimeout(function() { fade(arr,num); }, 1500);
            }
        }

The HTML is simple. I have two classes; style and stylebg. style sits in front of stylebg and then I change opacities and images as needed. The javascript seems logical to me, but it doesn't work as expected. Also worth noting is there are 3 comments. The first comment (line 3-4) is attemping to set the opacities to what they should be at the beginning. However, if I do this then I get even less progress than above: the first image loads and nothing else happens. The second two comments are used for debugging purposes. If I uncomment these then the image change occurs between the two alerts, which would seem to say the image change is caused by the opacity change.

So can anybody explain why it isn't doing what I expect it to? Thanks.

EDIT: Some more code:

HTML (This is the only part being affected):

CSS:

#slide{
    display:block;
    margin-left:5;
    margin-right:auto;
    border: 1px solid black;
    z-index: 1;
    top: 0px;
    position: relative;
}
#slidebg{
    display:block;
    margin-left:auto;
    margin-right:auto;
    border: 1px solid black;
    z-index: 0;
    top: 0px;
    position: absolute;
}

Body:
EDIT2

It works for me (chromium)

var images = new Array ();
images[0] = new Image();
images[0].src = "images/website6.jpg";
images[1] = new Image();
images[1].src = "images/website7.jpg";
images[2] = new Image();
images[2].src = "images/sunset.jpg";

function delay ( arr, num )
{
  slide.src = arr[num % 3].src;
  slide.style.opacity = 1;
  slidebg.style.opacity = 0;
  slidebg.src = arr[(num+1)%3].src;
  var number = num + 1;
  setTimeout(function() { fade(arr,number); }, 2000);
}

function fade(arr, num)
{
  if ( slide.style.opacity == 0 )
  setTimeout(function (){ delay(arr, num); }, 150);
  else
  {
    slide.style.opacity = (slide.style.opacity*10 - 1)/10 ;
    slidebg.style.opacity -= -0.1;
    setTimeout ( function(){fade(arr,num);}, 1500 );
  }
}
fade (images, 0);

AHA!

<img id="img_id"/> we can get by document.img_id, even in chromium

OK, OK, removed links to this WE TEACH YOU TO FAIL AT WEB DEV site..


来源: stackexchange

问:
Get record from particular department which is satisfying the condition?
```<code>create table tab1 (dep varchar2(10), val number);

begin
  insert into tab1 values ('a',10)
  insert into tab1 values ('a',20)
  insert into tab1 values ('a',30)
  insert into tab1 values ('b',10)
  insert into tab1 values ('b',20)
  insert into tab1 values ('c',10)
end;
</code>```

i need DEP and value matched only with 10,20,30

output:

```<code>DEP VAL
--- ---
a   10
a   20
a   30
</code>```

答:
Try this-

```<code>SELECT * FROM tab1
WHERE dep = 'Your Desired Dept Name Here'
AND val IN (10,20,30)
</code>```

For your case, if you wants to show records from Dept = A, the query will be as follow-

```<code>SELECT * FROM tab1
WHERE dep = 'a'
AND val IN (10,20,30)
</code>```

If you wants all dept name that has all three value (10,20 & 30) in it, you can use this following script-

```<code>SELECT * FROM Tab1
WHERE Dep IN
(
    SELECT DEP
    FROM tab1
    WHERE val IN (10,20,30)
    GROUP BY Dep
    HAVING COUNT(Val) = COUNT(DISTINCT Val)
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
create table tab1 (dep varchar2(10), val number);

begin
  insert into tab1 values ('a',10)
  insert into tab1 values ('a',20)
  insert into tab1 values ('a',30)
  insert into tab1 values ('b',10)
  insert into tab1 values ('b',20)
  insert into tab1 values ('c',10)
end;

i need DEP and value matched only with 10,20,30

output:

DEP VAL
--- ---
a   10
a   20
a   30

Body:
Try this-

SELECT * FROM tab1
WHERE dep = 'Your Desired Dept Name Here'
AND val IN (10,20,30)

For your case, if you wants to show records from Dept = A, the query will be as follow-

SELECT * FROM tab1
WHERE dep = 'a'
AND val IN (10,20,30)

If you wants all dept name that has all three value (10,20 & 30) in it, you can use this following script-

SELECT * FROM Tab1
WHERE Dep IN
(
    SELECT DEP
    FROM tab1
    WHERE val IN (10,20,30)
    GROUP BY Dep
    HAVING COUNT(Val) = COUNT(DISTINCT Val)
)


答:
Or just simply use ROCR::prediction(prediction(prob.result, test$Type))

For selecting the right package.

ContentLicense: CC BY-SA 3.0

Title: Plot a Neural Net Curve Using neuralnet and ROCR package

Body:
Here I have a classification task and I need to use neuralnet and ROCR packages. The problem is that I got the error messages when I use prediction function.

Here is my code:

#load packages
require(neuralnet)
library(ROCR)

#create data set
train<-read.table(file="train.txt",header=TRUE,sep=",")
test<- read.table(file="test.txt",header=TRUE,sep=",")

#build model and make predictions
nn.sag <- neuralnet(Type ~ Area+Perimeter+Compactness+Length+Width+Asymmetry+Groove, data = train, hidden = 5, algorithm = "sag", err.fct = "sse", linear.output = FALSE)

prob = compute(nn.sag, test[, -ncol(test)] )
prob.result <- prob$net.result

nn.pred = prediction(prob.result, test$Type)
pref <- performance(nn.pred, "tpr", "fpr")
plot(pref)

And here I got the error message for the 'prediction' function:
'$ operator is invalid for atomic vectors'

The dataset looks like (only training dataset here):

Area,Perimeter,Compactness,Length,Width,Asymmetry,Groove,Type
14.8,14.52,0.8823,5.656,3.288,3.112,5.309,1
14.79,14.52,0.8819,5.545,3.291,2.704,5.111,1
14.99,14.56,0.8883,5.57,3.377,2.958,5.175,1
19.14,16.61,0.8722,6.259,3.737,6.682,6.053,0
15.69,14.75,0.9058,5.527,3.514,1.599,5.046,1
14.11,14.26,0.8722,5.52,3.168,2.688,5.219,1
13.16,13.55,0.9009,5.138,3.201,2.461,4.783,1
16.16,15.33,0.8644,5.845,3.395,4.266,5.795,0
15.01,14.76,0.8657,5.789,3.245,1.791,5.001,1
14.11,14.1,0.8911,5.42,3.302,2.7,5,1
17.98,15.85,0.8993,5.979,3.687,2.257,5.919,0
21.18,17.21,0.8989,6.573,4.033,5.78,6.231,0
14.29,14.09,0.905,5.291,3.337,2.699,4.825,1
14.59,14.28,0.8993,5.351,3.333,4.185,4.781,1
11.42,12.86,0.8683,5.008,2.85,2.7,4.607,1
12.11,13.47,0.8392,5.159,3.032,1.502,4.519,1
15.6,15.11,0.858,5.832,3.286,2.725,5.752,0
15.38,14.66,0.899,5.477,3.465,3.6,5.439,0
18.94,16.49,0.875,6.445,3.639,5.064,6.362,0
12.36,13.19,0.8923,5.076,3.042,3.22,4.605,1
14.01,14.29,0.8625,5.609,3.158,2.217,5.132,1
17.12,15.55,0.8892,5.85,3.566,2.858,5.746,0
15.78,14.91,0.8923,5.674,3.434,5.593,5.136,1
16.19,15.16,0.8849,5.833,3.421,0.903,5.307,1
14.43,14.4,0.8751,5.585,3.272,3.975,5.144,1
13.8,14.04,0.8794,5.376,3.155,1.56,4.961,1
14.46,14.35,0.8818,5.388,3.377,2.802,5.044,1
18.59,16.05,0.9066,6.037,3.86,6.001,5.877,0
18.75,16.18,0.8999,6.111,3.869,4.188,5.992,0
15.49,14.94,0.8724,5.757,3.371,3.412,5.228,1
12.73,13.75,0.8458,5.412,2.882,3.533,5.067,1
13.5,13.85,0.8852,5.351,3.158,2.249,5.176,1
14.38,14.21,0.8951,5.386,3.312,2.462,4.956,1
14.86,14.67,0.8676,5.678,3.258,2.129,5.351,1
18.45,16.12,0.8921,6.107,3.769,2.235,5.794,0
17.32,15.91,0.8599,6.064,3.403,3.824,5.922,0
20.2,16.89,0.8894,6.285,3.864,5.173,6.187,0
20.03,16.9,0.8811,6.493,3.857,3.063,6.32,0
18.14,16.12,0.8772,6.059,3.563,3.619,6.011,0
13.99,13.83,0.9183,5.119,3.383,5.234,4.781,1
15.57,15.15,0.8527,5.92,3.231,2.64,5.879,0
16.2,15.27,0.8734,5.826,3.464,2.823,5.527,1
20.97,17.25,0.8859,6.563,3.991,4.677,6.316,0
14.16,14.4,0.8584,5.658,3.129,3.072,5.176,1
13.45,14.02,0.8604,5.516,3.065,3.531,5.097,1
15.5,14.86,0.882,5.877,3.396,4.711,5.528,1
16.77,15.62,0.8638,5.927,3.438,4.92,5.795,0
12.74,13.67,0.8564,5.395,2.956,2.504,4.869,1
14.88,14.57,0.8811,5.554,3.333,1.018,4.956,1
14.28,14.17,0.8944,5.397,3.298,6.685,5.001,1
14.34,14.37,0.8726,5.63,3.19,1.313,5.15,1
14.03,14.16,0.8796,5.438,3.201,1.717,5.001,1
19.11,16.26,0.9081,6.154,3.93,2.936,6.079,0
14.52,14.6,0.8557,5.741,3.113,1.481,5.487,1
18.43,15.97,0.9077,5.98,3.771,2.984,5.905,0
18.81,16.29,0.8906,6.272,3.693,3.237,6.053,0
13.78,14.06,0.8759,5.479,3.156,3.136,4.872,1
14.69,14.49,0.8799,5.563,3.259,3.586,5.219,1
18.85,16.17,0.9056,6.152,3.806,2.843,6.2,0
12.88,13.5,0.8879,5.139,3.119,2.352,4.607,1
12.78,13.57,0.8716,5.262,3.026,1.176,4.782,1
14.33,14.28,0.8831,5.504,3.199,3.328,5.224,1
19.46,16.5,0.8985,6.113,3.892,4.308,6.009,0
19.38,16.72,0.8716,6.303,3.791,3.678,5.965,0
15.26,14.85,0.8696,5.714,3.242,4.543,5.314,1
20.24,16.91,0.8897,6.315,3.962,5.901,6.188,0
19.94,16.92,0.8752,6.675,3.763,3.252,6.55,0
20.71,17.23,0.8763,6.579,3.814,4.451,6.451,0
16.17,15.38,0.8588,5.762,3.387,4.286,5.703,0
13.02,13.76,0.8641,5.395,3.026,3.373,4.825,1
16.53,15.34,0.8823,5.875,3.467,5.532,5.88,0
13.89,14.02,0.888,5.439,3.199,3.986,4.738,1
18.98,16.57,0.8687,6.449,3.552,2.144,6.453,0
17.08,15.38,0.9079,5.832,3.683,2.956,5.484,1
15.03,14.77,0.8658,5.702,3.212,1.933,5.439,1
16.14,14.99,0.9034,5.658,3.562,1.355,5.175,1
18.65,16.41,0.8698,6.285,3.594,4.391,6.102,0
20.1,16.99,0.8746,6.581,3.785,1.955,6.449,0
17.99,15.86,0.8992,5.89,3.694,2.068,5.837,0
15.88,14.9,0.8988,5.618,3.507,0.7651,5.091,1
13.22,13.84,0.868,5.395,3.07,4.157,5.088,1
18.3,15.89,0.9108,5.979,3.755,2.837,5.962,0
19.51,16.71,0.878,6.366,3.801,2.962,6.185,0


问:
Error when running Simpify (Python's Sympy)
I use Python's Sympy module.

I want to print out the mathml code using sympy.printing.mathml.

I am trying to convert a string to a formula using sympify, but I get an error.

test001.py

```<code>import sys
sys.path.append('/home/vagrant/.local/lib/python3.4/site-packages')
from sympy import *
from sympy.printing.mathml import mathml

print(mathml(sympify("y=4*x**3+3*x**2+2*x+1"),printer='presentation'))
print(mathml(sympify("y=a*x**3+b*x**2+c*x+d"),printer='presentation'))
</code>```

When I run test001.py, I get the following error.

```<code>$ python test001.py
Traceback (most recent call last):
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 368, in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 965, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 878, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Symbol ('y' )=Integer (4 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )+Integer (2 )*Symbol ('x' )+Integer (1 )
                 ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test001.py", line 6, in <module>
    print(mathml(sympify("y=4*x**3+3*x**2+2*x+1"),printer='presentation'))
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 370, in sympify
    raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'y=4*x**3+3*x**2+2*x+1'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 368, in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 965, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 878, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Symbol ('y' )=Integer (4 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )+Integer (2 )*Symbol ('x' )+Integer (1 )
                 ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test001.py", line 6, in <module>
    print(mathml(sympify("y=4*x**3+3*x**2+2*x+1"),printer='presentation'))
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 370, in sympify
    raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'y=4*x**3+3*x**2+2*x+1'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
</code>```

I want to output something like the following as an execution result.

What should I do?

```<code><mi>y</mi><mo>=</mo><mn>4</mn><mo><!--FUNCTION APPLICATION--></mo><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mn>3</mn><mo><!--FUNCTION APPLICATION--></mo><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>2</mn><mo><!--FUNCTION APPLICATION--></mo><mi>x</mi><mo>+</mo><mn>1</mn>
</code>```

```<code><mi>y</mi><mo>=</mo><mi>a</mi><mo><!--FUNCTION APPLICATION--></mo><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mi>b</mi><mo><!--FUNCTION APPLICATION--></mo><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>c</mi><mo><!--FUNCTION APPLICATION--></mo><mi>x</mi><mo>+</mo><mi>d</mi>
</code>```

I am using sympy version 1.4.
The Python version uses 3.6.3.

答:
Notice that the error has an arrow pointing at the equal sign

```<code>Symbol ('y' )=Integer (4 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )+Integer (2 )*Symbol ('x' )+Integer (1 )
             ^
SyntaxError: invalid syntax
</code>```

sympify operates on expressions, but not equations. So instead, you could split the equation string at the equal sign,
and apply sympify to the left-hand and right-hand sides separately:

```<code>map(sym.sympify, "y=4*x**3+3*x**2+2*x+1".split('='))
</code>```

Then form a sympy Equation object out of the two expressions:

```<code>>>> sym.Eq(*map(sym.sympify, "y=4*x**3+3*x**2+2*x+1".split('=')))
Eq(y, 4*x**3 + 3*x**2 + 2*x + 1)
</code>```

You can then apply mathml to this SymPy Equality object.

```<code>import sys
# sys.path.append('/home/vagrant/.local/lib/python3.4/site-packages')
import sympy as sym
from sympy.printing.mathml import mathml

print(mathml(sym.Eq(*map(sym.sympify, "y=4*x**3+3*x**2+2*x+1".split('='))),printer='presentation'))
print(mathml(sym.Eq(*map(sym.sympify, "y=a*x**3+b*x**2+c*x+d".split('='))),printer='presentation'))
</code>```

yields

```<code><mrow><mi>y</mi><mo>=</mo><mrow><mrow><mn>4</mn><mo></mo><msup><mi>x</mi><mn>3</mn></msup></mrow><mo>+</mo><mrow><mn>3</mn><mo></mo><msup><mi>x</mi><mn>2</mn></msup></mrow><mo>+</mo><mrow><mn>2</mn><mo></mo><mi>x</mi></mrow><mo>+</mo><mn>1</mn></mrow></mrow>
<mrow><mi>y</mi><mo>=</mo><mrow><mrow><mi>a</mi><mo></mo><msup><mi>x</mi><mn>3</mn></msup></mrow><mo>+</mo><mrow><mi>b</mi><mo></mo><msup><mi>x</mi><mn>2</mn></msup></mrow><mo>+</mo><mrow><mi>c</mi><mo></mo><mi>x</mi></mrow><mo>+</mo><mi>d</mi></mrow></mrow>
</code>```

Body:
I use Python's Sympy module.

I want to print out the mathml code using sympy.printing.mathml.

I am trying to convert a string to a formula using sympify, but I get an error.

test001.py

import sys
sys.path.append('/home/vagrant/.local/lib/python3.4/site-packages')
from sympy import *
from sympy.printing.mathml import mathml

print(mathml(sympify("y=4*x**3+3*x**2+2*x+1"),printer='presentation'))
print(mathml(sympify("y=a*x**3+b*x**2+c*x+d"),printer='presentation'))

When I run test001.py, I get the following error.

$ python test001.py
Traceback (most recent call last):
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 368, in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 965, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 878, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Symbol ('y' )=Integer (4 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )+Integer (2 )*Symbol ('x' )+Integer (1 )
                 ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test001.py", line 6, in <module>
    print(mathml(sympify("y=4*x**3+3*x**2+2*x+1"),printer='presentation'))
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 370, in sympify
    raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'y=4*x**3+3*x**2+2*x+1'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 368, in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 965, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/parsing/sympy_parser.py", line 878, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Symbol ('y' )=Integer (4 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )+Integer (2 )*Symbol ('x' )+Integer (1 )
                 ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test001.py", line 6, in <module>
    print(mathml(sympify("y=4*x**3+3*x**2+2*x+1"),printer='presentation'))
  File "/home/vagrant/.local/lib/python3.4/site-packages/sympy/core/sympify.py", line 370, in sympify
    raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'y=4*x**3+3*x**2+2*x+1'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

I want to output something like the following as an execution result.

What should I do?

<mi>y</mi><mo>=</mo><mn>4</mn><mo></mo><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mn>3</mn><mo></mo><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>2</mn><mo></mo><mi>x</mi><mo>+</mo><mn>1</mn>

<mi>y</mi><mo>=</mo><mi>a</mi><mo></mo><msup><mi>x</mi><mn>3</mn></msup><mo>+</mo><mi>b</mi><mo></mo><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>c</mi><mo></mo><mi>x</mi><mo>+</mo><mi>d</mi>

I am using sympy version 1.4.
The Python version uses 3.6.3.

Body:
Notice that the error has an arrow pointing at the equal sign

Symbol ('y' )=Integer (4 )*Symbol ('x' )**Integer (3 )+Integer (3 )*Symbol ('x' )**Integer (2 )+Integer (2 )*Symbol ('x' )+Integer (1 )
             ^
SyntaxError: invalid syntax

sympify operates on expressions, but not equations. So instead, you could split the equation string at the equal sign,
and apply sympify to the left-hand and right-hand sides separately:

map(sym.sympify, "y=4*x**3+3*x**2+2*x+1".split('='))

Then form a sympy Equation object out of the two expressions:

>>> sym.Eq(*map(sym.sympify, "y=4*x**3+3*x**2+2*x+1".split('=')))
Eq(y, 4*x**3 + 3*x**2 + 2*x + 1)

You can then apply mathml to this SymPy Equality object.

import sys
# sys.path.append('/home/vagrant/.local/lib/python3.4/site-packages')
import sympy as sym
from sympy.printing.mathml import mathml

print(mathml(sym.Eq(*map(sym.sympify, "y=4*x**3+3*x**2+2*x+1".split('='))),printer='presentation'))
print(mathml(sym.Eq(*map(sym.sympify, "y=a*x**3+b*x**2+c*x+d".split('='))),printer='presentation'))

yields

<mrow><mi>y</mi><mo>=</mo><mrow><mrow><mn>4</mn><mo>&InvisibleTimes;</mo><msup><mi>x</mi><mn>3</mn></msup></mrow><mo>+</mo><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msup><mi>x</mi><mn>2</mn></msup></mrow><mo>+</mo><mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow><mo>+</mo><mn>1</mn></mrow></mrow>
<mrow><mi>y</mi><mo>=</mo><mrow><mrow><mi>a</mi><mo>&InvisibleTimes;</mo><msup><mi>x</mi><mn>3</mn></msup></mrow><mo>+</mo><mrow><mi>b</mi><mo>&InvisibleTimes;</mo><msup><mi>x</mi><mn>2</mn></msup></mrow><mo>+</mo><mrow><mi>c</mi><mo>&InvisibleTimes;</mo><mi>x</mi></mrow><mo>+</mo><mi>d</mi></mrow></mrow>


问:
UIApplication not launching to make phone call
I have this code:

```<code>NSString *telURL = [NSString stringWithFormat:@"tel:1-%@",((UIButton*) sender).titleLabel.text];
telURL = [telURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURL]];
</code>```

But it does not launch the dialer application to make a phone call.

I've checked the string telURL and its contents are : "tel:[REDACTED]", which to my understanding is what it needs to be.

Any ideas?

EDIT:
In the event that it matters I've just been running this on the simulator. I won't have a physical device for a few days. (And from the answers  below apparently it does matter)

答:
First, just checking you are running on hardware that includes a phone (not iPod touch) and not the simulator right? The simulator won't let you test this.

An easy way to get rid of whitespace in your phone number is:

```<code>NSString *phoneURLString = [[self.phoneNumber componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];
</code>```

Also you should be programmatically checking if the device (or simulator) can handle the url. Simple way to check that is using canOpenURL:

```<code>[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:yourPhoneNumberStringHere]]
</code>```

Body:
I have this code:

NSString *telURL = [NSString stringWithFormat:@"tel:1-%@",((UIButton*) sender).titleLabel.text];
telURL = [telURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURL]];

But it does not launch the dialer application to make a phone call.

I've checked the string telURL and its contents are : "tel:[REDACTED]", which to my understanding is what it needs to be.

Any ideas?

EDIT:
In the event that it matters I've just been running this on the simulator. I won't have a physical device for a few days. (And from the answers  below apparently it does matter)

Body:
First, just checking you are running on hardware that includes a phone (not iPod touch) and not the simulator right? The simulator won't let you test this.

An easy way to get rid of whitespace in your phone number is:

NSString *phoneURLString = [[self.phoneNumber componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];

Also you should be programmatically checking if the device (or simulator) can handle the url. Simple way to check that is using canOpenURL:

[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:yourPhoneNumberStringHere]]


问:
Trying to convert string to datetime using ParseExact
I am trying to convert a string like this '5/29/2019 8:46:47 PM' to a datetime for use as a PowerShell object but I am getting an error

I am trying to use the [datetime]::ParseExact method

```<code>$Date = "5/29/2019 8:46:47 PM"

[datetime]::ParseExact($Date,'MM dd yyyy HH:mm:ss', $null)
</code>```

Instead of getting a datetime object, I just get this error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Any help will be greatly appreciated.

答:
```<code>PS /Users/js> [DateTime]'5/29/2019 8:46:47 PM'

Wednesday, May 29, 2019 8:46:47 PM

PS /Users/js> ([DateTime]'5/29/2019 8:46:47 PM').gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DateTime                                 System.ValueType
</code>```

Body:
I am trying to convert a string like this '5/29/2019 8:46:47 PM' to a datetime for use as a PowerShell object but I am getting an error

I am trying to use the [datetime]::ParseExact method

$Date = "5/29/2019 8:46:47 PM"

[datetime]::ParseExact($Date,'MM dd yyyy HH:mm:ss', $null)

Instead of getting a datetime object, I just get this error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Any help will be greatly appreciated.


问:
Selecting thousands separator character with RegEx
I need to change the decimal separator in a given string that has numbers in it.

What RegEx code can ONLY select the thousands separator character in the string?

It need to only select, when there is number around it. For example only when 123,456 I need to select and replace ,

I'm converting English numbers into Persian (e.g: Hello 123 becomes Hello ۱۲۳). Now I need to replace the decimal separator with Persian version too. But I don't know how I can select it with regex. e.g. Hello 121,534 most become Hello ۱۲۱/۵۳۴

The character that needs to be replaced is , with /

答:
You can write a regex to capture numbers with thousand separator, and then aggregate the two numeric parts with the separator you want :</p>

```<code>$text = "Hello, world, 121,534" ;
$pattern = "/([0-9]{1,3}),([0-9]{3})/" ;
$new_text = preg_replace($pattern, "$1X$2", $text); // replace comma per 'X', keep other groups intact.

echo $new_text ; // Hello, world, 121X534
</code>```

Body:
You can write a regex to capture numbers with thousand separator, and then aggregate the two numeric parts with the separator you want :

$text = "Hello, world, 121,534" ;
$pattern = "/([0-9]{1,3}),([0-9]{3})/" ;
$new_text = preg_replace($pattern, "$1X$2", $text); // replace comma per 'X', keep other groups intact.

echo $new_text ; // Hello, world, 121X534


问:
Unable to find image 'acbuild:latest' locally
I'm attempting to compile Stygian's repack of AzerothCore as I want to add the Auction House Bot module. I have installed and set up Docker, cloned the repo and installed the module and patch, but I am receiving an error while trying to run the "./bin/acore-docker-build" command as outlined in the wiki.

I am running Windows 10 Pro

I have run the following commands:

```<code>./bin/acore-docker-generate-etc
</code>```

Which appeared to work, and

```<code>./bin/acore-docker-build
</code>```

Which produced the following error:

scott@DESKTOP-BGVSVR4 MINGW64 ~/Desktop/Stygian/StygianCore/Source
  (master) $ ./bin/acore-docker-build unable to prepare context: unable
  to evaluate symlinks in Dockerfile path: GetFileAttributesEx
  C:\Users\scott\Desktop\Stygian\StygianCore\Source\docker\build: The
  system cannot find the file specified. Unable to find image
  'acbuild:latest' locally C:\Program
  Files\Docker\Docker\Resources\bin\docker.exe: Error response from
  daemon: pull access denied for acbuild, repository does not exist or
  may require 'docker login'. See 'C:\Program
  Files\Docker\Docker\Resources\bin\docker.exe run --help'.

答:
Repacks are not supported by AC. You are probably using an older version of AC and not the latest.

You are getting the error:

Unable to find image 'acbuild:latest'

but in the latest version of AC, such image is baked in the same script that you're trying to run (./bin/acore-docker-build) and its Dockerfile is located in docker/build/Dockerfile.

Try to clone AC from the official repository and it will work.

Body:
I'm attempting to compile Stygian's repack of AzerothCore as I want to add the Auction House Bot module. I have installed and set up Docker, cloned the repo and installed the module and patch, but I am receiving an error while trying to run the "./bin/acore-docker-build" command as outlined in the wiki.

I am running Windows 10 Pro

I have run the following commands:

./bin/acore-docker-generate-etc

Which appeared to work, and

./bin/acore-docker-build

Which produced the following error:

scott@DESKTOP-BGVSVR4 MINGW64 ~/Desktop/Stygian/StygianCore/Source
  (master) $ ./bin/acore-docker-build unable to prepare context: unable
  to evaluate symlinks in Dockerfile path: GetFileAttributesEx
  C:\Users\scott\Desktop\Stygian\StygianCore\Source\docker\build: The
  system cannot find the file specified. Unable to find image
  'acbuild:latest' locally C:\Program
  Files\Docker\Docker\Resources\bin\docker.exe: Error response from
  daemon: pull access denied for acbuild, repository does not exist or
  may require 'docker login'. See 'C:\Program
  Files\Docker\Docker\Resources\bin\docker.exe run --help'.


问:
Counter showing double data when fetch it from fread function
I create a counter function in PHP means if someone access or visit a web page so it will show count in file.txt(it contain the number of counts) and on the web page also. but now I want to fetch counts form file.txt and show it on another page. I tried PHP fread operation but it showing counting in double. suppose if the real number of count is 10 then after fetch it from fread it showing 1010.

I used this code to fetch count from file.txt for showing it to another page.

```<code><?php
$file = fopen("counter.txt", "r") or die("Unable to open file !");
echo fgets($file);
//fread($file,filesize("counter.txt"));
fclose($file);
?>
</code>```

答:
Counter TEXT are very basics. For writing to counter.txt file your code seems Ok:

```<code><?php
$handle = fopen("counter.txt", "r");
if (!$handle) {
  echo "could not open the file";
} else {
  $counter = (int)fread($handle,20);
  fclose($handle);
  $counter++;
  $handle = fopen("counter.txt", "w");
  fwrite($handle, $counter);
  fclose($handle);
}
?>
</code>```

You can save as write_counts.php and invoke into your php files at begin using:

```<code><?php include("write_counts.php"); ?>
</code>```

for reading your counter.txt instead you can use:

```<code><?php $counter = file_get_contents("counter.txt"); echo ($counter == 1) ? "Visitor: $counter" : "Visitors: $counter"; ?>
</code>```

and you can save as read_counts.php and invoke into your php files where you like... using:

```<code><?php include("read_counts.php"); ?>
</code>```

I hope this helps.

Body:
I create a counter function in PHP means if someone access or visit a web page so it will show count in file.txt(it contain the number of counts) and on the web page also. but now I want to fetch counts form file.txt and show it on another page. I tried PHP fread operation but it showing counting in double. suppose if the real number of count is 10 then after fetch it from fread it showing 1010.

I used this code to fetch count from file.txt for showing it to another page.

<?php
$file = fopen("counter.txt", "r") or die("Unable to open file !");
echo fgets($file);
//fread($file,filesize("counter.txt"));
fclose($file);
?>

Body:
Counter TEXT are very basics. For writing to counter.txt file your code seems Ok:

<?php
$handle = fopen("counter.txt", "r");
if (!$handle) {
  echo "could not open the file";
} else {
  $counter = (int)fread($handle,20);
  fclose($handle);
  $counter++;
  $handle = fopen("counter.txt", "w");
  fwrite($handle, $counter);
  fclose($handle);
}
?>

You can save as write_counts.php and invoke into your php files at begin using:

<?php include("write_counts.php"); ?>

for reading your counter.txt instead you can use:

<?php $counter = file_get_contents("counter.txt"); echo ($counter == 1) ? "Visitor: $counter" : "Visitors: $counter"; ?>

and you can save as read_counts.php and invoke into your php files where you like... using:

<?php include("read_counts.php"); ?>

I hope this helps.


问:
Is cursor over element (on page load)?
I have a .hover() action assigned to an element to hide/show something depending on the cursor being over it. The problem I am running into is that when the page loads and the cursor is OVER the element it doesn't register as being over because its not firing the mouseenter event.

Is there a another way to tell if the cursor is over a desired element?

答:
If you hide the element(s) until the page is done loading and then show them all at once, will your mouseover event now fire?

```<code><div id='allmyelementsinhere' style='display:none'>
</code>```

then use javascript to remove the display:none on page load.

I'm thinking that your mouseevent will fire as soon as you display the elements.

Title: Is cursor over element (on page load)?

Body:
If you hide the element(s) until the page is done loading and then show them all at once, will your mouseover event now fire?

<div id='allmyelementsinhere' style='display:none'>

then use javascript to remove the display:none on page load.

I'm thinking that your mouseevent will fire as soon as you display the elements.


答:
Use a regular expression with lookarounds.

```<code>$new_string = preg_replace('/(?<=\d),(?=\d)/', '/', $string);
</code>```

DEMO

(?<=\d) means there has to be a digit before the comma, (?=\d) means there has to be a digit after it. But since these are lookarounds, they're not included in the match, so they don't get replaced.

Title: Selecting thousands separator character with RegEx

Body:
I need to change the decimal separator in a given string that has numbers in it.

What RegEx code can ONLY select the thousands separator character in the string?

It need to only select, when there is number around it. For example only when 123,456 I need to select and replace ,

I'm converting English numbers into Persian (e.g: Hello 123 becomes Hello ۱۲۳). Now I need to replace the decimal separator with Persian version too. But I don't know how I can select it with regex. e.g. Hello 121,534 most become Hello ۱۲۱/۵۳۴

The character that needs to be replaced is , with /

Body:
Use a regular expression with lookarounds.

$new_string = preg_replace('/(?<=\d),(?=\d)/', '/', $string);

DEMO

(?<=\d) means there has to be a digit before the comma, (?=\d) means there has to be a digit after it. But since these are lookarounds, they're not included in the match, so they don't get replaced.


问:
How can I include the Telegram login widget in an Angular app?
I want to include the Telegram login widget in my Angular application. For this, you have to include the following script:

```

Embedding scripts in Angular templates is not allowed, it will just be removed. (However, it is possible to include a script tag via this hack.)

Is there a non-hacky way of including this widget?

答:
Not rendering script tags in template code is indeed a design choice from Angular team.

The way to do it is thus:

Add your scripts to index.html - only relevant if it makes sense to load the script globally.

Or Add your script programmatically. The post you refer to can be a solution, but brings in additional complication because it takes the input data from template code. A shorter solution is given here, when you're happy with inputing the parameters from the code-side (and the full issue is instructive too): Github issue #4903. Warning though: adding to the head is not suitable unless you remove it in OnDestroy. Prefer adding in the right DOM element of your component.

Body:
I want to include the Telegram login widget in my Angular application. For this, you have to include the following script:

Embedding scripts in Angular templates is not allowed, it will just be removed. (However, it is possible to include a script tag via this hack.)

Is there a non-hacky way of including this widget?


问:
Why do Berkeley sockets require byte swapping?
I understand that on the wire, most integers are in big endian format.

But why is it the burden of the application to do the byte swapping in structures like sockaddr_in and not the kernels, where all the low level work actually happens? It would make more sense if the userspace API was more platform agnostic and should not deal with this.

Why was the Berkeley socket API designed like this?

答:
The only technical advantage I can think of is that it allows the application to do the conversion once and cache it.

Then, for myriad calls to say sendto() for UDP, or what have you, the re-ordered-if-necessary address is supplied to the OS which can copy it as-is directly into outgoing network packets.

The alternative of doing it in the kernel would require every call to sendto() to take what the app knows as the same address over and over, and reconvert it every time.

Since sendto() benefits from this, they have the rest of the API work the same way.


问:
Most 'functional' way to sum pairs of elements from a vector using C++17 or later?
I'd like some suggestions for the most terse and 'functional' way to gather pairs of successive elements from a vector (1st and 2nd, 3rd and 4th, etc.) using modern C++.  Assume the vector is of arbitrary but even length.  For the examples I'm pulling together, I'm summing the elements of each pair but that's not the main problem.  I should add I'll use STL only, no Boost.

In Python I can zip them into 2-tuples via an iterator with

s = range(1,11)
print([(x + y) for x,y in zip(*[iter(s)] * 2)])
```

<p>In Perl 5 I can peel off pairs with</p>

<pre class="lang-perl prettyprint-override"><code>use List::Util qw/pairs sum/;
use feature 'say';
@s = 1 .. 10;
say sum @$_ foreach (pairs @s);
</code>```

In Perl 6 I can shove them two at a time into a block with

my @s = 1 .. 10;
for @s -> $x, $y { say $x + $y; }
```

<p>and in R I can wrap the vector into a 2-column array and sum the rows with</p>

<pre class="lang-r prettyprint-override"><code>s <- 1:10
print(apply(matrix(s, ncol=2, byrow=TRUE), 1, sum))
</code>```

I am not fluent in C++ and my solution uses for(;;).  That feels too much like C.

#include <iostream>
#include <vector>
#include <numeric>  // std::iota

int main() {
    std::vector<int> s(10);
    std::iota(s.begin(), s.end(), 1);
    for (auto p = s.cbegin(); p != s.cend(); p += 2)
        std::cout << (*p + *(p + 1)) << std::endl;
}
```

<p>The output of course should be some variant of </p>

```3
7
11
15
19
```

答:
Without using range-v3 I was able to do this with either a function or a lambda template. I'll show the lambda version here.

```<code>#include <iostream>
#include <string>
#include <vector>

template<typename T>
auto lambda = [](const std::vector<T>& values, std::vector<T>& results) {
    std::vector<T> temp1, temp2;

    for ( std::size_t i = 0; i < values.size(); i++ ) {
        if ( i & 1 ) temp2.push_back(values[i]); // odd index
        else temp1.push_back(values[i]); // even index
    }

    for ( std::size_t i = 0; i < values.size() / 2; i++ )
        results.push_back(temp[i] + temp[2]);
};

int main() {
    std::vector<int> values{ 1,2,3,4,5,6 };
    for (auto i : values)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<int> results;
    lambda<int>(values, results);
    for (auto i : results)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<float> values2{ 1.1f, 2.2f, 3.3f, 4.4f };
    for (auto f : values2)
        std::cout << f << " ";
    std::cout << '\n';

    std::vector<float> results2;
    lambda<float>(values2, results2);
    for (auto f : results2)
        std::cout << f << " ";
    std::cout << '\n';

    std::vector<char> values3{ 'a', 'd' };
    for (auto c : values3)
        std::cout << c << " ";
    std::cout << '\n';

    std::vector<char> results3;
    lambda<char>(values3, results3);
    for (auto c : results3)
        std::cout << c << " ";
    std::cout << '\n';

    std::vector<std::string> values4{ "Hello", " ", "World", "!" };
    for (auto s : values4)
        std::cout << s;
    std::cout << '\n';

    std::vector<std::string> results4;
    lambda<std::string>(values4, results4);
    for (auto s : results4)
        std::cout << s;
    std::cout << '\n';

   return EXIT_SUCCESS;
}
</code>```

Output

```<code>1 2 3 4 5 6
3 7 11
1.1 2.2 3.3 4.4
3.3 7.7
a d
┼
Hello World!
Hello World!
</code>```

Body:
I'd like some suggestions for the most terse and 'functional' way to gather pairs of successive elements from a vector (1st and 2nd, 3rd and 4th, etc.) using modern C++.  Assume the vector is of arbitrary but even length.  For the examples I'm pulling together, I'm summing the elements of each pair but that's not the main problem.  I should add I'll use STL only, no Boost.

In Python I can zip them into 2-tuples via an iterator with

s = range(1,11)
print([(x + y) for x,y in zip(*[iter(s)] * 2)])

In Perl 5 I can peel off pairs with

use List::Util qw/pairs sum/;
use feature 'say';
@s = 1 .. 10;
say sum @$_ foreach (pairs @s);

In Perl 6 I can shove them two at a time into a block with

my @s = 1 .. 10;
for @s -> $x, $y { say $x + $y; }

and in R I can wrap the vector into a 2-column array and sum the rows with

s <- 1:10
print(apply(matrix(s, ncol=2, byrow=TRUE), 1, sum))

I am not fluent in C++ and my solution uses for(;;).  That feels too much like C.

#include <iostream>
#include <vector>
#include <numeric>  // std::iota

int main() {
    std::vector<int> s(10);
    std::iota(s.begin(), s.end(), 1);
    for (auto p = s.cbegin(); p != s.cend(); p += 2)
        std::cout << (*p + *(p + 1)) << std::endl;
}

The output of course should be some variant of

3
7
11
15
19

Body:
Without using range-v3 I was able to do this with either a function or a lambda template. I'll show the lambda version here.

#include <iostream>
#include <string>
#include <vector>

template<typename T>
auto lambda = [](const std::vector<T>& values, std::vector<T>& results) {
    std::vector<T> temp1, temp2;

    for ( std::size_t i = 0; i < values.size(); i++ ) {
        if ( i & 1 ) temp2.push_back(values[i]); // odd index
        else temp1.push_back(values[i]); // even index
    }

    for ( std::size_t i = 0; i < values.size() / 2; i++ )
        results.push_back(temp[i] + temp[2]);
};

int main() {
    std::vector<int> values{ 1,2,3,4,5,6 };
    for (auto i : values)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<int> results;
    lambda<int>(values, results);
    for (auto i : results)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<float> values2{ 1.1f, 2.2f, 3.3f, 4.4f };
    for (auto f : values2)
        std::cout << f << " ";
    std::cout << '\n';

    std::vector<float> results2;
    lambda<float>(values2, results2);
    for (auto f : results2)
        std::cout << f << " ";
    std::cout << '\n';

    std::vector<char> values3{ 'a', 'd' };
    for (auto c : values3)
        std::cout << c << " ";
    std::cout << '\n';

    std::vector<char> results3;
    lambda<char>(values3, results3);
    for (auto c : results3)
        std::cout << c << " ";
    std::cout << '\n';

    std::vector<std::string> values4{ "Hello", " ", "World", "!" };
    for (auto s : values4)
        std::cout << s;
    std::cout << '\n';

    std::vector<std::string> results4;
    lambda<std::string>(values4, results4);
    for (auto s : results4)
        std::cout << s;
    std::cout << '\n';

   return EXIT_SUCCESS;
}

Output

1 2 3 4 5 6
3 7 11
1.1 2.2 3.3 4.4
3.3 7.7
a d
┼
Hello World!
Hello World!


答:
Use aggregation:

```<code>SELECT dep
FROM tab1
WHERE val IN (10, 20, 30)
GROUP BY dep
HAVING COUNT(*) = 3;
</code>```

This assumes no duplicate rows.

If you want those three and no others, then you can use conditional aggregation.  Here is one simple method:

```<code>SELECT dep
FROM tab1
GROUP BY dep
HAVING LISTAGG(val, ',') WITHIN GROUP (ORDER BY val) = '10,20,30';
</code>```

Title: Get record from particular department which is satisfying the condition?

Body:
create table tab1 (dep varchar2(10), val number);

begin
  insert into tab1 values ('a',10)
  insert into tab1 values ('a',20)
  insert into tab1 values ('a',30)
  insert into tab1 values ('b',10)
  insert into tab1 values ('b',20)
  insert into tab1 values ('c',10)
end;

i need DEP and value matched only with 10,20,30

output:

DEP VAL
--- ---
a   10
a   20
a   30

Body:
Use aggregation:

SELECT dep
FROM tab1
WHERE val IN (10, 20, 30)
GROUP BY dep
HAVING COUNT(*) = 3;

This assumes no duplicate rows.

If you want those three and no others, then you can use conditional aggregation.  Here is one simple method:

SELECT dep
FROM tab1
GROUP BY dep
HAVING LISTAGG(val, ',') WITHIN GROUP (ORDER BY val) = '10,20,30';


问:
Fetching Property in Angular 7
I want to use the property of the input element when form is submitted.
I read the concept of Template reference variable which helps in achieving this case in Angular.

When i assign 'id' attribute of input element with a value and later when i tried fetching, it throws an error.
It allows only template reference variable to extract the property.

Why not we access the property of the input element by directly invoking its ID attribute

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  // templateUrl: './test.component.html',
  template : `
  <input type="text" id = "{{idOne}}"  #idTwo/>
  <button type="text" (click) =
handleClickEvent(id.value)>Submit</button>

<button type="text" (click) = handleClickEvent(idTwo.value)>Submit
Again</button>`,
  styles: [`p {color : red}`]
})
export class TestComponent implements OnInit {

  handleClickEvent = (value : string) =>{
    console.log(value);
  }

  public idOne = "testID";
  constructor() { }

  ngOnInit() {
  }

}
</code>```

When i submit 1st button (which invokes ID directly), it throws error saying

cannot read value of undefined.

When i submit 2nd button, it prints correct value that i inputted.

So my question is

Is template reference variable the only way to fetch the property of the HTML element ?

Can you not fetch the property in a traditional way (directly calling id property) ?

答:
Using JavaScript on DOM elements directly is not generally something that is necessary in Angular.

You need to adjust your code as follows:

In the component class, declare your properties for binding on the template

Create a click handler for the button

Component

```<code>export class TestComponent {

  idVal = 'testID';

  submit(): void {
    // Not sure what needs to happen here.
  }

  submitAgain(): void {
    // Not sure what needs to happen here.
  }

  constructor() { }
}
</code>```

Then, in your template, bind the input field to the the property, and the click handler to the button.

Template

```<code><input type="text" [(ngModel)]="idVal" />

<button type="text" (click)="submit()">Submit</button>
<button type="text" (click)="submitAgain()">Submit Again</button>
</code>```

Rules

Don't use DOM to store/retrieve values from form fields. That is what ngModel is for.

Don't pass arguments in to event handler methods. The data needed for event handlers should be contained as property values on the component.

Title: Fetching Property in Angular 7

Body:
I want to use the property of the input element when form is submitted.
I read the concept of Template reference variable which helps in achieving this case in Angular.

When i assign 'id' attribute of input element with a value and later when i tried fetching, it throws an error.
It allows only template reference variable to extract the property.

Why not we access the property of the input element by directly invoking its ID attribute

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  // templateUrl: './test.component.html',
  template : `
  <input type="text" id = "{{idOne}}"  #idTwo/>
  <button type="text" (click) =
handleClickEvent(id.value)>Submit</button>

<button type="text" (click) = handleClickEvent(idTwo.value)>Submit
Again</button>`,
  styles: [`p {color : red}`]
})
export class TestComponent implements OnInit {

  handleClickEvent = (value : string) =>{
    console.log(value);
  }

  public idOne = "testID";
  constructor() { }

  ngOnInit() {
  }

}

When i submit 1st button (which invokes ID directly), it throws error saying

cannot read value of undefined.

When i submit 2nd button, it prints correct value that i inputted.

So my question is

Is template reference variable the only way to fetch the property of the HTML element ?

Can you not fetch the property in a traditional way (directly calling id property) ?

Body:
Using JavaScript on DOM elements directly is not generally something that is necessary in Angular.

You need to adjust your code as follows:

In the component class, declare your properties for binding on the template

Create a click handler for the button

Component

export class TestComponent {

  idVal = 'testID';

  submit(): void {
    // Not sure what needs to happen here.
  }

  submitAgain(): void {
    // Not sure what needs to happen here.
  }

  constructor() { }
}

Then, in your template, bind the input field to the the property, and the click handler to the button.

Template

<input type="text" [(ngModel)]="idVal" />

<button type="text" (click)="submit()">Submit</button>
<button type="text" (click)="submitAgain()">Submit Again</button>

Rules

Don't use DOM to store/retrieve values from form fields. That is what ngModel is for.

Don't pass arguments in to event handler methods. The data needed for event handlers should be contained as property values on the component.


问:
Having difficulty sorting this array
I want to sort by a string that appears in different place in each array object.

I have an nsarray that contains objects like this:

```<code>Jones John 05-12-1993 Diabetes *05-13-2019 **R ***No Data ****68xxx

Smith John 05-12-2019 Hypertension *05-12-2019 **R ***05-12-2019 ****117xx

Smithers John 05-12-1947 COPD *05-13-2019 **R ***05-13-2019 ****89xxx

Wilson John 05-13-2019 Atrial Fibrillation *05-13-2019 **R ***05-16-2019 ****90xxx

Davis Joe 05-23-1905 Hypertension *05-25-2019 **R ***05-23-2019 ****42xxx
</code>```

I need to sort the array by the date after the single asterisk. I cannot figure out how to do this. I've tried a number of example but it doesn't work.  Any suggestions? Thanks.

I have tried this and of course it only sorts by the beginning of each object

```<code>[self.nameAndDOB sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; // 1-5 sort patient roster by last name
</code>```

答:
localizedCaseInsensitiveCompare: is a method that compares strings. It obviously doesn't compare them the way you want. Your challenge, should you accept it, is to write a method that compares strings in the way you want them to be compared and pass the selector of the method to sortUsingSelector:

I usually use one of the block-based sorting methods; easier to write and more flexible.

Title: Having difficulty sorting this array

Body:
I want to sort by a string that appears in different place in each array object.

I have an nsarray that contains objects like this:

Jones John 05-12-1993 Diabetes *05-13-2019 **R ***No Data ****68xxx

Smith John 05-12-2019 Hypertension *05-12-2019 **R ***05-12-2019 ****117xx

Smithers John 05-12-1947 COPD *05-13-2019 **R ***05-13-2019 ****89xxx

Wilson John 05-13-2019 Atrial Fibrillation *05-13-2019 **R ***05-16-2019 ****90xxx

Davis Joe 05-23-1905 Hypertension *05-25-2019 **R ***05-23-2019 ****42xxx

I need to sort the array by the date after the single asterisk. I cannot figure out how to do this. I've tried a number of example but it doesn't work.  Any suggestions? Thanks.

I have tried this and of course it only sorts by the beginning of each object

[self.nameAndDOB sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; // 1-5 sort patient roster by last name


问:
How to host a Happstack website?
I've built a website using Happstack, but I have no experience in hosting. Everything I found online was either outdated or too complex for me. Is there an easy way, or tutorial I can follow to publish my Happstack website?

Thanks

答: Thanks for everyone who answered. I ended up using a docker image alongside heroku for deployment. If you want to see how the docker file looks check https://github.com/hpbl/haskellkoans</p>

Title: How to host a Happstack website?


问:
How to convert function returning [] to Traversable?
I have the following module which implements a directory walk:

module Walk
  ( walk
  ) where

import           Control.Monad
import           Control.Monad.IO.Class
import           Data.List
import           System.Directory
import           System.FilePath

walk :: (MonadIO m) => FilePath -> m [(FilePath, [FilePath])]
walk root = do
  entries <- liftIO $ listDirectory root
  (files, dirs) <- partition snd <$> liftM2 (<$>) zip (mapM (liftIO . doesFileExist . (root </>))) entries
  ((root, map fst files) :) . concat <$> mapM (walk . (root </>) . fst) dirs
```

<p>It currently returns a list, but I'd like it to return a <code>Traversable</code> instead:</p>

<pre class="lang-hs prettyprint-override"><code>walk :: (MonadIO m, Traversable t) => FilePath -> m (t (FilePath, [FilePath]))
</code>```

If I change the signature, I get the following error:

```<code>    • Couldn't match type ‘t’ with ‘[]’
      ‘t’ is a rigid type variable bound by
        the type signature for:
          walk :: forall (m :: * -> *) (t :: * -> *).
                  (MonadIO m, Traversable t) =>
                  FilePath -> m (t (FilePath, [FilePath]))
      Expected type: m (t (FilePath, [FilePath]))
        Actual type: m [(FilePath, [FilePath])]
    • In a stmt of a 'do' block:
        ((root, map fst files) :) . concat
          <$> mapM (walk . (root </>) . fst) dirs
      In the expression:
        do entries <- liftIO $ listDirectory root
           (files, dirs) <- partition snd
                              <$>
                                liftM2
                                  (<$>) zip (mapM (liftIO . doesFileExist .
(root </>))) entries
           ((root, map fst files) :) . concat
             <$> mapM (walk . (root </>) . fst) dirs
      In an equation for ‘walk’:
          walk root
            = do entries <- liftIO $ listDirectory root
                 (files, dirs) <- partition snd
                                    <$>
                                      liftM2
                                        (<$>)
                                        zip
                                        (mapM (liftIO . doesFileExist .
(root </>)))
                                        entries
                 ((root, map fst files) :) . concat
                   <$> mapM (walk . (root </>) . fst) dirs
    • Relevant bindings include
        walk :: FilePath -> m (t (FilePath, [FilePath]))
</code>```

I think it's failing on the :? I can't be sure. How do I fix this?

答:
I think it's failing on the :?

Indeed it is. If you use (:) to build the structure, the structure will be a list, and you can't change the type of walk to claim it returns an arbitrary traversable structure. There isn't really a good Traversable-centric workaround, either: Traversable means you have, via its Foldable superclass, a toList, but not a fromList.

Body:
I have the following module which implements a directory walk:

module Walk
  ( walk
  ) where

import           Control.Monad
import           Control.Monad.IO.Class
import           Data.List
import           System.Directory
import           System.FilePath

walk :: (MonadIO m) => FilePath -> m [(FilePath, [FilePath])]
walk root = do
  entries <- liftIO $ listDirectory root
  (files, dirs) <- partition snd <$> liftM2 (<$>) zip (mapM (liftIO . doesFileExist . (root </>))) entries
  ((root, map fst files) :) . concat <$> mapM (walk . (root </>) . fst) dirs

It currently returns a list, but I'd like it to return a Traversable instead:

walk :: (MonadIO m, Traversable t) => FilePath -> m (t (FilePath, [FilePath]))

If I change the signature, I get the following error:

    • Couldn't match type ‘t’ with ‘[]’
      ‘t’ is a rigid type variable bound by
        the type signature for:
          walk :: forall (m :: * -> *) (t :: * -> *).
                  (MonadIO m, Traversable t) =>
                  FilePath -> m (t (FilePath, [FilePath]))
      Expected type: m (t (FilePath, [FilePath]))
        Actual type: m [(FilePath, [FilePath])]
    • In a stmt of a 'do' block:
        ((root, map fst files) :) . concat
          <$> mapM (walk . (root </>) . fst) dirs
      In the expression:
        do entries <- liftIO $ listDirectory root
           (files, dirs) <- partition snd
                              <$>
                                liftM2
                                  (<$>) zip (mapM (liftIO . doesFileExist .
(root </>))) entries
           ((root, map fst files) :) . concat
             <$> mapM (walk . (root </>) . fst) dirs
      In an equation for ‘walk’:
          walk root
            = do entries <- liftIO $ listDirectory root
                 (files, dirs) <- partition snd
                                    <$>
                                      liftM2
                                        (<$>)
                                        zip
                                        (mapM (liftIO . doesFileExist .
(root </>)))
                                        entries
                 ((root, map fst files) :) . concat
                   <$> mapM (walk . (root </>) . fst) dirs
    • Relevant bindings include
        walk :: FilePath -> m (t (FilePath, [FilePath]))

I think it's failing on the :? I can't be sure. How do I fix this?


问:
Find invalid numbers - Oracle SQL
I have a table:

table1

```<code>column_name    value
Test1          80933Y355220
Test1          8093363X5220
Test1          809336355220
Test1          80.98
Test1          -80.98

Test2          1234
Test2          abc
Test2          12-23-09
</code>```

I need to identify all the invalid number values present in the column value

Output should be:

```<code>column_name    value
Test1          80933Y355220
Test1          8093363X5220

Test2          abc
Test2          12-23-09
</code>```

Is there a way to get this list?

答:
The common way to solve this is with a user-defined function:

```<code>create or replace function is_number (p_str in varchar2) return varchar2 is
n number;
rv varchar2(1);
begin
  begin
    n := to_number(p_str);
    rv := 'Y';
  exception
    when others then
      rv := 'N';
  end;
  return rv;
end;
/

select column_name, value, is_number(value) as is_number
from table1
where is_number(value) = 'N'
/
</code>```

In Oracle 12c R2 we acquired a built-in function to do it: validate_conversion() which handles lots of data types. Find out more.

```<code>select column_name
       , value
from table1
where validate_conversion(value as number) = 0
/
</code>```

Here is the inevitable demo on db<>fiddle.

Regex solutions are tricky to get right. It's easy to formulate expressions which exclude valid numbers (such as -80.98) or include non-numbers (such as (12-34-56). Even we do get that bit right (as Gordon's solution does) what happens if we want to allow decimal separators or currency symbols?  Or scientific notation? That's a messy regex. It's easy to extend a UDF to handle a format mask and validate_conversion() does it natively:

```<code>SELECT VALIDATE_CONVERSION('$100,00' AS NUMBER,
         '$999D99', 'NLS_NUMERIC_CHARACTERS = '',.''')
FROM DUAL;
</code>```

Title: Find invalid numbers - Oracle SQL

Body:
I have a table:

table1

column_name    value
Test1          80933Y355220
Test1          8093363X5220
Test1          809336355220
Test1          80.98
Test1          -80.98

Test2          1234
Test2          abc
Test2          12-23-09

I need to identify all the invalid number values present in the column value

Output should be:

column_name    value
Test1          80933Y355220
Test1          8093363X5220

Test2          abc
Test2          12-23-09

Is there a way to get this list?

Body:
The common way to solve this is with a user-defined function:

create or replace function is_number (p_str in varchar2) return varchar2 is
n number;
rv varchar2(1);
begin
  begin
    n := to_number(p_str);
    rv := 'Y';
  exception
    when others then
      rv := 'N';
  end;
  return rv;
end;
/

select column_name, value, is_number(value) as is_number
from table1
where is_number(value) = 'N'
/

In Oracle 12c R2 we acquired a built-in function to do it: validate_conversion() which handles lots of data types. Find out more.

select column_name
       , value
from table1
where validate_conversion(value as number) = 0
/

Here is the inevitable demo on db<>fiddle.

Regex solutions are tricky to get right. It's easy to formulate expressions which exclude valid numbers (such as -80.98) or include non-numbers (such as (12-34-56). Even we do get that bit right (as Gordon's solution does) what happens if we want to allow decimal separators or currency symbols?  Or scientific notation? That's a messy regex. It's easy to extend a UDF to handle a format mask and validate_conversion() does it natively:

SELECT VALIDATE_CONVERSION('$100,00' AS NUMBER,
         '$999D99', 'NLS_NUMERIC_CHARACTERS = '',.''')
FROM DUAL;


问:
expo cli error installing time i tried many time
i am facing this problem when i am installing expo cli i tried both command npm install expo-cli --global and with sudo also sudo npm install expo-cli --global but i am facing same error

npm WARN deprecated joi@14.0.4: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.

@expo/traveling-fastlane-darwin@1.9.4 preinstall /usr/local/lib/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin
  node platform.js

/usr/local/bin/expo -> /usr/local/lib/node_modules/expo-cli/bin/expo.js
/usr/local/bin/expo-cli -> /usr/local/lib/node_modules/expo-cli/bin/expo.js

fsevents@1.2.9 install /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
  node install

node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp WARN Pre-built binaries not installable for fsevents@1.2.9 and node@10.15.3 (node-v64 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib'
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/build'
gyp ERR! System Darwin 18.5.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node" "--module_name=fse" "--module_path=/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64" "--napi_version=3" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v64"
gyp ERR! cwd /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node --module_name=fse --module_path=/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64 --napi_version=3 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
node-pre-gyp ERR! stack     at ChildProcess. (/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:189:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:970:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
node-pre-gyp ERR! System Darwin 18.5.0
node-pre-gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/node_modules/node-pre-gyp/bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
node-pre-gyp ERR! node -v v10.15.3
node-pre-gyp ERR! node-pre-gyp -v v0.12.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node --module_name=fse --module_path=/usr/local/lib/node_modules/expo-cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64 --napi_version=3 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)

iltorb@2.4.3 install /usr/local/lib/node_modules/expo-cli/node_modules/iltorb
  node ./scripts/install.js || node-gyp rebuild

WARN install EACCES: permission denied, access '/Users/abhisheksharma/.npm'
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/expo-cli/node_modules/iltorb/build'
gyp ERR! System Darwin 18.5.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/expo-cli/node_modules/iltorb
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok

sharp@0.22.1 install /usr/local/lib/node_modules/expo-cli/node_modules/sharp
  (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

ERR! sharp EACCES: permission denied, mkdir '/Users/abhisheksharma/.npm/_libvips'
info sharp Attempting to build from source via node-gyp but this may fail due to the above error
info sharp Please see https://sharp.pixelplumbing.com/page/install for required dependencies
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/expo-cli/node_modules/sharp/build'
gyp ERR! System Darwin 18.5.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/expo-cli/node_modules/sharp
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-linux@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/traveling-fastlane-linux@1.9.4: wanted {"os":"win32,linux","arch":"any"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-x64@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-x64@2.2.8-beta.1: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-ia32@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-sunos-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-sunos-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-sunos-x64@2.2.8: wanted {"os":"sunos","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-x64@2.2.8: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-ia32@2.2.8: wanted {"os":"linux","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm64@2.2.8: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm@2.2.8: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-x64@2.2.8: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-ia32@2.2.8: wanted {"os":"freebsd","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-darwin-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-darwin-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-darwin-ia32@2.2.8: wanted {"os":"darwin","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/expo-cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: node install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 (node_modules/expo-cli/node_modules/iltorb):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 install: node ./scripts/install.js || node-gyp rebuild
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sharp@0.22.1 install: (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sharp@0.22.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/abhisheksharma/.npm/_logs/2019-05-28T02_07_57_162Z-debug.log
Abhisheks-MacBook-Air:~ abhisheksharma$

答:
Install it with yarn:

sudo npm install -g yarn

Then:

sudo yarn global add expo-cli


问:
Lambda copy assignment operator is not defined
Why this does not compile with CLang 7 and lower, but compiles with CLang 8 and above:

```<code>#include <map>
#include <string>

typedef std::map<std::string, int> TestMap;

TestMap m {
    {"a", 1},
    {"b", 2},
    {"c", 3},
};

auto func = [](const TestMap::value_type & p) -> int { return p.second; };
auto func1 = func;
//In CLang 7 and lower copy assignment operator is not defined
func = func1;
</code>```

what actually changed?

But this compiles with all CLang versions:

```<code>auto func1 = []() { return 5;};
decltype(func1) func2 = func1;
func2 = func1;
</code>```

All the sample code available here

what is the difference between lambdas?

答:
As @rafix07 mentioned in the comments, you have to compile with C++20 standard.

the standard prior to C++20:

```<code>ClosureType& operator=(const ClosureType&) = delete; (until C++20)
</code>```

If no captures are specified, the closure type has a defaulted copy
  assignment operator and a defaulted move assignment
  operator. Otherwise, it has a deleted copy assignment operator (this
  includes the case when there is a capture-default, even if it does not
  actually capture anything). (since C++20)

The copy assignment operator is defined as deleted (and the move
  assignment operator is not declared). Closure types are not
  CopyAssignable. (until C++20)
      ClosureType::operator=(const ClosureType&)

```<code>ClosureType& operator=(const ClosureType&) = delete; (until C++20)

ClosureType& operator=(const ClosureType&) = default; (since C++20)
ClosureType& operator=(ClosureType&&) = default; (only if no captures are specified)

ClosureType& operator=(const ClosureType&) = delete; (since C++20)
(otherwise)
</code>```

https://en.cppreference.com/w/cpp/language/lambda

see the compilation here: https://godbolt.org/z/jpCYNQ

code sample taken from @Alexey Starinsky link in the comments.

Body:
Why this does not compile with CLang 7 and lower, but compiles with CLang 8 and above:

#include <map>
#include <string>

typedef std::map<std::string, int> TestMap;

TestMap m {
    {"a", 1},
    {"b", 2},
    {"c", 3},
};

auto func = [](const TestMap::value_type & p) -> int { return p.second; };
auto func1 = func;
//In CLang 7 and lower copy assignment operator is not defined
func = func1;

what actually changed?

But this compiles with all CLang versions:

auto func1 = []() { return 5;};
decltype(func1) func2 = func1;
func2 = func1;

All the sample code available here

what is the difference between lambdas?

Body:
As @rafix07 mentioned in the comments, you have to compile with C++20 standard.

the standard prior to C++20:

ClosureType& operator=(const ClosureType&) = delete; (until C++20)

If no captures are specified, the closure type has a defaulted copy
  assignment operator and a defaulted move assignment
  operator. Otherwise, it has a deleted copy assignment operator (this
  includes the case when there is a capture-default, even if it does not
  actually capture anything). (since C++20)

The copy assignment operator is defined as deleted (and the move
  assignment operator is not declared). Closure types are not
  CopyAssignable. (until C++20)
      ClosureType::operator=(const ClosureType&)

ClosureType& operator=(const ClosureType&) = delete; (until C++20)

ClosureType& operator=(const ClosureType&) = default; (since C++20)
ClosureType& operator=(ClosureType&&) = default; (only if no captures are specified)

ClosureType& operator=(const ClosureType&) = delete; (since C++20)
(otherwise)

https://en.cppreference.com/w/cpp/language/lambda

see the compilation here: https://godbolt.org/z/jpCYNQ

code sample taken from @Alexey Starinsky link in the comments.


问:
Flutter android app crashes upon startup if I include a certain package
A problem has suddenly recently arisen such that simply by including the  dependency in 'location' in pubspec.yaml like e.g.

```<code>dependencies:
  flutter:
    sdk: flutter

  location: ^1.2.0  <------------------------ culprit
  firebase_auth: ^0.5.10
  cloud_firestore: ^0.7.2

the app crashes immediately upon startup.
</code>```

The 'location' package itself works when alone in an example app.
I am not currently importing i.e. using any of the functionality contained within the location package, yet when I remove the entry, all is well.

No clues from watching flutter log unfortunately...

答:
no need to change anything, a simple flutter build apk will solve the problem (if all the packages in pubspec.yaml are updated and error free)

this happens quite often when switching to a branch that has a completely different list of packages, flutter needs to build...

Body:
A problem has suddenly recently arisen such that simply by including the  dependency in 'location' in pubspec.yaml like e.g.

dependencies:
  flutter:
    sdk: flutter

  location: ^1.2.0  <------------------------ culprit
  firebase_auth: ^0.5.10
  cloud_firestore: ^0.7.2

the app crashes immediately upon startup.

The 'location' package itself works when alone in an example app.
I am not currently importing i.e. using any of the functionality contained within the location package, yet when I remove the entry, all is well.

No clues from watching flutter log unfortunately...


问:
Use "toLowerCase" on an interface's optional attribute
I'm developping a filtering app in Angular.
I fill a Mat-Table with data and then I set some filters to reduce the amount of displayed projects.

My 'Project' interface has an optional attribute 'location?', which is causing me problems:

```<code>export interface Project {
  id: number;
  name: string;
  location?: string;
}
</code>```

I add some projects to a constant:

```<code>export const PROJECTS: Project[] = [
  { id: 1, name: 'Hey', location: 'London' },
  { id: 2, name: 'Blub', location: 'Rome' },
  { id: 3, name: 'noloc'}
];
</code>```

BUT I have a problem when it comes to filtering:

```<code>proj.location.toLowerCase().indexOf(this.locationData.toLowerCase()) > -1
</code>```

The line above returns an error (because 'noloc' has no specified location and I'm therefore trying to apply the function to 'undefined'):

ERROR TypeError: Cannot read property 'toLowerCase' of undefined

What's the best way of tackling this?

For now all I can think of is to replace my interface with a class, and in the constructor make sure that if no location is specified, an empty string is set. But I guess there must be some smarter/nicer way of getting around this.

答:
I think its a simple null check before you apply toLowerCase()

proj && proj.location && proj.location.toLowerCase().indexOf(this.locationData.toLowerCase()) > -1

Body:
I'm developping a filtering app in Angular.
I fill a Mat-Table with data and then I set some filters to reduce the amount of displayed projects.

My 'Project' interface has an optional attribute 'location?', which is causing me problems:

export interface Project {
  id: number;
  name: string;
  location?: string;
}

I add some projects to a constant:

export const PROJECTS: Project[] = [
  { id: 1, name: 'Hey', location: 'London' },
  { id: 2, name: 'Blub', location: 'Rome' },
  { id: 3, name: 'noloc'}
];

BUT I have a problem when it comes to filtering:

proj.location.toLowerCase().indexOf(this.locationData.toLowerCase()) > -1

The line above returns an error (because 'noloc' has no specified location and I'm therefore trying to apply the function to 'undefined'):

ERROR TypeError: Cannot read property 'toLowerCase' of undefined

What's the best way of tackling this?

For now all I can think of is to replace my interface with a class, and in the constructor make sure that if no location is specified, an empty string is set. But I guess there must be some smarter/nicer way of getting around this.


问:
Double clicking on BottomSheetDialog quickly gives two dialog
I have a bottom sheet dialog fragment that i use as a menu for my bottom app bar.

If i click on the menu icon really quick two times, the dialog shows up two times and i have to close it two times which is annoying.

My code is as follows:

ActivityHome.kt

```<code>override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
    android.R.id.home -> {
        if(mBottomNavDrawerFragment != null && mBottomNavDrawerFragment!!.dialog!!.isShowing){
            mBottomNavDrawerFragment?.dismiss()
            return false
        }
        mBottomNavDrawerFragment = RoundedBottomSheetDialogFragment()
        mBottomNavDrawerFragment?.show(supportFragmentManager, mBottomNavDrawerFragment?.tag)
        true
    }
    R.id.BottomAppBar_fromHomeActivity_MenuMain_Search -> {
        Toast.makeText(this, "Not Implemented yet!", Toast.LENGTH_SHORT).show()
        false
    }
    else -> true
}
}
</code>```

Can anyone help? Thanks

答:
You can do a little bit hack here. Here is the code.

```<code>private var saveClickCounter = 0
override fun onOptionsItemSelected(item: MenuItem?): Boolean {

    return when (item?.itemId) {
        R.id.home -> {
            if (saveClickCounter++ == 0) {

                //Your Dialog Showing Code

                Handler().postDelayed({
                   saveClickCounter=0
                },1000)
            }
            true
        }

        R.id.BottomAppBar_fromHomeActivity_MenuMain_Search -> {
            Toast.makeText(this, "Not Implemented yet!", Toast.LENGTH_SHORT).show()
            false
        }
        else -> true
    }
}
</code>```

Make a variable saveClickCounter to store your counts.

On clicks increase the value of saveClickCounter and change it to zero after N seconds of delayed. I used 1 second in below code.

Body:
I have a bottom sheet dialog fragment that i use as a menu for my bottom app bar.

If i click on the menu icon really quick two times, the dialog shows up two times and i have to close it two times which is annoying.

My code is as follows:

ActivityHome.kt

override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
    android.R.id.home -> {
        if(mBottomNavDrawerFragment != null && mBottomNavDrawerFragment!!.dialog!!.isShowing){
            mBottomNavDrawerFragment?.dismiss()
            return false
        }
        mBottomNavDrawerFragment = RoundedBottomSheetDialogFragment()
        mBottomNavDrawerFragment?.show(supportFragmentManager, mBottomNavDrawerFragment?.tag)
        true
    }
    R.id.BottomAppBar_fromHomeActivity_MenuMain_Search -> {
        Toast.makeText(this, "Not Implemented yet!", Toast.LENGTH_SHORT).show()
        false
    }
    else -> true
}
}

Can anyone help? Thanks

Body:
You can do a little bit hack here. Here is the code.

private var saveClickCounter = 0
override fun onOptionsItemSelected(item: MenuItem?): Boolean {

    return when (item?.itemId) {
        R.id.home -> {
            if (saveClickCounter++ == 0) {

                //Your Dialog Showing Code

                Handler().postDelayed({
                   saveClickCounter=0
                },1000)
            }
            true
        }

        R.id.BottomAppBar_fromHomeActivity_MenuMain_Search -> {
            Toast.makeText(this, "Not Implemented yet!", Toast.LENGTH_SHORT).show()
            false
        }
        else -> true
    }
}

Make a variable saveClickCounter to store your counts.

On clicks increase the value of saveClickCounter and change it to zero after N seconds of delayed. I used 1 second in below code.


答: dplyr::as_tibble(df, rownames = "your_row_name") will give you even simpler result.

Title: How can I convert row names into the first column?

Body:
I have a data frame like this:

df
              VALUE              ABS_CALL DETECTION P-VALUE
    1007_s_at "957.729231881542" "P"      "0.00486279317241156"
    1053_at   "320.632701283368" "P"      "0.0313356324173416"
    117_at    "429.842323161046" "P"      "0.0170004527476119"
    121_at    "2395.7364289242"  "P"      "0.0114473584876183"
    1255_g_at "116.493632746934" "A"      "0.39799368200131"
    1294_at   "739.927122116896" "A"      "0.0668649772942343"

I want to convert the row names into the first column. Currently I use something  like this to make row names as the first column:

  d <- df
  names <- rownames(d)
  rownames(d) <- NULL
  data <- cbind(names,d)

Is there a single line to do this?


问:
Can we play .m3u8 file using flv.js player?
I am working on a Live video streaming project. I am using flv.js in my web application to play Live Stream Videos which are in the flv format. I want to give playback option for the user. for playback, I have m3u8 file to play video.
My questions are,

Can we play .m3u8 file using flv.js?

If yes. How to do that?

If No. What will be the best solution?

答:
1) no. flv.js plays flv files

2) hls.js plays m3u8 files.


问:
Using expression returning methods in EF
I have an expression returning method such as:

```<code>    public Expression<Func<User, bool>> GetUserPredicate(int userID)
    {
        return u => u.ID == userID;
    }
</code>```

(In the original code, this is a longer and more complex piece of logic that I want to reuse so that I extrcted it out into such a method.)

I can use it in queries for Users without a problem:

```<code>    var user = dbContext.Users
        .Where(GetUserPredicate(1))
        .Single();
</code>```

But I also want to use it when querying other entities like Posts:

```<code>    var post = dbContext.Posts
        .Where(p => p.ID == 1)
        .Where(p.User => GetUserPredicate(1))
        .Single();
</code>```

But this does not work. How can it be accomplished?

答:
You could create a generic method. The problem is that you need to access properties of unrelated classes. But this is not possible with generics, unless a generic type constraint makes these properties available. Idea: define the required properties in interfaces:

```<code>public interface IUserProvider
{
    int UserID { get; set; }
}

public class User : IUserProvider ...
public class Post : IUserProvider ...
</code>```

Then define the method as

```<code>public Expression<Func<TEntity, bool>> GetUserPredicate<TEntity>(int userID)
    where TEntity : IUserProvider
{
    return e => e.UserID == userID;
}
</code>```

Body:
I have an expression returning method such as:

    public Expression<Func<User, bool>> GetUserPredicate(int userID)
    {
        return u => u.ID == userID;
    }

(In the original code, this is a longer and more complex piece of logic that I want to reuse so that I extrcted it out into such a method.)

I can use it in queries for Users without a problem:

    var user = dbContext.Users
        .Where(GetUserPredicate(1))
        .Single();

But I also want to use it when querying other entities like Posts:

    var post = dbContext.Posts
        .Where(p => p.ID == 1)
        .Where(p.User => GetUserPredicate(1))
        .Single();

But this does not work. How can it be accomplished?

Body:
You could create a generic method. The problem is that you need to access properties of unrelated classes. But this is not possible with generics, unless a generic type constraint makes these properties available. Idea: define the required properties in interfaces:

public interface IUserProvider
{
    int UserID { get; set; }
}

public class User : IUserProvider ...
public class Post : IUserProvider ...

Then define the method as

public Expression<Func<TEntity, bool>> GetUserPredicate<TEntity>(int userID)
    where TEntity : IUserProvider
{
    return e => e.UserID == userID;
}


问:
How to generate a random sample of points from a 3-D ellipsoid using Python?
I am trying to sample around 1000 points from a 3-D ellipsoid, uniformly. Is there some way to code it such that we can get points starting from the equation of the ellipsoid?

I want points on the surface of the ellipsoid.

答:
J.F. Williamson, "Random selection of points distributed on curved surfaces", Physics in Medicine & Biology 32(10), 1987, describes a general method of choosing a uniformly random point on a parametric surface. It is an acceptance/rejection method that accepts or rejects each candidate point depending on its stretch factor (norm-of-gradient). To use this method for a parametric surface, several things have to be known about the surface, namely—

x(u, v), y(u, v) and z(u, v), which are functions that generate 3-dimensional coordinates from two dimensional coordinates u and v,

The ranges of u and v,

g(point), the norm of the gradient ("stretch factor") at each point on the surface, and

gmax, the maximum value of g for the entire surface.

The algorithm is then:

Generate a point on the surface, xyz.

If g(xyz) >= RNDU01()*gmax, where RNDU01() is a uniform random variate in [0, 1), accept the point. Otherwise, repeat this process.

Chen and Glotzer (2007) apply the method to the surface of a prolate spheroid (one form of ellipsoid) in "Simulation studies of a phenomenological model for elongated virus capsid formation", Physical Review E 75(5), 051504 (preprint).