问:
Problems with convergency when using solnp function in R
When solving a portfolio optimization problem with an additional 1-norm constraint on the portfolio weights, I faced with convergency problems.

Description of the exercise:

For given N assets with T observations of their returns find the value of 1Norm constraint Theta, such that the last period portfolio return (T-th one) is maximized. That is, solve the problem: min_w w'COVw$ s.t. w1+w2+...+wN=1 and |w1|+|w2|+...+|wN|<=Theta and, out of all values of Theta, choose the one with the maximum value of w'r_T, where r_T is the vector of assets returns in the last period and COV is the variance-covariance matrix of asset returns.

Description of the problem:

First I tried the "naive" approach: with a grid of 0.001 for Theta from 1 to 6 I was going to solve the portfolio optimization problem and compute the last period portfolio return for each Theta. The idea was to choose then the value of Theta with the largest corresponding last period return. However, I noticed that for quite a few values of Theta the solnp function did not converge. The problem occured mostly for small values of Theta: from 1 to 3. For larger values no problems with convergency were detected.

The second approach was to use solnp function twice: first as the function to find Theta and second as the inner part of the objective function. However, I could not find reliable estimates in this way: the values I got did not deliver the optimal solution. Apparently, the objective function is not smooth, but gosolnp function does not find the solution.

The code with data (6 assets with 120 return observations) is provided below. Any suggestions are welcome.

```<code>> exp_d
        [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
1     1.3724   0.9081  -0.0695   5.7168   1.9642   1.4222
2     0.6095   1.5075   5.3842   2.7154   2.6838   6.3154
3    -2.6779  -0.1359  -0.4374   1.4287   0.0709  -0.7967
4    -3.5365  -4.3572  -2.0112  -3.5898  -2.3460  -4.0970
5     3.1210   3.6608   2.0944   3.1292   2.8965   3.4614
6     2.7364   1.8411   3.2639   2.9678   2.6067   2.3950
7    -1.0001  -0.3782   3.9316  -0.2621   0.0347   4.4635
8     3.9022   6.3784   6.6192   5.0044   3.5568   8.6305
9    -1.6000  -0.9889  -3.1676   1.3025   0.2071  -2.4764
10   -1.3184   0.8741   3.4796   3.0510  -0.7634  -0.5452
11    5.5482   3.3467  13.3256   5.4076   5.1017   7.4921
12   -1.5484   1.3040  -3.9474  -0.9628  -3.0156  -1.6326
13    4.3331   5.2347   3.9846   9.2369   6.7429   7.2603
14    2.3503  -2.2044   0.8600   3.9191   1.2181  -1.9651
15    2.3981   2.2316   0.3990   5.3864   4.3919   5.9674
16   -0.1633  -2.1458  -5.8357  -3.6349  -4.2840  -6.6219
17   10.4346   8.0620  10.2275   7.0560   6.7676   6.6346
18    5.5505   2.6016   2.4506   2.4954   1.8547   3.4755
19    3.2031   2.7804   3.5948  -0.4774  -0.3667  -2.3168
20   -4.7913  -1.7203  -4.1271  -0.6762  -1.1395  -2.7296
21    7.3930   8.6229   9.4570  12.2800   6.1327   7.8254
22    4.2158  10.6845   9.9723   2.9145   6.0000   4.4979
23    7.5326   1.9540   2.5740   2.6065  -0.1128   0.6388
24   -8.5131  -8.3044  -6.8294  -3.6094  -4.1224  -5.4164
25   -0.4048  -0.4017  -0.8867   1.3590   0.1098   0.9017
26    6.1240   5.0517   3.6990   8.7368   5.3867   6.9468
27    5.7317   4.4538   6.1762   3.4108   1.9153   4.4896
28    6.8299   3.1244   1.6621   1.3590   1.4325   2.0067
29    8.6705  11.1936  12.2831  11.1602  13.2781  13.1497
30    0.9055  -0.5953  -0.6462   0.9332  -0.0008   1.2917
31   -0.0340   1.9379   1.4480   6.5262   4.8373   2.6307
32    0.7414   1.1014   0.3820  -0.5791   0.8306   3.1476
33   -5.9533  -3.4602  -4.1597  -1.3835   2.2098  -0.0642
34   -0.0822   2.7549   0.5136   2.2172   1.1145   2.8362
35  -10.2009  -9.3603 -12.8907  -5.7297  -4.1622  -6.1709
36    6.9673   9.4356   6.4064  12.4593   9.3500   7.5052
37   -0.0681  -0.7029   3.8633   3.5471   6.2018   4.9529
38   -0.8885  -0.4641  -0.4544   7.2353  12.5430   6.9497
39   -4.2569  -4.3105  -3.6218  -4.4211  -4.9685  -6.3175
40  -21.7261 -19.3351 -19.8329 -24.1865 -14.0943 -10.3723
41  -16.4096  -9.8425 -12.3366 -14.2535 -10.9314  -7.6677
42   -2.7511  -2.7249  -1.8488   3.3988   0.5515   1.3170
43    6.2347   9.4395   8.4631   7.1735   3.3113   2.9221
44    1.3502   1.2075   4.3779   3.4639   1.8818   1.2221
45    9.0009  11.0661  10.7647   6.8160   8.3348   5.3573
46   -6.0956  -1.7406  -3.4814  -2.3610  -1.7939  -6.6523
47   -3.7611  -2.3132  -2.9578   0.7061  -2.2643  -1.3650
48  -16.9330 -16.6497 -18.9287 -17.8490 -13.1565 -11.8439
49    6.5208   3.7280   2.5406   4.4017   4.2198   5.2644
50   -3.7646  -1.6135  -2.5073   1.1969  -0.8000  -1.6232
51  -13.6823 -14.6721 -19.1619 -12.0325 -11.7394 -17.0858
52  -10.1007  -7.6801 -10.7443  -9.4278  -7.3264 -11.4835
53    0.2234  -2.7838  -2.6023  -2.3616  -2.8339  -6.6002
54  -10.4236 -11.0266 -17.2866  -5.8057  -9.1776  -9.7245
55    9.9121  11.3602  15.4627   4.7170   6.9823  13.5911
56   13.2032  11.6577  17.0900  12.8706   6.7357  12.1756
57   -4.3440  -2.9204  -6.9601  -4.1971 -10.3577  -8.8826
58  -12.8949 -14.0212 -18.2229  -8.8412 -11.1070 -11.3490
59   -9.6709  -8.7006 -13.8440 -11.3932 -15.9343 -20.3630
60   10.1262   7.7295  20.3174  12.8509  16.1956  25.2657
61   -8.5867  -8.9411  -5.7363  -5.1668 -10.1775 -12.2143
62   -1.6114  -1.1797  -3.7504   0.8986  -1.5948   0.0531
63  -26.5722 -30.0521 -33.8286 -28.8671 -28.1493 -35.1131
64    4.2319   9.2071   5.4593   9.5401   3.2588  11.7214
65   -7.7335  -7.2915  -9.3902  -6.1288 -16.6307 -14.5665
66  -13.7987 -16.5088 -22.4192 -11.5667 -18.8221 -20.6686
67    2.4924   3.9264  10.5116  -3.4347   1.9132   6.6353
68   -2.4754   1.9822   1.3833   7.1142   1.7366   0.3507
69  -10.5259 -12.1366 -10.6244 -10.2031 -15.1403 -14.7460
70  -19.3072 -17.1449 -16.0430 -18.1275 -20.1476 -18.5418
71  -17.1387 -24.8400 -17.4741 -19.2184 -25.9531 -25.4360
72    0.9540   6.2481   1.0364  -1.7110   0.0545   8.8476
73   31.9086  36.1125  63.2475  28.1955  48.6209  67.7847
74   48.7266  55.3725  83.5754  31.3211  50.9661  62.5277
75   -2.8054  -4.5841 -12.4737  -1.0366  -6.5149  -5.0087
76  -16.2535 -19.6450 -23.8672 -10.7514 -17.5126 -23.2272
77   -0.2972  -8.2786 -13.2053  -2.7223  -8.9288 -16.3816
78   -5.1581  -4.2529 -11.0631   6.8503   1.0438  -3.5633
79    4.3896   1.3914   7.8950  -0.0120   3.0297   8.7685
80  -17.8468 -18.4137 -20.8881 -14.9493 -16.5816 -17.3738
81    7.0790   6.1577  16.0332   0.9569   9.8608   6.7577
82   45.4453  54.8024  56.5610  33.7390  51.8933  57.4905
83   59.9378  62.1965  73.3394  16.9717  26.7781  41.6260
84   32.9373  23.3035  18.5882  11.3683  15.5089  21.9496
85  -14.1385 -12.7712  -7.2418  -8.8583 -13.0573  -9.2208
86   10.5585  10.1102   8.2144  10.5958  15.7784  18.8615
87   -7.6121 -13.3352 -20.9042  -9.1454 -12.3603 -19.3866
88   -8.4949 -12.4200 -13.8362  -6.1614 -10.5922 -17.7448
89    4.4492   4.6618   6.1086   9.6900  12.2772  12.6924
90    4.7702   4.0567   0.4565   2.1093   1.8286   3.3536
91   21.5203  28.5643  38.3403   9.8669  16.8246  24.1368
92   -0.2935   1.1796   5.3723  -2.3815  -3.1241  -3.8100
93    4.7722   2.0674  -0.0727  -0.0029  -0.1362  -0.6200
94    2.8356  -1.3170  -1.8303  -1.7780  -2.3152  -4.6160
95   -7.3381  -9.8907 -12.0504  -6.4033  -8.5879 -13.5106
96    3.7672   0.0811  -2.3100   2.6280   2.4811   2.8615
97  -18.0226 -21.5042 -24.4760  -8.3110 -11.7051 -23.1790
98   10.9235   9.4125  12.2230   6.0718   4.4464   5.7691
99   -0.9255  -0.5806  -3.5672  -0.2597  -0.1487  -0.1050
100  -0.9250  -1.6380  -4.1937  -0.4115  -2.7080  -7.3690
101  17.4218  15.4433  12.5284  10.2402   5.0137  10.6573
102   4.9409   1.7554   1.5981   0.7507   0.5333  -2.2372
103  -5.5523  -3.3988  -3.0325  -3.0099  -2.8838  -9.3128
104  -3.5225  -4.8589  -5.8780  -0.8581  -1.6838 -12.9875
105  -5.9234  -7.4692 -11.2668  -2.9715  -3.3289  -7.7499
106   6.7174   9.3484  10.2238   8.0311   9.8871  13.0598
107  -2.4801   2.3317   1.7345   3.1370   4.3390   3.9570
108  -1.7502   5.9262   0.8071   6.3821   5.6136   8.0813
109   9.1528  12.9358  12.7537   6.9882   6.3196  17.1148
110   4.2227   8.6796  14.4462   2.5694   2.2001   3.7475
111   5.0917   5.5331   0.5575   4.6757   0.6768   1.1198
112  10.9064  10.8504   6.8068   6.6016   7.9769   6.0328
113   6.6969  10.4475  18.9743   3.0389   5.6087  14.5739
114   5.7713  10.1556   2.2152   2.9835   5.8064   8.6858
115  10.3194   7.6727  22.3771   3.2881   9.5299  12.2406
116   1.9010   6.5601   6.7824   1.9137   2.8060   7.1039
117   0.5096   2.3380   0.8324   2.6378   0.0632  -1.0088
118 -14.3931 -13.9743 -15.4640  -7.1563  -8.3505 -10.2494
119   4.9011   5.5856   8.6767   5.0578   5.1107   6.5508
120  -2.2080  -0.2588  -1.2498   3.6325   2.1402   0.2676

#define equality constraint function
equal <- function(x) c(sum(x))

#define inequality constraint function
in_inequal <- function(x) c(sum(abs(x)))

#define objective function1
obj_f <- function(x) {

  int_r <- t(x)%*%V_C_M%*%x
  c(as.numeric(int_r))

}

#define objective function2
ex_obj_f <- function(x) {

  tteta <- x

  port_w <- solnp(rep(1/n,n), fun = obj_f, eqfun=equal, eqB=1,
       ineqfun = in_inequal, ineqLB = 0, ineqUB = tteta, control = list(trace=0))

  lp_ret <- exp_d[nrow(exp_d),]%*%port_w$pars

  -lp_ret

}

#First "naive" attempt
exp_d <- as.matrix(exp_d)
n <- 6
V_C_M <- cov(exp_d)

res <- matrix(0:0, nrow = 5000, ncol = 3)

for (i in 1:5000) {

  tteta <- 1 + i*0.001
  port_w <- solnp(rep(1/n,n), fun = obj_f, eqfun=equal, eqB=1,  ineqfun = in_inequal, ineqLB = 0, ineqUB = tteta, control = list(trace=0))
  lp_ret <- exp_d[nrow(exp_d),]%*%port_w$pars

  res[i,1] <- tteta
  res[i,2] <- lp_ret
  res[i,3] <- port_w$convergence

}

#Second Approach (the result really depends on the starting value of the parameter)
tt_op1 <- solnp(pars = 1.5, fun = ex_obj_f, LB = 1, UB = 10, control = list(trace=1))
tt_op2 <- gosolnp(pars = 1.5, fun = ex_obj_f, LB = 1, UB = 10)
</code>```

P.S. I have read posts with similar problems here, but coud not find a solution to my question.

答:
Your model can be formulated as a pure QP (quadratic programming) problem instead of a difficult nonlinear problem with a nonlinear non-differentiable constraint.

The constraint

```<code> sum(i, |x(i)|) <= Theta
</code>```

can be linearized in different ways. One possible reformulation is

```<code> -y(i) <= x(i) <= y(i)
 sum(i, y(i)) <= Theta
 non-negative (or free) variable y(i)
</code>```

Now you can solve the model with a QP solver instead of a general purpose NLP solver.

Body:
When solving a portfolio optimization problem with an additional 1-norm constraint on the portfolio weights, I faced with convergency problems.

Description of the exercise:

For given N assets with T observations of their returns find the value of 1Norm constraint Theta, such that the last period portfolio return (T-th one) is maximized. That is, solve the problem: min_w w'COVw$ s.t. w1+w2+...+wN=1 and |w1|+|w2|+...+|wN|<=Theta and, out of all values of Theta, choose the one with the maximum value of w'r_T, where r_T is the vector of assets returns in the last period and COV is the variance-covariance matrix of asset returns.

Description of the problem:

First I tried the "naive" approach: with a grid of 0.001 for Theta from 1 to 6 I was going to solve the portfolio optimization problem and compute the last period portfolio return for each Theta. The idea was to choose then the value of Theta with the largest corresponding last period return. However, I noticed that for quite a few values of Theta the solnp function did not converge. The problem occured mostly for small values of Theta: from 1 to 3. For larger values no problems with convergency were detected.

The second approach was to use solnp function twice: first as the function to find Theta and second as the inner part of the objective function. However, I could not find reliable estimates in this way: the values I got did not deliver the optimal solution. Apparently, the objective function is not smooth, but gosolnp function does not find the solution.

The code with data (6 assets with 120 return observations) is provided below. Any suggestions are welcome.

> exp_d
        [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
1     1.3724   0.9081  -0.0695   5.7168   1.9642   1.4222
2     0.6095   1.5075   5.3842   2.7154   2.6838   6.3154
3    -2.6779  -0.1359  -0.4374   1.4287   0.0709  -0.7967
4    -3.5365  -4.3572  -2.0112  -3.5898  -2.3460  -4.0970
5     3.1210   3.6608   2.0944   3.1292   2.8965   3.4614
6     2.7364   1.8411   3.2639   2.9678   2.6067   2.3950
7    -1.0001  -0.3782   3.9316  -0.2621   0.0347   4.4635
8     3.9022   6.3784   6.6192   5.0044   3.5568   8.6305
9    -1.6000  -0.9889  -3.1676   1.3025   0.2071  -2.4764
10   -1.3184   0.8741   3.4796   3.0510  -0.7634  -0.5452
11    5.5482   3.3467  13.3256   5.4076   5.1017   7.4921
12   -1.5484   1.3040  -3.9474  -0.9628  -3.0156  -1.6326
13    4.3331   5.2347   3.9846   9.2369   6.7429   7.2603
14    2.3503  -2.2044   0.8600   3.9191   1.2181  -1.9651
15    2.3981   2.2316   0.3990   5.3864   4.3919   5.9674
16   -0.1633  -2.1458  -5.8357  -3.6349  -4.2840  -6.6219
17   10.4346   8.0620  10.2275   7.0560   6.7676   6.6346
18    5.5505   2.6016   2.4506   2.4954   1.8547   3.4755
19    3.2031   2.7804   3.5948  -0.4774  -0.3667  -2.3168
20   -4.7913  -1.7203  -4.1271  -0.6762  -1.1395  -2.7296
21    7.3930   8.6229   9.4570  12.2800   6.1327   7.8254
22    4.2158  10.6845   9.9723   2.9145   6.0000   4.4979
23    7.5326   1.9540   2.5740   2.6065  -0.1128   0.6388
24   -8.5131  -8.3044  -6.8294  -3.6094  -4.1224  -5.4164
25   -0.4048  -0.4017  -0.8867   1.3590   0.1098   0.9017
26    6.1240   5.0517   3.6990   8.7368   5.3867   6.9468
27    5.7317   4.4538   6.1762   3.4108   1.9153   4.4896
28    6.8299   3.1244   1.6621   1.3590   1.4325   2.0067
29    8.6705  11.1936  12.2831  11.1602  13.2781  13.1497
30    0.9055  -0.5953  -0.6462   0.9332  -0.0008   1.2917
31   -0.0340   1.9379   1.4480   6.5262   4.8373   2.6307
32    0.7414   1.1014   0.3820  -0.5791   0.8306   3.1476
33   -5.9533  -3.4602  -4.1597  -1.3835   2.2098  -0.0642
34   -0.0822   2.7549   0.5136   2.2172   1.1145   2.8362
35  -10.2009  -9.3603 -12.8907  -5.7297  -4.1622  -6.1709
36    6.9673   9.4356   6.4064  12.4593   9.3500   7.5052
37   -0.0681  -0.7029   3.8633   3.5471   6.2018   4.9529
38   -0.8885  -0.4641  -0.4544   7.2353  12.5430   6.9497
39   -4.2569  -4.3105  -3.6218  -4.4211  -4.9685  -6.3175
40  -21.7261 -19.3351 -19.8329 -24.1865 -14.0943 -10.3723
41  -16.4096  -9.8425 -12.3366 -14.2535 -10.9314  -7.6677
42   -2.7511  -2.7249  -1.8488   3.3988   0.5515   1.3170
43    6.2347   9.4395   8.4631   7.1735   3.3113   2.9221
44    1.3502   1.2075   4.3779   3.4639   1.8818   1.2221
45    9.0009  11.0661  10.7647   6.8160   8.3348   5.3573
46   -6.0956  -1.7406  -3.4814  -2.3610  -1.7939  -6.6523
47   -3.7611  -2.3132  -2.9578   0.7061  -2.2643  -1.3650
48  -16.9330 -16.6497 -18.9287 -17.8490 -13.1565 -11.8439
49    6.5208   3.7280   2.5406   4.4017   4.2198   5.2644
50   -3.7646  -1.6135  -2.5073   1.1969  -0.8000  -1.6232
51  -13.6823 -14.6721 -19.1619 -12.0325 -11.7394 -17.0858
52  -10.1007  -7.6801 -10.7443  -9.4278  -7.3264 -11.4835
53    0.2234  -2.7838  -2.6023  -2.3616  -2.8339  -6.6002
54  -10.4236 -11.0266 -17.2866  -5.8057  -9.1776  -9.7245
55    9.9121  11.3602  15.4627   4.7170   6.9823  13.5911
56   13.2032  11.6577  17.0900  12.8706   6.7357  12.1756
57   -4.3440  -2.9204  -6.9601  -4.1971 -10.3577  -8.8826
58  -12.8949 -14.0212 -18.2229  -8.8412 -11.1070 -11.3490
59   -9.6709  -8.7006 -13.8440 -11.3932 -15.9343 -20.3630
60   10.1262   7.7295  20.3174  12.8509  16.1956  25.2657
61   -8.5867  -8.9411  -5.7363  -5.1668 -10.1775 -12.2143
62   -1.6114  -1.1797  -3.7504   0.8986  -1.5948   0.0531
63  -26.5722 -30.0521 -33.8286 -28.8671 -28.1493 -35.1131
64    4.2319   9.2071   5.4593   9.5401   3.2588  11.7214
65   -7.7335  -7.2915  -9.3902  -6.1288 -16.6307 -14.5665
66  -13.7987 -16.5088 -22.4192 -11.5667 -18.8221 -20.6686
67    2.4924   3.9264  10.5116  -3.4347   1.9132   6.6353
68   -2.4754   1.9822   1.3833   7.1142   1.7366   0.3507
69  -10.5259 -12.1366 -10.6244 -10.2031 -15.1403 -14.7460
70  -19.3072 -17.1449 -16.0430 -18.1275 -20.1476 -18.5418
71  -17.1387 -24.8400 -17.4741 -19.2184 -25.9531 -25.4360
72    0.9540   6.2481   1.0364  -1.7110   0.0545   8.8476
73   31.9086  36.1125  63.2475  28.1955  48.6209  67.7847
74   48.7266  55.3725  83.5754  31.3211  50.9661  62.5277
75   -2.8054  -4.5841 -12.4737  -1.0366  -6.5149  -5.0087
76  -16.2535 -19.6450 -23.8672 -10.7514 -17.5126 -23.2272
77   -0.2972  -8.2786 -13.2053  -2.7223  -8.9288 -16.3816
78   -5.1581  -4.2529 -11.0631   6.8503   1.0438  -3.5633
79    4.3896   1.3914   7.8950  -0.0120   3.0297   8.7685
80  -17.8468 -18.4137 -20.8881 -14.9493 -16.5816 -17.3738
81    7.0790   6.1577  16.0332   0.9569   9.8608   6.7577
82   45.4453  54.8024  56.5610  33.7390  51.8933  57.4905
83   59.9378  62.1965  73.3394  16.9717  26.7781  41.6260
84   32.9373  23.3035  18.5882  11.3683  15.5089  21.9496
85  -14.1385 -12.7712  -7.2418  -8.8583 -13.0573  -9.2208
86   10.5585  10.1102   8.2144  10.5958  15.7784  18.8615
87   -7.6121 -13.3352 -20.9042  -9.1454 -12.3603 -19.3866
88   -8.4949 -12.4200 -13.8362  -6.1614 -10.5922 -17.7448
89    4.4492   4.6618   6.1086   9.6900  12.2772  12.6924
90    4.7702   4.0567   0.4565   2.1093   1.8286   3.3536
91   21.5203  28.5643  38.3403   9.8669  16.8246  24.1368
92   -0.2935   1.1796   5.3723  -2.3815  -3.1241  -3.8100
93    4.7722   2.0674  -0.0727  -0.0029  -0.1362  -0.6200
94    2.8356  -1.3170  -1.8303  -1.7780  -2.3152  -4.6160
95   -7.3381  -9.8907 -12.0504  -6.4033  -8.5879 -13.5106
96    3.7672   0.0811  -2.3100   2.6280   2.4811   2.8615
97  -18.0226 -21.5042 -24.4760  -8.3110 -11.7051 -23.1790
98   10.9235   9.4125  12.2230   6.0718   4.4464   5.7691
99   -0.9255  -0.5806  -3.5672  -0.2597  -0.1487  -0.1050
100  -0.9250  -1.6380  -4.1937  -0.4115  -2.7080  -7.3690
101  17.4218  15.4433  12.5284  10.2402   5.0137  10.6573
102   4.9409   1.7554   1.5981   0.7507   0.5333  -2.2372
103  -5.5523  -3.3988  -3.0325  -3.0099  -2.8838  -9.3128
104  -3.5225  -4.8589  -5.8780  -0.8581  -1.6838 -12.9875
105  -5.9234  -7.4692 -11.2668  -2.9715  -3.3289  -7.7499
106   6.7174   9.3484  10.2238   8.0311   9.8871  13.0598
107  -2.4801   2.3317   1.7345   3.1370   4.3390   3.9570
108  -1.7502   5.9262   0.8071   6.3821   5.6136   8.0813
109   9.1528  12.9358  12.7537   6.9882   6.3196  17.1148
110   4.2227   8.6796  14.4462   2.5694   2.2001   3.7475
111   5.0917   5.5331   0.5575   4.6757   0.6768   1.1198
112  10.9064  10.8504   6.8068   6.6016   7.9769   6.0328
113   6.6969  10.4475  18.9743   3.0389   5.6087  14.5739
114   5.7713  10.1556   2.2152   2.9835   5.8064   8.6858
115  10.3194   7.6727  22.3771   3.2881   9.5299  12.2406
116   1.9010   6.5601   6.7824   1.9137   2.8060   7.1039
117   0.5096   2.3380   0.8324   2.6378   0.0632  -1.0088
118 -14.3931 -13.9743 -15.4640  -7.1563  -8.3505 -10.2494
119   4.9011   5.5856   8.6767   5.0578   5.1107   6.5508
120  -2.2080  -0.2588  -1.2498   3.6325   2.1402   0.2676

#define equality constraint function
equal <- function(x) c(sum(x))

#define inequality constraint function
in_inequal <- function(x) c(sum(abs(x)))

#define objective function1
obj_f <- function(x) {

  int_r <- t(x)%*%V_C_M%*%x
  c(as.numeric(int_r))

}

#define objective function2
ex_obj_f <- function(x) {

  tteta <- x

  port_w <- solnp(rep(1/n,n), fun = obj_f, eqfun=equal, eqB=1,
       ineqfun = in_inequal, ineqLB = 0, ineqUB = tteta, control = list(trace=0))

  lp_ret <- exp_d[nrow(exp_d),]%*%port_w$pars

  -lp_ret

}

#First "naive" attempt
exp_d <- as.matrix(exp_d)
n <- 6
V_C_M <- cov(exp_d)

res <- matrix(0:0, nrow = 5000, ncol = 3)

for (i in 1:5000) {

  tteta <- 1 + i*0.001
  port_w <- solnp(rep(1/n,n), fun = obj_f, eqfun=equal, eqB=1,  ineqfun = in_inequal, ineqLB = 0, ineqUB = tteta, control = list(trace=0))
  lp_ret <- exp_d[nrow(exp_d),]%*%port_w$pars

  res[i,1] <- tteta
  res[i,2] <- lp_ret
  res[i,3] <- port_w$convergence

}

#Second Approach (the result really depends on the starting value of the parameter)
tt_op1 <- solnp(pars = 1.5, fun = ex_obj_f, LB = 1, UB = 10, control = list(trace=1))
tt_op2 <- gosolnp(pars = 1.5, fun = ex_obj_f, LB = 1, UB = 10)

P.S. I have read posts with similar problems here, but coud not find a solution to my question.

Body:
Your model can be formulated as a pure QP (quadratic programming) problem instead of a difficult nonlinear problem with a nonlinear non-differentiable constraint.

The constraint

 sum(i, |x(i)|) <= Theta

can be linearized in different ways. One possible reformulation is

 -y(i) <= x(i) <= y(i)
 sum(i, y(i)) <= Theta
 non-negative (or free) variable y(i)

Now you can solve the model with a QP solver instead of a general purpose NLP solver.


来源: stackexchange

问:
How do I get Batch to choose a random number from 0 to 5?
First of all, thank you for reading this.

I am making a fun little program in batch to practice with it and get familiar. I know this may not be the best language to start with, but it's what i'm using.

Here is what I have:

```<code>@echo off
:ask trump

set /p Input= Ask Trump Something (Yes or No questions):

goto random

:random
set /a "rand=%random% %% 6"
goto option%number%

cls

:option0
echo You asked: %Input%
echo Trump: Covfefe
pause
goto ask trump

:option1
echo You asked: %Input%
echo Trump: I dont know, and I dont care.
pause
cls
goto ask trump

option2
echo You asked: %Input%
echo Trump: CHINA
pause
cls
goto ask trump

:option3
echo You asked: %Input%
echo Trump: Build a wall.
pause
cls
goto ask trump

:option4
echo You asked: %Input%
echo Trump: I think so, yes.
pause
cls
goto ask trump

:option5
echo You asked: %Input%
echo Trump: No, I don't think there's a chance.
pause
cls
goto ask trump
</code>```

I want it so that It completely disregards what the user writes and just chooses a random answer. But, whenever I try it, I type in a question, hit enter, and it does nothing. Another input thing pops up without any new text, and it crashes no matter what I type in there. I have tried to find answers on here but I couldn't find something that would work/do what I wanted.

Again, I greatly appreciate any help and I apologize if I wasted your time.

答:
Your main issue is that you set /a rand but then you never use rand as a variable, instead you say goto option%number% which should be `goto option%rand%

Some other things I changed, added cls after :ask trump this way you get rid op the c:\> prompt and is left with a plain cmd screen.
cls was added to the rest of the tags as well so it will look a lot cleaner on screen.

Lastly, the line set /a rand=%random% %%6 will generate a number set between 0 - 5 which is fine as it is 6 numbers regardless, but labelling your options based on real values sounds like a better idea. So if I have 6 answers I want to label them 1 - 6 instead of 0 - 5 therefore it is better to set the random as set /a rand=%random% %%6 +1 The options were updated accordingly as well.

```<code>@echo off
:ask trump
cls
set /p Input= Ask Trump Something (Yes or No questions):

goto random

:random
set /a rand=%random% %%6 +1
goto option%rand%

:option1
cls
echo You asked: %Input%
echo Trump: Covfefe
pause
goto ask trump

:option2
cls
echo You asked: %Input%
echo Trump: I dont know, and I dont care.
pause
cls
goto ask trump

:option3
cls
echo You asked: %Input%
echo Trump: CHINA
pause
cls
goto ask trump

:option4
cls
echo You asked: %Input%
echo Trump: Build a wall.
pause
cls
goto ask trump

:option5
cls
echo You asked: %Input%
echo Trump: I think so, yes.
pause
cls
goto ask trump

:option6
cls
echo You asked: %Input%
echo Trump: No, I don't think there's a chance.
pause
cls
goto ask trump
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First of all, thank you for reading this.

I am making a fun little program in batch to practice with it and get familiar. I know this may not be the best language to start with, but it's what i'm using.

Here is what I have:

@echo off
:ask trump

set /p Input= Ask Trump Something (Yes or No questions):

goto random

:random
set /a "rand=%random% %% 6"
goto option%number%

cls

:option0
echo You asked: %Input%
echo Trump: Covfefe
pause
goto ask trump

:option1
echo You asked: %Input%
echo Trump: I dont know, and I dont care.
pause
cls
goto ask trump

option2
echo You asked: %Input%
echo Trump: CHINA
pause
cls
goto ask trump

:option3
echo You asked: %Input%
echo Trump: Build a wall.
pause
cls
goto ask trump

:option4
echo You asked: %Input%
echo Trump: I think so, yes.
pause
cls
goto ask trump

:option5
echo You asked: %Input%
echo Trump: No, I don't think there's a chance.
pause
cls
goto ask trump

I want it so that It completely disregards what the user writes and just chooses a random answer. But, whenever I try it, I type in a question, hit enter, and it does nothing. Another input thing pops up without any new text, and it crashes no matter what I type in there. I have tried to find answers on here but I couldn't find something that would work/do what I wanted.

Again, I greatly appreciate any help and I apologize if I wasted your time.

Body:
Your main issue is that you set /a rand but then you never use rand as a variable, instead you say goto option%number% which should be `goto option%rand%

Some other things I changed, added cls after :ask trump this way you get rid op the c:\> prompt and is left with a plain cmd screen.
cls was added to the rest of the tags as well so it will look a lot cleaner on screen.

Lastly, the line set /a rand=%random% %%6 will generate a number set between 0 - 5 which is fine as it is 6 numbers regardless, but labelling your options based on real values sounds like a better idea. So if I have 6 answers I want to label them 1 - 6 instead of 0 - 5 therefore it is better to set the random as set /a rand=%random% %%6 +1 The options were updated accordingly as well.

@echo off
:ask trump
cls
set /p Input= Ask Trump Something (Yes or No questions):

goto random

:random
set /a rand=%random% %%6 +1
goto option%rand%

:option1
cls
echo You asked: %Input%
echo Trump: Covfefe
pause
goto ask trump

:option2
cls
echo You asked: %Input%
echo Trump: I dont know, and I dont care.
pause
cls
goto ask trump

:option3
cls
echo You asked: %Input%
echo Trump: CHINA
pause
cls
goto ask trump

:option4
cls
echo You asked: %Input%
echo Trump: Build a wall.
pause
cls
goto ask trump

:option5
cls
echo You asked: %Input%
echo Trump: I think so, yes.
pause
cls
goto ask trump

:option6
cls
echo You asked: %Input%
echo Trump: No, I don't think there's a chance.
pause
cls
goto ask trump


问:
filter results in an array of objects just like operator(%oil%) using lodash
I want to filter array of objects based on the input change by the user and create a new array of matched array of objects using LODASH (https://lodash.com/).

```<code>let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];
</code>```

I have tried lodash _.filter but this filters exact words and exact case and then return that single searched value.

```<code>const filtered = _.filter(listing, function(o) {
        return o.title === "oi";
      });
      console.log(filtered);
</code>```

I want to get results just like we do in mysql as:

```<code>WHERE title like %oi%
</code>```

and it gives matched values which contained that input.

Thanks

答:
see the snippet,
used to lowerCase to match all string in upper and lower case,
in your example, your string "Oil & Gas" is in Camel case and when you try to match the string it will always result in blank array.

let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];
const filtered = _.filter(listing, function(o) {
  return o.title.toLowerCase().indexOf("oi") > -1;
});
console.log(filtered);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Body:
I want to filter array of objects based on the input change by the user and create a new array of matched array of objects using LODASH (https://lodash.com/).

let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];

I have tried lodash _.filter but this filters exact words and exact case and then return that single searched value.

const filtered = _.filter(listing, function(o) {
        return o.title === "oi";
      });
      console.log(filtered);

I want to get results just like we do in mysql as:

WHERE title like %oi%

and it gives matched values which contained that input.

Thanks

Body:
see the snippet,
used to lowerCase to match all string in upper and lower case,
in your example, your string "Oil & Gas" is in Camel case and when you try to match the string it will always result in blank array.

let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];
const filtered = _.filter(listing, function(o) {
  return o.title.toLowerCase().indexOf("oi") > -1;
});
console.log(filtered);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
Remove array from multidimentional array using id in php
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

```<code>Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)
</code>```

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

```<code>foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }
</code>```

答:
Is the function getData() returning a copy of the array or a reference? If is is only a copy the unset($collection->getData()[$key]) won't work.

Better you loop over the array as you do, but store all keys you want to delete in side a other array (e.g. $keysToRemove). When the for-each-loop is finished you start to loop the new array $keysToRemove containing all the keys you want to remove and remove then from array.

```<code>$keysToRemove = array();
$data = $collection->getData(); // copy or reference?
foreach ($data as $key => $value) {
  if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
    echo $value['id'].'<br>';
    break; // exit the loop? If you want to jump to the next element use "continue"
  }
  echo $value['field_id'].'<br>';
  echo $value['value'].'<br>';
  if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
    $keysToRemove[$key]   = true;
    $keysToRemove[$key-1] = true;
  }
}

foreach(array_keys($keysToRemove) as $key){
  echo '<p>remove key '.$key.' with content ```'.print_r($data[$key], true).'```</p>';
  unset($data[$key]);
}

echo '<p>Result array is```'.print_r($data, true).'```</p>';
</code>```

So you don't manipulate the array your loop use at the moment.

Body:
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }

Body:
Is the function getData() returning a copy of the array or a reference? If is is only a copy the unset($collection->getData()[$key]) won't work.

Better you loop over the array as you do, but store all keys you want to delete in side a other array (e.g. $keysToRemove). When the for-each-loop is finished you start to loop the new array $keysToRemove containing all the keys you want to remove and remove then from array.

$keysToRemove = array();
$data = $collection->getData(); // copy or reference?
foreach ($data as $key => $value) {
  if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
    echo $value['id'].'<br>';
    break; // exit the loop? If you want to jump to the next element use "continue"
  }
  echo $value['field_id'].'<br>';
  echo $value['value'].'<br>';
  if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
    $keysToRemove[$key]   = true;
    $keysToRemove[$key-1] = true;
  }
}

foreach(array_keys($keysToRemove) as $key){
  echo '<p>remove key '.$key.' with content <pre>'.print_r($data[$key], true).'</pre></p>';
  unset($data[$key]);
}

echo '<p>Result array is<pre>'.print_r($data, true).'</pre></p>';

So you don't manipulate the array your loop use at the moment.


问:
Why does MySQL return duplicate information in the returned JOIN array?
I'm wondering if I'm doing something wrong, or if this is just a quirk in how everything is processed in MySQL. Here's the setup: (I can't seem to find this exact topic anywhere else)

I have two tables order and menu.

menu has an 'id' (for the item), an 'item' and three prices ('prc1' 'prc2' 'prc3') in each row.

```<code>menu +----+----------+------+------+------+
     |'id'|  'item'  |'prc1'|'prc2'|'prc3'|
     +----+----------+------+------+------+
     |  1 | 'tshirt' | 3.00 | 4.50 | 4.00 |
     |  2 | 'socks'  | 1.00 | 2.50 | 2.00 |
     +----+----------+------+------+------+
</code>```

order also has an item id to match against the order menu, ('i_id'), and an integer I use for filtering the prices later in php ('prc_id').

```<code>order +------+--------+
      |'i_id'|'prc_id'|
      +--------+------+
      |  1   |   1    | # i_id matches id - tshirt and informs to use prc1
      |  2   |   3    | # i_id matchis id - socks and uses prc3
      +--------+------+
</code>```

I use JOIN to match the orders up to the items

```<code>"SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
        FROM order
        LEFT JOIN menu
        ON order.i_id = menu.id"
</code>```

I then get the result back, and initially to make sure everything panned out, I printed the array:

```<code>$result = mysql_query($query)
while($row = mysql_fetch_array($result))
    {
        print_r($row);
    }
</code>```

This is the array I get back (obviously dummy info for the initial tests):

```<code>Array
 (
    [0] => 1 [prc_id] => 1         #the value (1) for 'prc_id' is given twice
    [1] => tshirt [item] => tshirt #the value (tshirt) for 'item' is given twice
    [2] => 3.00 [prc1] => 3.00     #the value (3.00) for 'prc1' is given twice
    [3] => 4.50 [prc2] => 4.50     #etc
    [4] => 4.00 [prc3] => 4.00

    [0] => 3 [prc_id] => 3
    [1] => socks [item] => socks
    [2] => 1.00 [prc1] => 1.00
    [3] => 2.50 [prc2] => 2.50
    [4] => 2.00 [prc3] => 2.00
 )
</code>```

So my question(finally, right? xD)... Why is duplicate data sent back in the array response?

Have I done something wrong? Am I overlooking something?

It's not a huge issue, it doesn't affect my end result, I'd just like to be as precise as possible.

Thank you for your time. :)

答:
```<code>     SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
     FROM order
      LEFT JOIN menu
      ON order.i_id = menu.id
</code>```

It looks like you are joining based on the item_id in order and id of menu, while you should be doing based on (if I understand correctly) the item_id of menu.

Something like:

```<code>     SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
     FROM order
      LEFT JOIN menu
      ON order.i_id = menu.item_id
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm wondering if I'm doing something wrong, or if this is just a quirk in how everything is processed in MySQL. Here's the setup: (I can't seem to find this exact topic anywhere else)

I have two tables order and menu.

menu has an 'id' (for the item), an 'item' and three prices ('prc1' 'prc2' 'prc3') in each row.

menu +----+----------+------+------+------+
     |'id'|  'item'  |'prc1'|'prc2'|'prc3'|
     +----+----------+------+------+------+
     |  1 | 'tshirt' | 3.00 | 4.50 | 4.00 |
     |  2 | 'socks'  | 1.00 | 2.50 | 2.00 |
     +----+----------+------+------+------+

order also has an item id to match against the order menu, ('i_id'), and an integer I use for filtering the prices later in php ('prc_id').

order +------+--------+
      |'i_id'|'prc_id'|
      +--------+------+
      |  1   |   1    | # i_id matches id - tshirt and informs to use prc1
      |  2   |   3    | # i_id matchis id - socks and uses prc3
      +--------+------+

I use JOIN to match the orders up to the items

"SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
        FROM order
        LEFT JOIN menu
        ON order.i_id = menu.id"

I then get the result back, and initially to make sure everything panned out, I printed the array:

$result = mysql_query($query)
while($row = mysql_fetch_array($result))
    {
        print_r($row);
    }

This is the array I get back (obviously dummy info for the initial tests):

Array
 (
    [0] => 1 [prc_id] => 1         #the value (1) for 'prc_id' is given twice
    [1] => tshirt [item] => tshirt #the value (tshirt) for 'item' is given twice
    [2] => 3.00 [prc1] => 3.00     #the value (3.00) for 'prc1' is given twice
    [3] => 4.50 [prc2] => 4.50     #etc
    [4] => 4.00 [prc3] => 4.00

    [0] => 3 [prc_id] => 3
    [1] => socks [item] => socks
    [2] => 1.00 [prc1] => 1.00
    [3] => 2.50 [prc2] => 2.50
    [4] => 2.00 [prc3] => 2.00
 )

So my question(finally, right? xD)... Why is duplicate data sent back in the array response?

Have I done something wrong? Am I overlooking something?

It's not a huge issue, it doesn't affect my end result, I'd just like to be as precise as possible.

Thank you for your time. :)

Body:
     SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
     FROM order
      LEFT JOIN menu
      ON order.i_id = menu.id

It looks like you are joining based on the item_id in order and id of menu, while you should be doing based on (if I understand correctly) the item_id of menu.

Something like:

     SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
     FROM order
      LEFT JOIN menu
      ON order.i_id = menu.item_id


问:
Adding the quantities of products in a dataframe column in Python
I'm trying to calculate the sum of weights in a column of an excel sheet that contains the product title with the help of Numpy/Pandas. I've already managed to load the sheet into a dataframe, and isolate the rows that contain the particular product that I'm looking for:

```<code>dframe = xlsfile.parse('Sheet1')
dfFent = dframe[dframe['Product:'].str.contains("ABC") == True]
</code>```

But, I can't seem to find a way to sum up its weights, due to the obvious complexity of the problem (as shown below). For eg. if the column 'Product Title' contains values like -

1 gm ABC

98% pure 12 grams ABC

0.25 kg ABC Powder

ABC 5gr

where, ABC is the product whose weight I'm looking to add up. Is there any way that I can add these weights all up to get a total of 268 gm. Any help or resources pointing to the solution would be highly appreciated. Thanks! :)

答:
You need to do some data wrangling to get the column consistent in same format. You may do some matching and try to get Product column aligned and consistent, similar to date -time formatting.

Like you may do the following things.

Make a separate column with only values(float)

Change % value to decimal and multiply by quantity

Replace value with kg to grams

Without any string, only float column to get total.

Pandas can work well with this problem.

Note: There is no shortcut to this problem, you need to get rid of strings mixed with decimal values for calculation of sum.

Body:
I'm trying to calculate the sum of weights in a column of an excel sheet that contains the product title with the help of Numpy/Pandas. I've already managed to load the sheet into a dataframe, and isolate the rows that contain the particular product that I'm looking for:

dframe = xlsfile.parse('Sheet1')
dfFent = dframe[dframe['Product:'].str.contains("ABC") == True]

But, I can't seem to find a way to sum up its weights, due to the obvious complexity of the problem (as shown below). For eg. if the column 'Product Title' contains values like -

1 gm ABC

98% pure 12 grams ABC

0.25 kg ABC Powder

ABC 5gr

where, ABC is the product whose weight I'm looking to add up. Is there any way that I can add these weights all up to get a total of 268 gm. Any help or resources pointing to the solution would be highly appreciated. Thanks! :)


问:
Azure Function Targeting .NET Standard Showing Warning
Just installed Visual Studio 15.5 Preview so that I can create an Azure Function targeting .NET Core. Without making any changes, I'm seeing a warning -- see below -- that reads:

Package Microsoft.AspNet.WebApi.Client 5.2.2 was restored using .NET
  Framework version 4.6.1 instead of the project target framework .NET
  Standard version 2.0. This package may not be fully compatible with
  your project.

Any idea how to fix this or do I ignore this warning? As I said, this is a brand new Azure Function project I created with no changes at all.

Here's what the warning looks like:

答: Yes, you did nothing wrong: this is to be expected for now. Functions v2 are in beta now, so you'd have to live with this warning for a while. It should give you no functional issues.</p>


问:
Zxing Scanner App, How to show a result as a yes or no?
Using zxing on Android Studio with empty activity and 4.4 KitKat. I would like to show the result as a yes or no. I would like to reference a google sheet with the UPC codes. If the UPC is in the spreadsheet already then show "YES" or if the UPC is not in the spreadsheet show "NO". Can I use an "If, Else" in the MainActivity java code using only the UPC column on the google sheet?

```<code>@Override
        protected void onActivityResult ( int requestCode, int resultCode, Intent data){
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Log.d("MainActivity", "Cancelled scan");
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    Log.d("MainActivity", "Scanned");
                    Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
</code>```

I want to show this code as a "Yes" or "NO" based on if the scanned barcode is already in the spreadsheet. My question is how to get the spreadsheet to communicate with the scanner or can copy all of the barcodes from the spreadsheet in a boolean?

```<code>Set<String> getStringSet (String key,
            Set<String> defValues)

makeText(Context context, int resId, int duration)

protected void onActivityResult ( int requestCode, int resultCode, Intent data){
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Log.d("MainActivity", "Cancelled scan");
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    Log.d("MainActivity", "Scanned");
                    Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                }
</code>```

So above is what ive come up with from search. Is it practical to use shared preference to store my data(1000 UPC) use ZXING to parse as well as IF ELSE to check the code and finally TOAST to show "YES" or "NO" based on if my result is located in the shared preference?

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = this.findViewById(R.id.button);
    final Activity activity = this;
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            IntentIntegrator integrator = new IntentIntegrator(activity);
            integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
            integrator.setPrompt("Scan");
            integrator.setCameraId(0);
            integrator.setBeepEnabled(false);
            integrator.setBarcodeImageEnabled(false);
            integrator.initiateScan();
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        if (result.getContents() == null) {
            Log.d("MainActivity", "Cancelled scan");
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            Log.d("MainActivity", "Scanned");
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

public void scanCode(View view) {
}

public class myWebView extends MainActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WebView webview = new WebView(this);
        setContentView(webview);

        WebView myWebView = findViewById(R.id.myWebView);

        myWebView.setWebViewClient(new MyWebViewClient());

        WebSettings webSettings = myWebView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webview.loadUrl("https://google.com/");
    }

    private class MyWebViewClient extends WebViewClient {

        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

            startActivity(intent);

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

}

答:
for segregation of code you need to create SacnActivity as a separate activity which is extend Activity and impliments ZXingScannerView.ResultHandler and call from the MainActivity and give call back to Mainactivity in onActivityResult().

MainActivity

```<code>public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scan = (Button)findViewById(R.id.btnScan);

        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivityForResult(new Intent(MainActivity.this,SacnActivity .class),1);

            }
        });

    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                String result=data.getStringExtra("result");
                Log.d("result================>",""+result);

                try {
                    //processData(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultCode == Activity.RESULT_CANCELED) {
</code>```

Body:
Using zxing on Android Studio with empty activity and 4.4 KitKat. I would like to show the result as a yes or no. I would like to reference a google sheet with the UPC codes. If the UPC is in the spreadsheet already then show "YES" or if the UPC is not in the spreadsheet show "NO". Can I use an "If, Else" in the MainActivity java code using only the UPC column on the google sheet?

@Override
        protected void onActivityResult ( int requestCode, int resultCode, Intent data){
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Log.d("MainActivity", "Cancelled scan");
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    Log.d("MainActivity", "Scanned");
                    Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);

I want to show this code as a "Yes" or "NO" based on if the scanned barcode is already in the spreadsheet. My question is how to get the spreadsheet to communicate with the scanner or can copy all of the barcodes from the spreadsheet in a boolean?

Set<String> getStringSet (String key,
            Set<String> defValues)

makeText(Context context, int resId, int duration)

protected void onActivityResult ( int requestCode, int resultCode, Intent data){
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Log.d("MainActivity", "Cancelled scan");
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    Log.d("MainActivity", "Scanned");
                    Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                }

So above is what ive come up with from search. Is it practical to use shared preference to store my data(1000 UPC) use ZXING to parse as well as IF ELSE to check the code and finally TOAST to show "YES" or "NO" based on if my result is located in the shared preference?

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = this.findViewById(R.id.button);
    final Activity activity = this;
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            IntentIntegrator integrator = new IntentIntegrator(activity);
            integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
            integrator.setPrompt("Scan");
            integrator.setCameraId(0);
            integrator.setBeepEnabled(false);
            integrator.setBarcodeImageEnabled(false);
            integrator.initiateScan();
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        if (result.getContents() == null) {
            Log.d("MainActivity", "Cancelled scan");
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            Log.d("MainActivity", "Scanned");
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

public void scanCode(View view) {
}

public class myWebView extends MainActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WebView webview = new WebView(this);
        setContentView(webview);

        WebView myWebView = findViewById(R.id.myWebView);

        myWebView.setWebViewClient(new MyWebViewClient());

        WebSettings webSettings = myWebView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webview.loadUrl("https://google.com/");
    }

    private class MyWebViewClient extends WebViewClient {

        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

            startActivity(intent);

            return true;
        }
    }
}

}

Body:
for segregation of code you need to create SacnActivity as a separate activity which is extend Activity and impliments ZXingScannerView.ResultHandler and call from the MainActivity and give call back to Mainactivity in onActivityResult().

MainActivity

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scan = (Button)findViewById(R.id.btnScan);

        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivityForResult(new Intent(MainActivity.this,SacnActivity .class),1);

            }
        });

    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                String result=data.getStringExtra("result");
                Log.d("result================>",""+result);

                try {
                    //processData(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultCode == Activity.RESULT_CANCELED) {


问:
dynamic script not parsing correctly
I basically trying to create a dynamic sql script that should do the following

```<code>IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('FinData2000_1') AND NAME = 'idx_FinData2000_1')
            drop  index idx_FinData2000_1 on FinData2000_1
</code>```

Following is the dynamic script that is not parsing

```<code>SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('
            + @tableName + '') AND NAME =  'idx_' + @tableName + '
            drop  index' + @tableName + '.idx_' + @tableName;
</code>```

答:
Dynamic query

```<code>declare @tablename varchar(100) = 'tablename'
declare @indexname varchar (100) = 'indexname'
declare @query varchar(max) = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('+@tablename+') AND NAME = '+@indexname+')
            drop  index '+@indexname+' on '+@tablename+''
</code>```

works for any table and index name you pass

Title: dynamic script not parsing correctly

Body:
I basically trying to create a dynamic sql script that should do the following

IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('FinData2000_1') AND NAME = 'idx_FinData2000_1')
            drop  index idx_FinData2000_1 on FinData2000_1

Following is the dynamic script that is not parsing

SET @sql = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('
            + @tableName + '') AND NAME =  'idx_' + @tableName + '
            drop  index' + @tableName + '.idx_' + @tableName;

Body:
Dynamic query

declare @tablename varchar(100) = 'tablename'
declare @indexname varchar (100) = 'indexname'
declare @query varchar(max) = 'IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id('+@tablename+') AND NAME = '+@indexname+')
            drop  index '+@indexname+' on '+@tablename+''

works for any table and index name you pass


问:
Does Perl initialize variables in a sub that returns nothing before the declaration of the variables
```<code>sub Thing {
  my $self = shift;
  if ($self->{validationTest} != 1) {return;}

  my $data = 'Hello, World!';
  return $data;
}
</code>```

What happens to $data if the IF conditional is true and the sub is returned early?

答:
[You ask when the initialization of the variable occurs, but I think you are talking about the assignment of the string Hello, World! to $data. I'm answering that.]

The assignment occurs when the assignment is evaluated, which is never if the sub returns before reaching the assignment.

Body:
sub Thing {
  my $self = shift;
  if ($self->{validationTest} != 1) {return;}

  my $data = 'Hello, World!';
  return $data;
}

What happens to $data if the IF conditional is true and the sub is returned early?


问:
The performance (or other) differences between raw Socket and UdpClient?
As we know .Net has UdpClient for simple Socket usage for UDP.

From MSDN:

If you are writing a relatively simple application and do not require maximum performance, consider using TcpClient, TcpListener, and UdpClient. These classes provide a simpler and more user-friendly interface to Socket communications.

I am wondering how much performance differences between Raw Socket and UdpClient? I know UdpClient is a wrapper of socket for Udp and it does not have asynchron read/write.

Anything else?

Thanks

答:
sendfile is not faster.

```<code>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Cache;
using System.Threading;

namespace socket_sendfile
{
    delegate TimeSpan SendFileDelegate(Socket client, String filename, long fileSize);

    class Header
    {
        public long FileSize { get; set; }
        public int FileNumber { get; set; }

        public void Serialize(Stream stream)
        {
            byte[] buffer = BitConverter.GetBytes(this.FileNumber);
            stream.Write(buffer, 0, buffer.Length);

            buffer = BitConverter.GetBytes(this.FileSize);
            stream.Write(buffer, 0, buffer.Length);
        }

        public static Header Deserialize(Stream stream)
        {
            Header header = new Header();

            byte[] buffer = new byte[4];
            int read = stream.Read(buffer, 0, buffer.Length);
            header.FileNumber = BitConverter.ToInt32(buffer, 0);

            buffer = new byte[sizeof(long)];
            read = stream.Read(buffer, 0, buffer.Length);
            header.FileSize = BitConverter.ToInt64(buffer, 0);
            return header;
        }
    }

    class Program
    {
        private Random rand = new Random();

        static void Main(string[] args)
        {
            Program prog = new Program();

            try
            {
                prog.StartServer();

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    client.Bind(new IPEndPoint(0, 0));
                    client.Connect(new IPEndPoint(IPAddress.Loopback, 8080));

                    prog.Run(client, new SendFileDelegate(prog.SendFile1));

                    Console.WriteLine();
                    prog.Run(client, new SendFileDelegate(prog.SendFile2));
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
            Console.ReadKey();
        }

        void StartServer()
        {
            Thread serverThread = new Thread(new ThreadStart(this.Server));
            serverThread.Start();
        }

        void Run(Socket client, SendFileDelegate sendFileMethod)
        {
            foreach (long size in this.GetNextSize())
            {
                String filename = Path.GetTempFileName();

                this.CreateFile(filename, size);

                for (int i = 0; i  GetNextSize()
        {
            ulong[] sizes = { 1024, 4096, 8192, 16385, 65536, 1048576 };
            for (int i = 0; i  0)
                {
                    rand.NextBytes(buffer);
                    int writeSize = buffer.Length;
                    if (writeSize > (int)remaining)
                    {
                        writeSize = (int)remaining;
                    }

                    bw.Write(buffer, 0, writeSize);
                    remaining -= writeSize;
                }
            }
        }

        TimeSpan SendFile1(Socket client, String filename, long fileSize)
        {
            Stopwatch timer = new Stopwatch();

            //timer.Start();
            using (NetworkStream ns = new NetworkStream(client))
            {
                Header header = new Header();
                header.FileSize = fileSize;
                header.FileNumber = 1;

                // send the header
                header.Serialize(ns);

                using (FileStream fs = File.OpenRead(filename))
                {
                    //byte[] buffer = new byte[1024];
                    byte[] buffer = new byte[fileSize];
                    int read = fs.Read(buffer, 0, buffer.Length);
                    //Console.WriteLine("read = " + read);

                    while (read > 0)
                    {
                        timer.Start();
                        ns.Write(buffer, 0, read);
                        timer.Stop();
                        read = fs.Read(buffer, 0, buffer.Length);
                        //Console.WriteLine("read = " + read);
                    }
                }
            }

            //timer.Stop();

            return timer.Elapsed;
        }

        TimeSpan SendFile2(Socket client, String filename, long fileSize)
        {
            Stopwatch timer = new Stopwatch();

            //timer.Start();
            using (NetworkStream ns = new NetworkStream(client))
            {
                Header header = new Header();
                header.FileSize = fileSize;
                header.FileNumber = 1;

                byte[] headerBuffer = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    header.Serialize(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    headerBuffer = ms.ToArray();
                }

                // send the header
                timer.Start();
                client.SendFile(filename, headerBuffer, null, TransmitFileOptions.UseDefaultWorkerThread);
                timer.Stop();
            }

            //timer.Stop();

            return timer.Elapsed;
        }

        void Server()
        {
            byte[] buffer = new byte[1024];
            try
            {
                TcpListener listener = new TcpListener(IPAddress.Loopback, 8080);
                listener.Start();
                using (TcpClient client = listener.AcceptTcpClient())
                using (NetworkStream ns = client.GetStream())
                {
                    bool hasData = true;
                    while (hasData)
                    {
                        // first get the header. Header has the file size.
                        Header header = Header.Deserialize(ns);

                        long remaining = header.FileSize;

                        while (remaining > 0)
                        {
                            int readSize = buffer.Length;
                            if ((long)readSize > remaining)
                                readSize = (int)remaining;

                            int read = ns.Read(buffer, 0, readSize);
                            remaining -= read;
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }
    }
}
</code>```

wasted couple hours of my precious time.

Body:
sendfile is not faster.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Cache;
using System.Threading;

namespace socket_sendfile
{
    delegate TimeSpan SendFileDelegate(Socket client, String filename, long fileSize);

    class Header
    {
        public long FileSize { get; set; }
        public int FileNumber { get; set; }

        public void Serialize(Stream stream)
        {
            byte[] buffer = BitConverter.GetBytes(this.FileNumber);
            stream.Write(buffer, 0, buffer.Length);

            buffer = BitConverter.GetBytes(this.FileSize);
            stream.Write(buffer, 0, buffer.Length);
        }

        public static Header Deserialize(Stream stream)
        {
            Header header = new Header();

            byte[] buffer = new byte[4];
            int read = stream.Read(buffer, 0, buffer.Length);
            header.FileNumber = BitConverter.ToInt32(buffer, 0);

            buffer = new byte[sizeof(long)];
            read = stream.Read(buffer, 0, buffer.Length);
            header.FileSize = BitConverter.ToInt64(buffer, 0);
            return header;
        }
    }

    class Program
    {
        private Random rand = new Random();

        static void Main(string[] args)
        {
            Program prog = new Program();

            try
            {
                prog.StartServer();

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    client.Bind(new IPEndPoint(0, 0));
                    client.Connect(new IPEndPoint(IPAddress.Loopback, 8080));

                    prog.Run(client, new SendFileDelegate(prog.SendFile1));

                    Console.WriteLine();
                    prog.Run(client, new SendFileDelegate(prog.SendFile2));
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
            Console.ReadKey();
        }

        void StartServer()
        {
            Thread serverThread = new Thread(new ThreadStart(this.Server));
            serverThread.Start();
        }

        void Run(Socket client, SendFileDelegate sendFileMethod)
        {
            foreach (long size in this.GetNextSize())
            {
                String filename = Path.GetTempFileName();

                this.CreateFile(filename, size);

                for (int i = 0; i  GetNextSize()
        {
            ulong[] sizes = { 1024, 4096, 8192, 16385, 65536, 1048576 };
            for (int i = 0; i  0)
                {
                    rand.NextBytes(buffer);
                    int writeSize = buffer.Length;
                    if (writeSize > (int)remaining)
                    {
                        writeSize = (int)remaining;
                    }

                    bw.Write(buffer, 0, writeSize);
                    remaining -= writeSize;
                }
            }
        }

        TimeSpan SendFile1(Socket client, String filename, long fileSize)
        {
            Stopwatch timer = new Stopwatch();

            //timer.Start();
            using (NetworkStream ns = new NetworkStream(client))
            {
                Header header = new Header();
                header.FileSize = fileSize;
                header.FileNumber = 1;

                // send the header
                header.Serialize(ns);

                using (FileStream fs = File.OpenRead(filename))
                {
                    //byte[] buffer = new byte[1024];
                    byte[] buffer = new byte[fileSize];
                    int read = fs.Read(buffer, 0, buffer.Length);
                    //Console.WriteLine("read = " + read);

                    while (read > 0)
                    {
                        timer.Start();
                        ns.Write(buffer, 0, read);
                        timer.Stop();
                        read = fs.Read(buffer, 0, buffer.Length);
                        //Console.WriteLine("read = " + read);
                    }
                }
            }

            //timer.Stop();

            return timer.Elapsed;
        }

        TimeSpan SendFile2(Socket client, String filename, long fileSize)
        {
            Stopwatch timer = new Stopwatch();

            //timer.Start();
            using (NetworkStream ns = new NetworkStream(client))
            {
                Header header = new Header();
                header.FileSize = fileSize;
                header.FileNumber = 1;

                byte[] headerBuffer = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    header.Serialize(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    headerBuffer = ms.ToArray();
                }

                // send the header
                timer.Start();
                client.SendFile(filename, headerBuffer, null, TransmitFileOptions.UseDefaultWorkerThread);
                timer.Stop();
            }

            //timer.Stop();

            return timer.Elapsed;
        }

        void Server()
        {
            byte[] buffer = new byte[1024];
            try
            {
                TcpListener listener = new TcpListener(IPAddress.Loopback, 8080);
                listener.Start();
                using (TcpClient client = listener.AcceptTcpClient())
                using (NetworkStream ns = client.GetStream())
                {
                    bool hasData = true;
                    while (hasData)
                    {
                        // first get the header. Header has the file size.
                        Header header = Header.Deserialize(ns);

                        long remaining = header.FileSize;

                        while (remaining > 0)
                        {
                            int readSize = buffer.Length;
                            if ((long)readSize > remaining)
                                readSize = (int)remaining;

                            int read = ns.Read(buffer, 0, readSize);
                            remaining -= read;
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }
    }
}

wasted couple hours of my precious time.


问:
Error in QueryExpression with PartyList
I'm trying to retrieve appointments whose "requiredattendees" contains on one of entities from account list. requiredattendees have a type of PartyList.
My query looks like:

```<code>var query = new QueryExpression("appointment")
{
      ColumnSet = columnSet,
      Criteria = new FilterExpression(LogicalOperator.Or)
};
</code>```

And adding conditions :

```<code>GetAccounts()
.Select(a => new ConditionExpression("requiredattendees", ConditionOperator.Contains, a.Id))
.ForEach(c => query.Criteria.AddCondition(c));

a.Id is the account guid.
</code>```

I'm getting following error:

```<code>Cannot add attribute requiredattendees of type partylist in a condition
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral]]
</code>```

答:
```<code>QueryExpression query = new QueryExpression(LetterEntityAttributeNames.EntityName)
                {
                    ColumnSet = new ColumnSet(new string[]
                        {
                            LetterEntityAttributeNames.SubjectFieldName,
                            LetterEntityAttributeNames.RegardingObjectId,
                            LetterEntityAttributeNames.ToFieldName
                        }),
                    Criteria = new FilterExpression
                    {
                        FilterOperator = LogicalOperator.And,
                        Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = LetterEntityAttributeNames.DirectChannelTypeFieldName,
                                    Operator = ConditionOperator.Equal,
                                    Values =
                                    {
                                        DirectChannelType
                                    }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = LetterEntityAttributeNames.RegardingObjectId,
                                    Operator = ConditionOperator.Equal,
                                    Values =
                                    {
                                        RegardingId
                                    }
                                }
                            }
                    },
                    LinkEntities =
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName = ActivityPointerEntityAttributeNames.EntityName,
                                LinkFromAttributeName = ActivityPartyAttributeNames.ActivityId,
                                LinkToEntityName = ActivityPartyAttributeNames.EntityName,
                                LinkToAttributeName = CampaignActivityAttributeNames.Id,
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = ActivityPointerAttributeNames.PartyIdField,
                                            Operator = ConditionOperator.Equal,
                                            Values =
                                            {
                                                ToEntityGuid
                                            }
                                        }
                                    }
                                }
                            }
                        }
                };
</code>```

Title: Error in QueryExpression with PartyList

Body:
I'm trying to retrieve appointments whose "requiredattendees" contains on one of entities from account list. requiredattendees have a type of PartyList.
My query looks like:

var query = new QueryExpression("appointment")
{
      ColumnSet = columnSet,
      Criteria = new FilterExpression(LogicalOperator.Or)
};

And adding conditions :

GetAccounts()
.Select(a => new ConditionExpression("requiredattendees", ConditionOperator.Contains, a.Id))
.ForEach(c => query.Criteria.AddCondition(c));

a.Id is the account guid.

I'm getting following error:

Cannot add attribute requiredattendees of type partylist in a condition
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral]]


问:
Unable to create functional app bundle on Sierra using py2app and python 3.6.2
I'm using python 3.6.2 with pyenv and homebrew on Mac OS Sierra and i've been unable to create functional bundle apps with py2app v0.14 and pyinstaller v3.2.1.

ActiveTcl version 8.5.18/tkinter are installed.

Standard 2.7.10 Mac version of python doesn't do much else. I actually managed to make one or two attempts to work on python 2.7.10 with other programs, but since i want to use 3.6.2 there's no point to stay on standard.

py2app creates an .app file that just gives "error" and Mac asks to terminate. pyinstaller doesn't even create an .app file. I followed all the instructions in all the programs.

py2app gives me this message at the end when creating the .app:

```<code>Modules not found (unconditional imports):

 * com (com.sun.jna)
 * com.jna (com.sun)
 * com.sun (com.sun.jna.platform)
 * ordereddict (pkg_resources._vendor.pyparsing)
 * win32com (win32com)
 * win32com.shell (win32com.shell)
 * win32com.shellcon (win32com.shell)

Modules not found (conditional imports):

 * StringIO (pkg_resources._vendor.six)
 * com (pkg_resources._vendor.appdirs)
 * com.sun.jna (pkg_resources._vendor.appdirs)
 * com.sun.jna.platform (pkg_resources._vendor.appdirs)
 * win32com (pkg_resources._vendor.appdirs)
 * win32com.shell (pkg_resources._vendor.appdirs)
</code>```

I checked for missing modules and for me it doesn't look like the program is trying to use any module listed above.

I retrieved the program from the internet, it's a simple test program, here's the script:

```<code>from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = float(feet.get())
        meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass

root = Tk()
root.title("Feet to Meters")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

feet = StringVar()
meters = StringVar()

feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)

ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()
</code>```

I've tried uninstalling and reinstalling python, ActiveTcl, i've run brew doctor, nothing seems to work. Pyenv is working fine. Homebrew is working fine.

I've searched everywhere for two days, and no matter what i do every time py2app creates the .app file it only gives "Error".

The app runs perfectly when i run through IDLE. What problem can it be???

EDIT: After sometime working this out i found a solution for python 3.6.2 using cx_freeze. Py2app only worked with Python 2.7.10 as i told before. For some reason Py2app only load the missing modules i mentioned earlier when running with python 2.7.10, when python 3.6.2 comes in he fails to load the modules and the .app file don't work properly.

答:
After my own 'pyjinks' with py2app I found a few things that might relate.

First of all, your problem with 'error' sounds like an issue that I experienced when my app file was sync'd (via a dropbox style service) to another computer.  The file would run fine on the computer that created it but I would get an error that it couldn't be opened when I tried to run it on the remote computer.  BUT, if  I uploaded the app file via google drive and then downloaded it to the remote computer, it would open and run fine!!  So, after poking around I found that the python script inside the app bundle on this remote computer didn't have execution permissions.  After running 'chmod 775 myapp.py' on the script, MacOs would open it.

I ran across this same gotcha with an app using pydub and ffmpeg that had to do with the fact that pydub uses subprocess to run ffmpeg. If ffmpeg is in your system's path then pydub finds it ok but if you're packaging your app with py2app, then it's a different story because the ffmpeg that comes in the app won't be in the system path [of this other computer].  I ended up using this line in my python app to define where the ffmpeg is:  btw, AudioSegment is a module of pydub and the converter attribute tells it to look for it's format conversion tool at this specific path:

```<code>AudioSegment.converter = "../Frameworks/ffmpeg"
</code>```

Then I put this in the py2app setup file:

```<code>OPTIONS = {
    'frameworks': ['/usr/local/Cellar/portaudio/19.6.0/lib/libportaudio.dylib',
    '/usr/local/Cellar/ffmpeg/3.4/bin/ffmpeg'], }
</code>```

This tells py2app to add the [portaudio and] ffmpeg Framework to the bundle.  BUT, I found that the file named ffmpeg that is included doesn't have execution privileges out of the gate. After each py2app creation I had to 'chmod 775 ffmpeg' inside the contents of the app 'bungle' in order to allow the app to run ffmpeg.

I'm not sure if there are special rules with py2app that allow it to create files with execution permissions but it didn't do it automatically.

While troubleshooting this kind of thing it can be difficult to get info about what's going wrong where.  So I looked for extra techniques to find what was going wrong.  It might be a good idea when troubleshooting a py2app issue to use a lot of try's so you don't miss any exceptions:

```<code>try:
    from tkinter import *
except Exception as e:
    print("tkinter didn't import: {}".format(e))
</code>```

Body:
I'm using python 3.6.2 with pyenv and homebrew on Mac OS Sierra and i've been unable to create functional bundle apps with py2app v0.14 and pyinstaller v3.2.1.

ActiveTcl version 8.5.18/tkinter are installed.

Standard 2.7.10 Mac version of python doesn't do much else. I actually managed to make one or two attempts to work on python 2.7.10 with other programs, but since i want to use 3.6.2 there's no point to stay on standard.

py2app creates an .app file that just gives "error" and Mac asks to terminate. pyinstaller doesn't even create an .app file. I followed all the instructions in all the programs.

py2app gives me this message at the end when creating the .app:

Modules not found (unconditional imports):

 * com (com.sun.jna)
 * com.jna (com.sun)
 * com.sun (com.sun.jna.platform)
 * ordereddict (pkg_resources._vendor.pyparsing)
 * win32com (win32com)
 * win32com.shell (win32com.shell)
 * win32com.shellcon (win32com.shell)

Modules not found (conditional imports):

 * StringIO (pkg_resources._vendor.six)
 * com (pkg_resources._vendor.appdirs)
 * com.sun.jna (pkg_resources._vendor.appdirs)
 * com.sun.jna.platform (pkg_resources._vendor.appdirs)
 * win32com (pkg_resources._vendor.appdirs)
 * win32com.shell (pkg_resources._vendor.appdirs)

I checked for missing modules and for me it doesn't look like the program is trying to use any module listed above.

I retrieved the program from the internet, it's a simple test program, here's the script:

from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = float(feet.get())
        meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass

root = Tk()
root.title("Feet to Meters")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

feet = StringVar()
meters = StringVar()

feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)

ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()

I've tried uninstalling and reinstalling python, ActiveTcl, i've run brew doctor, nothing seems to work. Pyenv is working fine. Homebrew is working fine.

I've searched everywhere for two days, and no matter what i do every time py2app creates the .app file it only gives "Error".

The app runs perfectly when i run through IDLE. What problem can it be???

EDIT: After sometime working this out i found a solution for python 3.6.2 using cx_freeze. Py2app only worked with Python 2.7.10 as i told before. For some reason Py2app only load the missing modules i mentioned earlier when running with python 2.7.10, when python 3.6.2 comes in he fails to load the modules and the .app file don't work properly.

Body:
After my own 'pyjinks' with py2app I found a few things that might relate.

First of all, your problem with 'error' sounds like an issue that I experienced when my app file was sync'd (via a dropbox style service) to another computer.  The file would run fine on the computer that created it but I would get an error that it couldn't be opened when I tried to run it on the remote computer.  BUT, if  I uploaded the app file via google drive and then downloaded it to the remote computer, it would open and run fine!!  So, after poking around I found that the python script inside the app bundle on this remote computer didn't have execution permissions.  After running 'chmod 775 myapp.py' on the script, MacOs would open it.

I ran across this same gotcha with an app using pydub and ffmpeg that had to do with the fact that pydub uses subprocess to run ffmpeg. If ffmpeg is in your system's path then pydub finds it ok but if you're packaging your app with py2app, then it's a different story because the ffmpeg that comes in the app won't be in the system path [of this other computer].  I ended up using this line in my python app to define where the ffmpeg is:  btw, AudioSegment is a module of pydub and the converter attribute tells it to look for it's format conversion tool at this specific path:

AudioSegment.converter = "../Frameworks/ffmpeg"

Then I put this in the py2app setup file:

OPTIONS = {
    'frameworks': ['/usr/local/Cellar/portaudio/19.6.0/lib/libportaudio.dylib',
    '/usr/local/Cellar/ffmpeg/3.4/bin/ffmpeg'], }

This tells py2app to add the [portaudio and] ffmpeg Framework to the bundle.  BUT, I found that the file named ffmpeg that is included doesn't have execution privileges out of the gate. After each py2app creation I had to 'chmod 775 ffmpeg' inside the contents of the app 'bungle' in order to allow the app to run ffmpeg.

I'm not sure if there are special rules with py2app that allow it to create files with execution permissions but it didn't do it automatically.

While troubleshooting this kind of thing it can be difficult to get info about what's going wrong where.  So I looked for extra techniques to find what was going wrong.  It might be a good idea when troubleshooting a py2app issue to use a lot of try's so you don't miss any exceptions:

try:
    from tkinter import *
except Exception as e:
    print("tkinter didn't import: {}".format(e))


问:
close button overlap scrollbar (position:fixed)

I'd like to fixed position right of the div inside the scrollable div.

But the fixed div just overlaps the parent div's scrollbar!
How to fix it?

(must be fixed, only css)

```<code>div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:15px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}
</code>```

答:
If the scroll bar is on the body (which is the default behaviour when the page content is long), the fixed position div will not overlap on the scroll bar.

In your case, most likely the scroll bar is of one of the elements with overflow: scroll; or overflow: auto; or alike, that's why that div is overlapping.

Since we don't know what's your full HTML/CSS, we cannot tell which one is causing the issue or how to fix it.

Body:
I'd like to fixed position right of the div inside the scrollable div.

But the fixed div just overlaps the parent div's scrollbar!
How to fix it?

(must be fixed, only css)

div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:15px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}