Plotting mixture of univariate normal distributions using the R package EMCluster

Question: I would like to visualize a mixture of univariate normal distributions fitted by the EMCluster R package. I would like to get a set of Gaussian curves plotted for each group separately onto a histogram of my data like this:

However, there does not seem to be any plotting function in EMCluster doing that, and the EMCluster help files do not cover this topic. I am aware of other R packages having this functionality (e.g., mixtools or mclust), but these do not do the fitting job right unlike EMCluster, which as the only one fits the distribution correctly.
This is is the code used to fit the model:
# input data
ratio <- c(2.3082202,2.2682008,2.3430013,2.3131582,2.3442648,2.2866254,2.4438874,2.4360583,2.4907970,2.4785809,2.4368449,2.4589041,2.2404580,2.2568378,2.2305135,2.2316156,2.1975250,2.2003426,2.3995671,2.2367229,2.2380535,2.2695250,2.2795190,2.2804133,2.2873157,2.3025447,2.2981834,2.2774566,2.1899404,2.2675393,2.2863328,2.2702749,2.2173223,2.1615549,2.3052489,1.4739972,1.4703164,1.8989637,1.6309663,1.4742799,1.6040551,1.5125876,2.3090968,2.4032732,2.2939723,2.4932422,2.4572377,2.2887470,2.2541456,2.3912709,2.3709839,2.2961881,2.3252021,2.4311603,2.4526981,2.2712559,2.4556190,2.4480402,2.2345277,2.2832188,2.3259353,2.3486292,2.3477749,2.3160682,2.3025502,2.3645101,2.2972784,2.3914385,2.4182051,2.3144094,2.3182206,2.3032635,2.3304741,2.4386540,2.4750668,1.5558920,1.5520053,1.5679544,1.5674089,1.5318896,1.5378909,1.5780276,1.5884973,1.5535807,2.4912484,1.5725149,1.6011670,1.5669198,1.5581934,1.5688439,1.5578162,1.5593121,1.5563160,1.5468341,1.5433628,1.5141012,1.5842708,1.5632946,1.5233117,1.5867471,1.5010637,1.5865281,1.5836973,1.6140125,1.6285195,1.5592994,1.5584742,1.6113194,1.6074361,1.5850861,1.5612799,1.5905453,2.3874244,2.4045643,2.3996815,2.3605345,2.3346210,2.3865179,2.4406780,2.3688209,2.3649233,2.3668617,2.4675781,2.4767129,2.4664701,2.3560843,2.5487013,2.4604951,2.5133258,2.4387729,1.4955564,1.5082731,1.5440476,1.5911176,2.4114691,2.4188795,2.4320730,2.4896641,2.4439351,2.4726592,2.4819837,2.4053318,2.4694447,2.3929463,2.3948703,2.3993741,2.4535933,2.4556870,2.3877090,2.4466891,2.4426443,2.3879938,2.3402072,2.3448416,2.4782167,2.5233350,1.5917363,1.6355997,1.5816622,1.6164543,1.5466306,1.5081628,1.4992875,1.6306420,1.6762845,1.6866838,2.4210023,2.4406259,2.3720587,2.4113856,2.3190864,2.4250728,2.4457677,2.4429783,2.4122941,2.4424428,2.4527037,2.4966437,2.4035152,2.4137089,2.3954934,2.4212645,2.4087689,2.4105695,2.5525013,1.5290941,1.5728092,1.5543364,1.5641066,1.6006943,1.5889370,1.5321614,1.5586370,1.5415335,1.5491241,1.5541842,1.5852345,1.5902462,1.5801461,1.5930383,1.5523744,1.5575027,1.5546879,1.5726514,1.5938686,1.6222843,1.5881920,1.5889394,1.6246987,1.5791531,1.6059873,1.5860296,1.5701796,1.5763713,1.6315066,1.6206847,1.5685662,1.5892450,1.6186198,1.6242586,1.5481500,2.5555498,2.5258320,1.6016010,1.6078024,1.7627993,2.5282046,2.5283876,1.6267890,1.6268478,1.6069182,1.5574029,1.5672845,1.6389830,1.5810995,1.5809019,1.5621111,1.6275267,1.5630592,1.5361265,1.5750796,1.5447555,1.5755329,1.5092036,1.5607702,1.5812295,1.6181003,1.6067561,1.6846355,1.6251237,1.7229672,1.6319477,2.0122061,1.6008821,1.4929003,1.5977780,1.6336924,1.7014357,1.7084902,1.5106016,1.6115451,1.5218875,1.5394796,1.5841880,1.6021178,1.6286143,1.6322306,1.6479547,1.6051730,1.6903781,1.5605062,1.6159015,1.5648148,1.6410461,1.5526851,1.5951099,1.6702494,1.6863064,1.5488679,1.5722265,1.5789145,2.3835058)
ratio <- c(ratio,2.4312322,2.4034768,2.4384596,2.4436314,2.4303576,2.4266296,2.3727400,2.3769620,1.4916100,2.0513010,2.0537072,1.6218816,1.6315519,1.6242272,1.5328026,2.4791800,2.4943584,1.5233619,1.5520066,1.5211411,1.5946195,1.5954327,1.5099963,1.6025225,1.4824897,1.5543129,1.6041963,1.9676651,1.8662227,1.9669943,1.5584472,1.5664382,1.5551137,1.5563330,1.5637281,1.6058321,2.3605461,1.4467948,2.4481076,2.2974519,2.4029441,2.4499736,2.4637541,2.4147364,2.4483680,2.4730025,2.4344831,2.4246536,2.3520329,2.3551388,2.4119589,2.4621961,2.3978363,2.4289587,2.4244460,2.3955454,2.4106017,2.4766059,2.5505131,2.5904964,2.4405065,2.5502677,2.5418027,2.5946520,2.3462233,2.3910095,2.3808582,2.4900000,2.4929675,2.5957481,2.6473263,2.6821399,2.5863157,2.5706163,2.5873251,2.3470114,2.3549401,2.4447632,2.3895783,2.4598023,1.9194875,1.9098258,1.5563858,1.9655190,1.9843544,1.5075750,1.9197088,1.8606831,1.5003864,1.5420225,1.5832182,1.4812740,1.5309472,1.5425323,1.6757806,1.6147225,1.5449271,1.6736108,1.6062912,1.5309035,1.5375653,1.5230470,1.4537051,1.5208274,1.6269986,1.6722362,1.5627355,1.5736269,1.5597532,1.6075006,1.5912113,1.4857339,1.4865164,1.5915908,1.5626763,1.6001816,1.5838017,1.6547792,1.6521739,1.5541260,1.5589220,1.6041114,1.6052877,1.6188839,1.5851005,1.5210468,1.5914289,1.5612923,1.5543678,1.6405511,1.5491183,1.5760101,1.5988843,1.5453074,1.5629486,2.3506363,2.3900338,2.3692994,2.3774440,2.3778159,1.4801504,1.5272571,1.5429716,1.5863007,1.5595683,1.5373692,1.5547804,1.6523496,1.6553747,2.4441022,2.3405286,2.4331678,2.4992773,2.4313793,2.3579883,2.4041657,2.3764722,2.3899039,2.4933925,2.4881635,2.3814493,2.4341179,2.5575816,2.4556496,2.5024020,2.4669698,2.4933790,2.5047439,2.4975195,2.4015712,2.4469022,2.4567287,2.5280128,2.4781728,2.5028472,2.5189290,2.5043568,2.4434804,2.4769850,2.4082988,2.4613414,2.3871942,2.4679938,2.4711610,2.3716282,2.4665808,2.4719631,2.4671665,2.3450332,2.3711461,2.3567956,2.4531954,2.4627118,2.4688380,2.4264698,2.4634535,2.4754286,2.4152280,2.4200143,2.4366610,2.4748473,2.3998817,2.4435630,2.4505969,2.4825692,2.4722832,2.3908582,2.5265103,2.4205017,2.4975109,1.8273926,1.8191600,1.7649152,1.8441525,1.8362518,1.7798777,1.7749614,1.8514624,1.8231416,1.7980675,1.8139444,1.7813007,1.8112133,1.8506497,1.7888465,1.7981612,1.7877846,1.8448715,1.8428863,1.7778798,1.8004113,1.8293173,1.8581288,0.7568285,0.7681167,0.7569872,0.7478473,0.7586729,0.7574590,0.7707119,0.7654296,0.7560802,0.7223322,0.7634792,0.7577954,0.7630233,0.7439842,0.7501500,0.7666750,0.7503895,0.7622286,0.7635520,0.7534987,0.7599475,0.7748956,0.7590139,0.7568013,0.7586510,0.7564873,0.7576587,0.7756744,0.7637029,0.7579558,0.7735586,0.7692345,0.7611547,0.7551704,0.7715118,0.7736083,0.7635049,0.7559560,0.7667778,0.7618454,0.7648308,0.7693512,0.7653699,0.7589299,2.3590999,2.3619440,2.3519471,2.3453709,2.3486040,2.4295357,2.4219361,2.4488210,2.4213269,2.3923218,1.5402144,0.7652187,0.7650076,0.7486516,0.7643569,0.7677992,0.7586368,0.7584026,0.7662775,0.7740569,0.7713377,0.7740677,0.7686109,0.7490695,0.7681402,0.7639513,0.7896797,0.7660664,0.7720809,2.4936417,2.3834268,0.7626155,0.7566950,0.7824697,0.7735270,2.4219853,2.5196019,0.7636966,0.7570312,2.4539218,2.4338622,2.4396830,0.7733773,0.7632390,0.7697633,0.7677199,0.7563686,0.7569366,0.7785563,2.3883388,2.4508850,2.5454545,2.4078138,2.4295884,2.5461211,2.3826057,2.4070722,2.4136287,2.4216196,2.3854115,2.4173648,2.4553045,2.4356992,2.3863270,2.4346182,2.3953523,2.4102911,2.4179386,2.4251441,2.4217263,2.4586260,2.4059818,2.4069762,2.4099267,2.4387039,2.4458400,2.4573490,2.4759171,2.4772782,2.4684424,2.4434910,2.4804417,2.4192554,2.4454277,2.3955812)
ratio <- c(ratio,2.4749573,2.4724740,2.4209932,2.4249042,0.7610100,2.3671184,2.3697960,2.4023920,2.4053188,2.4351452,2.4386339,2.4094596,2.3468609,2.3155974,2.3104149,2.3627904,2.2658038,2.3885135,2.3038569,2.3350929,2.3612206,2.2781386,2.2077955,2.2325030,2.2679324,2.2823724,2.4542063,2.1998876,2.3031394,2.2881462,2.3198411,2.1884115,2.2710756,2.1827032,2.3180018,2.2993929,2.2874717,2.2829849,2.3455578,2.2977960,2.3410225,2.4081727,2.3638018,2.2795117,2.3976837,2.3932511,2.4075917,2.4015616,2.3418264,2.3349013,2.4240838,2.4173924,2.3960085,2.4031925,2.3945173,2.3856273,2.4690719,2.4686576,2.6263546,2.4718199,2.3463103,2.3652738,2.4379702,2.4796148,2.4287476,2.2620077,2.3805959,2.3458551,2.3461876,2.3171412,2.3897433,2.3912464,2.3614724,2.5442086,1.7773526,1.7178727,2.3689272,2.3640495,2.2916104,2.3356112,2.3964407,2.4015147,1.7590361,2.3414859,2.2694388,2.3567392,2.2708003,2.2956377,2.3101355,2.3125120,2.3004763,2.2705803,2.2875544,2.2712565,2.3089819,2.2945688,2.3205069,2.2732516,1.7467849,1.7259182,1.7686619,1.7095978,2.2485174,2.4754472,2.4495703,2.4074395,2.4539152,2.3435356,2.3811995,2.4362843,2.4403479,2.5180754,0.7635700,0.7702974,0.7722231,0.7511177,0.7551106,0.7601832,0.7361963,0.7794874,0.7934396,0.7709755,0.7844490,0.7596845,0.7930613,0.7504008,0.7627609,0.7532478,0.7581377,0.7705301,0.7721196,0.7567074,0.7828257,0.7780374,0.7669904,0.7812995,0.7834886,0.7889141,0.7859603,0.7682853,0.7478378,0.7673373,0.7629394,0.7715725,0.7791851,0.7666474,0.7714516,0.7496962,0.7533639,0.7579321,0.7737278,0.7853168,0.7645964,0.7725103,0.7677113,1.6156064,1.5390375,1.5211357,1.5385035,1.4920242,1.6010156,1.5269279,1.5407954,1.4766077,1.5165483,2.4101888,2.4461818,2.4832620,2.4234102,2.3891139,2.4782895,2.4514298,2.4655178,1.5269570,1.5543206,1.5397302,1.5121552,1.5089835,1.5259734,1.5593889,1.5634023,1.5243902,1.5291230,1.5649990,2.3870746,2.4165985,2.4108952,2.5178706,2.4626444,2.4056250,2.4241015,2.2767663,2.1800944,2.2449665,2.2155462,2.2102232,2.1888782,2.1780130,2.1797660,2.2164432,2.1815838,2.2745605,2.2695021,2.1916002,2.1620086,2.1604276,2.1606576,2.1582508,2.1380764,2.1869745,2.1967953,2.1466257,2.1625341,2.2056076,2.1491951,2.2865496,2.2079291,2.1408957,2.1638916,2.5895003,2.1258483,2.1444175,2.2055520,2.1909330,2.2072956,2.2051386,2.4054279,2.4282109,2.4143596,2.4389768,2.4716971,2.4614070,2.4076957,2.4289880,2.4710598,2.4395144,2.4251923,2.4528039,2.4597420,2.4047160,2.4214961,2.4052775,2.4002135,2.3944374,2.4051049,2.4450801,1.5737999,1.5879028,1.4740943,1.5251975,1.5084994,1.5176669,1.5827066,1.8177106,2.4441547,2.4143742,2.4699203,2.3762657,2.3688625,2.4603598,2.4191691,2.4546725,2.4275861,2.4220888,2.4021738,2.4979091,2.4092485,2.4321795,2.4349427,2.4462136,2.4662561,2.3542403,2.4312644,2.4911342,2.4228929,2.4431390,2.4214492,2.4497284,2.4559866,2.4404771,2.4329174,2.4118930,2.4634206,2.4609880)
ratio <- c(ratio,2.4827362,2.3897923,2.4143036,2.4375662,2.4641043,2.4222062,2.4024445,2.4035411,2.4564304,2.4355113,2.3968869,2.4147049,2.4618251,2.4281002,2.3793209,2.4370193,2.3959920,2.3882394,2.4338975,2.4221606,2.4012736,2.4163148,2.4014352,2.3909576,2.4497283,2.3379209,2.2898380,2.3337816,2.2496425,2.3140063,2.2480368,2.3382981,2.4370101,2.3976064,1.5515221,1.6095634,1.5416116,1.5449938,1.5357950,1.6159637,2.5099319,2.4895688,2.5469330,2.4921635,2.4849558,2.5936576,2.4149410,2.3313097,2.3891210,2.3958461,2.4481496,2.3889537,2.3672844,2.3638062,2.3213211,2.2783695,2.3841916,2.3915916,2.4455549,2.3920387,2.3327502,2.3814912,2.3998684,2.5413619,2.4137805,2.4694112,2.2786062,2.3302104,2.3343673,2.3937296,2.3613661,2.4505636,2.4254633,2.5044136,2.4344560,2.3947676,2.3527630,2.3999480,2.3888254,2.4736389,2.4171134,2.4438647,2.2072640,2.4066542,2.4867753,2.4228284,2.4383648,2.4733934,2.3856568,2.3750662,2.2850762,2.3953039,2.4272293,2.4479172,2.4583161,2.4372287,2.4391820,2.4068650,2.3923539,2.4295108,2.4074787,2.4039005,2.4916317,2.4349603,2.4786877,2.4942217,2.2279876,2.4491045,2.2402399,2.3116072,2.3713333,2.3000641,2.2848940,2.4239510,2.4702209,2.4698362,2.4101398,2.3967287,2.4586776,2.4489123,2.4533943,2.4532398,2.4235131,2.4177043,2.4007880,2.4442298,2.4343659,2.4388599,2.3495992,2.4192377,2.3928401)
library(EMCluster)
ret <- init.EM(as.data.frame(ratio),nclass=6,method="Rnd.EM") # fitting model
# now how to plot the distribution curves?

Thank you in advance for your advice.
EDIT:
The structure of the resulting object is this:
> str(ret,vec.len = 10)
List of 13
 $ pi       : num [1:6] 0.0537 0.234 0.299 0.1124 0.2225 0.0784
 $ Mu       : num [1:6, 1] 1.794 1.568 2.429 0.765 2.316 2.474
 $ LTSigma  : num [1:6, 1] 0.011002 0.001946 0.001355 0.000124 0.008215 0.006486
 $ llhdval  : num 435
 $ nc       : int [1:6] 52 252 406 119 195 35
 $ class    : num [1:1059] 5 5 5 5 5 5 3 3 3 3 3 3 5 5 5 5 5 5 3 5 5 5 5 5 5 ...
 $ conv.iter: int 93
 $ conv.eps : num 9.81e-07
 $ flag     : num 0
 $ n        : int 1059
 $ p        : int 1
 $ nclass   : num 6
 $ method   : chr "Rnd.EM"
 - attr(*, "class")= chr "emret"

Comment: Yes, the function outputs means and sigmas:
`$ pi       : num [1:6] 0.0537 0.234 0.299 0.1124 0.2225 0.0784`
 `$ Mu       : num [1:6, 1] 1.794 1.568 2.429 0.765 2.316 2.474`
 `$ LTSigma  : num [1:6, 1] 0.011002 0.001946 0.001355 0.000124 0.008215 0.006486`
Comment: What does the function output?  Does it give you the means & SDs of the fitted clusters?
Answer: This is pretty straightforward.  There's a little bit of calculation involved in getting the heights of the curves to line up reasonably, but otherwise it's pretty basic.  First plot a histogram.  If you want a box around it, like your example, do that.  Then you'll need to call lines() 6 times to plot the 6 normals.  In R, lines are just a sequence of interpolated points—(x,y) coordinates—so make a sufficiently fine-grained set of x coordinates, then compute the normal density for each component using dnorm() and the fitted parameters.  You'll need to multiply those y-values by the appropriate proportion and a height adjustment factor to get the heights of the curves right.  It turns out that the highest bin in your histogram is 82, which is approximately the peak of your third component, but since that represents only 30%, you need to rescale the adjustment factor by that.  You may want to choose your own colors.  Consider:
xs  <- seq(min(ratio), max(ratio), length.out=1000)

windows()
  h <- hist(ratio, breaks=seq(0, 3, by=0.02)); box()
  # max(h$counts)  # [1] 82
  height <- 82/dnorm(ret$Mu[3,1], mean=ret$Mu[3,1], sd=sqrt(ret$LTSigma[3,1]))
  height <- height/ret$pi[3]
  for(i in 1:6){
    lines(xs, dnorm(xs, mean=ret$Mu[i,1], sd=sqrt(ret$LTSigma[i,1]))*height*ret$pi[i],
          lwd=2, col=i)
  }


Preventing Spoofed Forms

Question: I have a php page that submits form to itself.
I wanted to add a check where I can possibly stop basic cross site forgery.
my code:
<?php
session_start();

(...) //some code

$secret = substr(md5(uniqid(rand(), true)), 1, 2);
$_SESSION["secret"] = $secret;
$auth = $secret;

?>

(...)

<form id="form" name="form" action="<?php echo htmlentities($_SERVER[PHP_SELF]); ?>" method="post">

(...)

<input type="hidden" name="id" value="<? echo $auth; ?>" />

(...)

<?php

(...)

//as a debug I just tried to display
echo $_POST["id"];
echo "=";
echo $_SESSION["secret"];

(...)

?>

But both id and secret never returns the same value.
Why is that? What am I missing?

UPDATE
So, I tried an answer here by Samuel Cook, as also suggested by the comment of Jon Stirling:
if(!isset($_SESSION["secret"])){
    $secret = substr(md5(uniqid(rand(), true)), 1, 2);
    $_SESSION["secret"] = $secret;
    $auth = $secret;
}

But now if there is no $_SESSION["secret"]
The page returns:
<input type="hidden" name="id" value="" />

I understand why, its because secret is only being set if the session variable is present.
Any suggestions?

UPDATE
Moved the check before generating a new session key and is only checking if there is a post of id. works well now thanks.
Comment: Is it because you regenerate $secret at the top of the page and assign it to the session?
Answer: Once You Open A page $auth Will generate and i will be in hidden field after submiting $_SESSION["secret"] will change because $secret will generate new key but $_POST['id'] is old one which coming from Post method.
Comment: Ahh, i guess i should only generate a new session key if the ID is not present?
Comment: Yes
if(empty($_POST['id'])){
//generate new key
}
Answer: you are always generating a new $secret therefore it will always be different. You could check to see if the $_SESSION['secret'] exists, and if it doesn't then create a new variable. Something like:
if(!isset($_SESSION["secret"])){
    $secret = substr(md5(uniqid(rand(), true)), 1, 2);
    $_SESSION["secret"] = $secret;
    $auth = $secret;
}

Answer: At the point when you debug code executes, the secret has changed:
echo $_POST["id"]; // previous secret
echo "=";
echo $_SESSION["secret"]; // new secret

As long as you do your check for a match at the beginning of the script (before generating the next secret) it will be fine.

Preventing Spoofed Forms


Share Large, Read-Only Numpy Array Between Multiprocessing Processes

Question: I have a 60GB SciPy Array (Matrix) I must share between 5+ multiprocessing Process objects. I've seen numpy-sharedmem and read this discussion on the SciPy list. There seem to be two approaches--numpy-sharedmem and using a multiprocessing.RawArray() and mapping NumPy dtypes to ctypes. Now, numpy-sharedmem seems to be the way to go, but I've yet to see a good reference example. I don't need any kind of locks, since the array (actually a matrix) will be read-only. Now, due to its size, I'd like to avoid a copy. It sounds like the correct method is to create the only copy of the array as a sharedmem array, and then pass it to the Process objects? A couple of specific questions:

What's the best way to actually pass the sharedmem handles to sub-Process()es? Do I need a queue just to pass one array around? Would a pipe be better? Can I just pass it as an argument to the Process() subclass's init (where I'm assuming it's pickled)?
In the discussion I linked above, there's mention of numpy-sharedmem not being 64bit-safe? I'm definitely using some structures that aren't 32-bit addressable.
Are there tradeoff's to the RawArray() approach? Slower, buggier?
Do I need any ctype-to-dtype mapping for the numpy-sharedmem method?
Does anyone have an example of some OpenSource code doing this? I'm a very hands-on learned and it's hard to get this working without any kind of good example to look at.

If there's any additional info I can provide to help clarify this for others, please comment and I'll add. Thanks!
This needs to run on Ubuntu Linux and Maybe Mac OS, but portability isn't a huge concern.
Comment: @tiago: "I don't need any kind of locks, since the array (actually a matrix) will be read-only"
Comment: here's [a RawArray-based example that should work both on *nix and Windows, and it also supports writing to the array](http://stackoverflow.com/a/7908612/4279).
Comment: If the different processes are going to write to that array, expect `multiprocessing` to make a copy of the whole thing for each process.
Comment: @tiago: also, multiprocessing is not making a copy as long as not explicitly told to (via arguments to the `target_function`). The operating system is going to copy parts of the parent's memory to the child's memory space upon modification only.
Comment: I asked a [few](https://stackoverflow.com/questions/37705974/why-are-multiprocessing-sharedctypes-assignments-so-slow) [questions](https://stackoverflow.com/questions/32566404/assertion-error-when-using-multiprocessing-in-python-3-4) about this before. My solution can be found here: https://github.com/david-hoffman/peaks/blob/3a2c1c39119388a8996cdd510524a48ee5d7907d/stackanalysis.py#L85-L108 (sorry the code is a disaster).
Answer: If you are on Linux (or any POSIX-compliant system), you can define this array as a global variable. multiprocessing is using fork() on Linux when it starts a new child process. A newly spawned child process automatically shares the memory with its parent as long as it does not change it (copy-on-write mechanism).
Since you are saying "I don't need any kind of locks, since the array (actually a matrix) will be read-only" taking advantage of this behavior would be a very simple and yet extremely efficient approach: all child processes will access the same data in physical memory when reading this large numpy array.
Don't hand your array to the Process() constructor, this will instruct multiprocessing to pickle the data to the child, which would be extremely inefficient or impossible in your case. On Linux, right after fork() the child is an exact copy of the parent using the same physical memory, so all you need to do is making sure that the Python variable 'containing' the matrix is accessible from within the target function that you hand over to Process(). This you can typically achieve with a 'global' variable.
Example code:
from multiprocessing import Process
from numpy import random

global_array = random.random(10**4)

def child():
    print sum(global_array)

def main():
    processes = [Process(target=child) for _ in xrange(10)]
    for p in processes:
        p.start()
    for p in processes:
        p.join()

if __name__ == "__main__":
    main()

On Windows -- which does not support fork() -- multiprocessing is using the win32 API call CreateProcess. It creates an entirely new process from any given executable. That's why on Windows one is required to pickle data to the child if one needs data that has been created during runtime of the parent.
Comment: A word of caution to people stumbling across this question/answer: If you happen to be using OpenBLAS-linked Numpy for its multithreadead operation, make sure to disable its multithreading (export OPENBLAS_NUM_THREADS=1) when using `multiprocessing` or child processes might end up hanging (typically using 1/n of _one_ processor rather than n processors) upon performing linear algebra operations on a shared global array/matrix. The [known multithreaded conflict with OpenBLAS](https://github.com/xianyi/OpenBLAS/wiki/faq#wiki-multi-threaded) seems to extend to Python `multiprocessing`
Comment: Copy-on-write will copy the page containing the reference counter (so each forked python will have its own reference counter) but it will not copy the whole data array.
Comment: We are all aware of that `fork()` is not available on Windows, it has been stated in my answer and multiple times in the comments. I know that this was your initial question, and I answered it four comments above *this*: "the compromise is to use the same method of parameter transfer on both platforms by default, for better maintainability and for ensuring equal behavior.". Both ways have their advantages and disadvantages, which is why in Python 3 there is greater flexibility for the user to choose the method. This discussion is not productive w/o talking details, which we should not do here.
Comment: What about the `global` keyword, is it required?
Comment: I would add that I've had more success with module level variables than with global variables... ie add the variable to a module in global scope before the fork
Comment: Can anyone explain why python wouldn't just use OS `fork` to pass parameters given to `Process`, instead of serializing them? That is, couldn't the `fork` be applied to the parent process just *before* `child` is called, so that the parameter value is still available from the OS? Would seem to be more efficient than serializing it?
Comment: @max providing a common interface on top of very different platforms (Windows and POSIX are *very* different in terms of process creation) requires making compromises. Here, I guess, the compromise is to use the *same* method of parameter transfer on both platforms by default, for better maintainability and for ensuring equal behavior. Nevertheless, if you are aware of it, you can take advantage of POSIX fork() yourself, as I proposed in this answer. This is not difficult at all, so there is no particular "need" for multiprocessing to support it.
Comment: @Jan-PhilipGehrcke python only supports the `fork` method under POSIX, so compatibility isn't an issue.
Comment: @max I guess you do not really know what you are writing about, and now I am entirely confused and cannot really help. I try anyway: `fork()` is a system call, which is something that the operating system has to provide. Python, or any other application, can *use* it. Windows does not provide `fork()`. So, *"python only supports the fork method under POSIX"* is half wrong and half obvious, and *"compatibility isn't an issue"* tells me nothing about what you are struggling with now. It *is* an issue, considering that Windows does not support `fork()`.
Comment: @Jan-PhilipGehrcke I meant that I'm asking about `'fork'`, which is one of several start methods supported by python's `multiprocessing.Process`, and which is documented as only supported under POSIX; you can't use it on Windows at all. So Python is not constrained by any cross-platform issues when using `'fork'` start method. My question was why in this situation, Python wouldn't call the `target` function and then `os.fork()` instead of `fork`ing before the call and therefore serializing the argument to `target`.
Comment: Thanks, but, doesn't referencecounting force a copy? I know how copy-on-write works in a C program, but how can I guarantee there are no "writes"? I feel like I need some kind of shared memory here.
Answer: @Velimir Mlaker gave a great answer. I thought I could add some bits of comments and a tiny example.
(I couldn't find much documentation on sharedmem - these are the results of my own experiments.)

Do you need to pass the handles when the subprocess is starting, or after it has started? If it's just the former, you can just use the target and args arguments for Process. This is potentially better than using a global variable.
From the discussion page you linked, it appears that support for 64-bit Linux was added to sharedmem a while back, so it could be a non-issue.
I don't know about this one.
No. Refer to example below.

Example
#!/usr/bin/env python
from multiprocessing import Process
import sharedmem
import numpy

def do_work(data, start):
    data[start] = 0;

def split_work(num):
    n = 20
    width  = n/num
    shared = sharedmem.empty(n)
    shared[:] = numpy.random.rand(1, n)[0]
    print "values are %s" % shared

    processes = [Process(target=do_work, args=(shared, i*width)) for i in xrange(num)]
    for p in processes:
        p.start()
    for p in processes:
        p.join()

    print "values are %s" % shared
    print "type is %s" % type(shared[0])

if __name__ == '__main__':
    split_work(4)

Output
values are [ 0.81397784  0.59667692  0.10761908  0.6736734   0.46349645  0.98340718
  0.44056863  0.10701816  0.67167752  0.29158274  0.22242552  0.14273156
  0.34912309  0.43812636  0.58484507  0.81697513  0.57758441  0.4284959
  0.7292129   0.06063283]
values are [ 0.          0.59667692  0.10761908  0.6736734   0.46349645  0.
  0.44056863  0.10701816  0.67167752  0.29158274  0.          0.14273156
  0.34912309  0.43812636  0.58484507  0.          0.57758441  0.4284959
  0.7292129   0.06063283]
type is <type 'numpy.float64'>

This related question might be useful.
Answer: You may be interested in a tiny piece of code I wrote: github.com/vmlaker/benchmark-sharedmem
The only file of interest is main.py. It's a benchmark of numpy-sharedmem -- the code simply passes arrays (either numpy or sharedmem) to spawned processes, via Pipe. The workers just call sum() on the data. I was only interested in comparing the data communication times between the two implementations.
I also wrote another, more complex code: github.com/vmlaker/sherlock.
Here I use the numpy-sharedmem module for real-time image processing with OpenCV -- the images are NumPy arrays, as per OpenCV's newer cv2 API. The images, actually references thereof, are shared between processes via the dictionary object created from multiprocessing.Manager (as opposed to using Queue or Pipe.) I'm getting great performance improvements when compared with using plain NumPy arrays.
Pipe vs. Queue:
In my experience, IPC with Pipe is faster than Queue. And that makes sense, since Queue adds locking to make it safe for multiple producers/consumers. Pipe doesn't. But if you only have two processes talking back-and-forth, it's safe to use Pipe, or, as the docs read:

... there is no risk of corruption from processes using different ends of the pipe at the same time.

sharedmem safety:
The main issue with sharedmem module is the possibility of memory leak upon ungraceful program exit. This is described in a lengthy discussion here. Although on Apr 10, 2011 Sturla mentions a fix to memory leak, I have still experienced leaks since then, using both repos, Sturla Molden's own on GitHub (github.com/sturlamolden/sharedmem-numpy) and Chris Lee-Messer's on Bitbucket (bitbucket.org/cleemesser/numpy-sharedmem).
Comment: Beyond just noticing the leaks, I haven't looked for it in the code. I added to my answer, under "sharedmem safety" above, keepers of the two open source repos of the ``sharedmem`` module, for reference.
Comment: Thanks, very very informative. The memory leak in `sharedmem` sounds like a big deal, though. Any leads on solving that?
Answer: If your array is that big you can use numpy.memmap. For example, if you have an array stored in disk, say 'test.array', you can use simultaneous processes to access the data in it even in "writing" mode, but your case is simpler since you only need "reading" mode.
Creating the array:
a = np.memmap('test.array', dtype='float32', mode='w+', shape=(100000,1000))

You can then fill this array in the same way you do with an ordinary array. For example:
a[:10,:100]=1.
a[10:,100:]=2.

The data is stored into disk when you delete the variable a.
Later on you can use multiple processes that will access the data in test.array:
# read-only mode
b = np.memmap('test.array', dtype='float32', mode='r', shape=(100000,1000))

# read and writing mode
c = np.memmap('test.array', dtype='float32', mode='r+', shape=(100000,1000))

Related answers:

Working with big data in python and numpy, not enough ram, how to save partial results on disc?
Is it possible to map a discontiuous data on disk to an array with python?
Comment: So in this case, all processes will be able to access the same `np.memmap` object without replication, and without having to somehow pass the object?
Answer: You may also find it useful to take a look at the documentation for pyro as if you can partition your task appropriately you could use it to execute different sections on different machines as well as on different cores in the same machine.
Answer: Why not use multithreading?
Resources of main process can be shared by its threads natively, thus multithreading is obviously a better way to share objects owned by the main process.
If you worry about python's GIL mechanism, maybe you can resort to the nogil of numba.


Image loaded in ImageView is hiding the button

Question: When I am loading an image(more specifically, an image of portrait shape) in an ImageView that image is sometimes covering the Button which is above the ImageView. The ImageView has layout_width and layout_height set to wrap_content. My requirement is that the ImageView will wrap content but, won't cover up the button. I don't want to hardcode pixel values.
layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="mg.colorfilters.ResultActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/button1"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@color/red"
        android:text="@string/string3"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:onClick="loadImageWithFilterOrSaveImage" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/abc_ab_bottom_solid_dark_holo"
        android:contentDescription="@string/string4" />

</RelativeLayout>

Comment: You shouldn't use pixels use `dp` instead.
Comment: You can use `android:layout_above="@+id/imageView1"` in the `Button`
Comment: Is there any way to mention how many pixels above?
Comment: @Apoorv I use dp. You didn't answer my question.
Comment: Use `android:layout_marginBottom=""` to give margin below `Button`
Comment: Just tested, didn't solve the problem. Loaded image is still covering the button.
Answer: You want your image to be at centre?
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

If yes, then may want to put your Button code below ImageView code, like
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/abc_ab_bottom_solid_dark_holo"
    android:contentDescription="@string/string4" />

<Button
    android:id="@+id/button1"
    android:layout_width="320dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:background="@color/red"
    android:text="@string/string3"
    android:textStyle="bold"
    android:textColor="@color/white"
    android:onClick="loadImageWithFilterOrSaveImage" />

This way the button will always be on top. If image is large, button will be visible on top of it. Use this solution only if you are OK with this behavior.
Comment: Yes, I want the image at the center. Your solution is very close to the solution I want, but not the exact solution.
Comment: You want image to be at center of screen and want button to be at center horizontal and top aligned. What happens when image dimensions grow? something will have to give way or you have to set max dimentions to image view
Comment: We can resize the ImageView maintaining the aspect ratio of the loaded image.
Comment: yup we can. I think setting max dimension should take care of aspect ratio. (if you do this remember to do dp-px calculation, as u'll need dimension in dp but it is set in px)
Comment: I've already found that out. Using android:maxHeight="300dp" and android:adjustViewBounds="true". Any way to mention relative dimensions inside RelativeLayout. I am getting warnings if I use layout_weight.
Comment: What exactly you mean by relative dimensions? We have layout_alignLeft="viewId", layout_toRightOf="viewId", layout_above="viewId" etc etc.
Answer: In Your Layout.xml
please insert android:layout_above="@+id/button1 line in <ImageView> tag.
Answer: you can use a scrollview inside the relative layout and use a linear layout in vertical orientation in the scrollview...then add your button and imageview in the linear layout.....I havent tried this but i think this will work :D


How to write jasmine test case for ngDialog in angular Js?

Question: I have code lines in my controller. Let me know how to write jasmine test case for this?

 if(!angular.element('#reimsave').hasClass("pointerEvent") && !angular.element('#reimedit').is(':visible'))
                    {
                        ngDialog.openConfirm({
                            template: 'app/shared/views/confirmAlert.html',
                            scope: $scope,
                            closeByDocument: false,
                            closeByEscape:false
                        }).then(function (value) {
                            intial = slected;
                            $scope.selectedTab = 'earnings';
                            $location.path( "/directDeposit/earnings" );
                        }, function (error) {
                        });
                    }
Comment: No Answer for this question?
Answer: It depends on what you are trying to test exactly.
One way of testing could be...
it("should call ngDialog.openConfirm"), function() {
  spyOn(ngDialog, 'openConfirm').and.callThrough();

  //include whatever code you need here to meet your if condition

  expect(ngDialog.openConfirm).toHaveBeenCalled();
}

I have not been able to test anything in the dialog itself though as in my test runner, the dialog does not actually popup!


Dúvida sobre contexMenuStrip

Question:
É o seguinte, eu preciso adicionar essas ferramentas, exatamente como mostra na imagem.
Preciso só de um empurrão, sobre como começar.

Inserir texto
Inserir Imagem
Excluir (botão)

CODE
namespace frmLoginRPG
{
    public partial class frmMenuPrincipal : Form
    {
        private readonly Button[] _todosBotoes;
        public frmMenuPrincipal()
        {

            InitializeComponent();
            //Passo 1

            _todosBotoes = _mainPanel.Controls.OfType<Button>().ToArray();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            //Passo 2.1
            var controles = _todosBotoes.Where(btnRifts => (btnRifts.Tag as String ?? btnRifts.Text).ContainsIgnoreCase(txtBuscarJogo.Text)).ToArray();
            //Passo 2.2
            _mainPanel.Controls.Clear();
            //Passo 2.3
            _mainPanel.Controls.AddRange(controles);
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void btnAdicionar_Click(object sender, EventArgs e)
        {

            Button button = new Button(); //criando botão
            button.Size = _todosBotoes[0].Size; //criando botão, puxando o tamanho dos outros botões
            button.BackColor = Color.AliceBlue; //definindo cor do botão
            _mainPanel.Controls.Add(button); //Adicionando botão no _mainPanel
            button.ContextMenuStrip = this.contextMenuStrip1; //Adicionando contextMenuStrip assim que o Botão for criado.

            MessageBox.Show("                  CRIADO        ");

        }
    }

}
namespace MyMethod
{
    public static class MyExtensions
    {
        public static bool ContainsIgnoreCase(this string source, string search)
        {
            return source.IndexOf(search, StringComparison.CurrentCultureIgnoreCase) >= 0;
        }
    }
}
`

Answer: Você cria um contextMenu e define ele na propriedade do Button, no evento do click você saberá de qual button veio o click pelo sender:
    private void inserirTextoToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string name = ((Button)sender).Name;
        MessageBox.Show("Você clicou para inserir no botão: " + name);
    }

    private void excluirToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string name = ((Button)sender).Name;
        MessageBox.Show("Você clicou para excluir o botão: " + name);
    }

Comment: Mas eu preciso daquelas funçoes funcionando, Excluir o botão, colocar imagem no botão, alterar descrição no botão... entendeu?
Comment: @Dário, é só você trocar o MessageBox do código do rovann pela funçao que você precisa. Em inserir por exemplo ficaria: Button btn = (Button) sender; btn.Text = text;
Comment: Presumindo que text seja uma String que você definiu, ou pediu pro usuário.
Comment: nao tenho como colocar funcionando pq o 'inserir texto' como q o usuario irá inserir ? o excluir, vai excluir da onde ? entende....rs só o conceito
Comment: Eu entendi, mas no caso não seria usuário nenhum, só eu mesmo! Excluir o botão do Panel inserir descrição de texto no botão e colocar imagem no botão. tudo através do ContextMenu
Comment: Eu não tenho um banco de dados, nada... ta bem cru
Comment: A função para excluir poderia ser algo assim: Button btn = (Button) sender; _mainPanel.Controls.Remove(btn);
Comment: Já as outras duas, você precisa receber o texto e a imagem de algum lugar. Uma opção seria abrir um novo Form passando o botao como parâmetro e dentro desse Form, alterar as propriedades necessárias como text e image.
Comment: Está faltando você projetar sua aplicação antes de desenvolver e saber cadas recurso que ela precisará. Desde a primeira pergunta que você fez onde eu respondi com exemplo onde um DataTable era origem dos botões. Agora se você precisa armazenar essas informações, editar, inserir ou excluir, nada dessa parte estática dos botões inseridas diretamente na tela faz sentido, teria que alterar essa parte toda.

Dúvida sobre contexMenuStrip


Como modificar um extrato diario para um extrato mensal?

Question: Tenho uma tabela que não está nas formas normais de banco de dados, mas tem dados antigos que eu preciso obter.
Eu consegui fazer com que me apresentasse o extrato diário, mas agora preciso modificar para que gere o extrato mensal na seguinte query:
SELECT dia, mes, ano, credito, debito, format(saldo,2) as saldo
FROM (
    SELECT
        dia,
        mes,
        ano,
        credito,
        debito,
    @dc := dc AS tipo,
    @saldo := IF(@dc = 'C', @saldo + credito, @saldo - debito) AS saldo
    FROM lc_movimento, (SELECT @dc := 'C', @saldo := 0) as vars
    ORDER BY ano, mes, dia
) AS extrato

Este é o link da demo:
Tabela no SQL Fiddle
Este é o resultado desejado.

    mês   ano     credito   debeito          saldo
    5     2014     2500     8722,6          -6222,6
    6     2014     0        12792,96        -19015,56
    7     2014     0        10884,82        -29900,38
    8     2014     0        10884,82        -40785,2
    9     2014     0        10022,68        -50807,88
    5     2015     650      7580,25         -57738,13
Answer: Consegui chegar ao resultado mas tive que criar um VIEW. Usei uma dica do @Maniero e deu tudo certo.
Me cheira uma gambiarra, mas funcionou.
Segue o link demo SQL Fiddle.
SELECT DATE_FORMAT(data,'%d/%m/%Y') AS data,
    SUM(IF(tipo = 'D', valor, 0)) AS debito,
    SUM(IF(tipo = 'C', valor, 0)) AS credito,
    (SELECT SUM(IF(tipo = 'C', valor, -valor)) FROM vw_extrato AS L2
         WHERE DATE_FORMAT(vw_extrato.data,'%Y%m') >= DATE_FORMAT(L2.data,'%Y%m')
    ) AS saldo
FROM vw_extrato
GROUP BY MONTH(data), YEAR(data) ORDER BY data desc

Comment: A *view* não é necessária mas até facilita a leitura da consulta. Aceite sua resposta.


jqPlot loading via AJAX

Question: I don't think I'm understanding JSON completely, here is my code:
$.ajax({
            type: "POST",
            url: baseurl + "analytics/grab_points"
        }).done(function(data) {
            console.log(data);
            var line1=$.parseJSON(data);
            console.log(line1);
            var plot2 = $.jqplot('chartdiv', line1, {
                title: 'Customized Date Axis',
                gridPadding: {right: 35},
                axes: {
                    xaxis: {
                        renderer: $.jqplot.DateAxisRenderer,
                        tickOptions: {formatString: '%b %#d, %y'},
                        min: 'May 30, 2008',
                        tickInterval: '1 month'
                    }
                },
                series: [{lineWidth: 4, markerOptions: {style: 'square'}}]
            });
        });

jqPlot seems to expect data like so:
[['2008-06-28 8:00AM', 4], ['2008-6-30 8:00AM', 1], ['2008-8-30 8:00AM', 5.7]]

(that should the content in var line1)
My server side code (PHP):
$test=array(
            "2008-06-28 8:00AM" =>4,
            "2008-6-30 8:00AM" =>1,
            "2008-8-30 8:00AM" =>5.7,
        );

        echo json_encode($test);

My console logs:
{"2008-06-28 8:00AM":4,"2008-6-30 8:00AM":1,"2008-8-30 8:00AM":5.7} analytics:103
Object {2008-06-28 8:00AM: 4, 2008-6-30 8:00AM: 1, 2008-8-30 8:00AM: 5.7} analytics:105
Uncaught Error: No data specified

Pretty sure I'm going barbarian on this JSON (growing pains), any idea would be great.
Answer: if you want to get the same structure that jqPlot wants you'll have to change your array in your php code...
jqPlot is expecting something like in your php array-structure:
$test = array(
    array("2008-06-28 8:00AM",4),
    array("2008-6-30 8:00AM",1)
);

check example 2 on http://php.net/manual/en/function.json-encode.php (the $c)
the {} you see is just because you output it as object rather than as array, but this should be the same as the [] (this is also explained on the php manual)
EDIT: also i don't think this line: var line1=$.parseJSON(data); is still needed because your data is already json.

jqPlot loading via AJAX


Classe derivada da classe PrintDocument C#

Question: Tenho uma classe para imprimir etiquetas (CPrint), essa classe é derivada da classe PrintDocument. Nela recebe uma imagem chamando um método contido na classe Form1.cs.
Segue o código da classe CPrint.cs (derivada da classe PrintDocument):
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;

namespace WindowsApplication1
{
class CPrint : PrintDocument
{
    private Font printFont;
    private TextReader printStream;
    private string fileToPrint;
    private Bitmap imgWatermark, bmpImg;

    public bool Watermark = false;

    public CPrint()
    {
        Form1 principal = new Form1();

        imgWatermark = principal.enviaImg();  //ESSE TEM QUE RECEBER A IMAGEM

    }

    public CPrint(string fileName) : this()
    {
        this.FileToPrint = fileName;
    }

    public string FileToPrint
    {
        get
        {
            return fileToPrint;
        }
        set
        {
            if (File.Exists(value))
            {
                CPrint p = new CPrint();
                fileToPrint = value;
                this.DocumentName = value;
            }
            else
                throw (new Exception("File not found."));
        }
    }

    public Font Font
    {
        get { return printFont; }
        set { printFont = value; }
    }

    protected override void OnBeginPrint(PrintEventArgs e)
    {
        base.OnBeginPrint(e);
        printFont = new Font("Verdana", 10);
        printStream = new StreamReader(FileToPrint);
    }

    protected override void OnEndPrint(PrintEventArgs e)
    {
        base.OnEndPrint(e);
        printFont.Dispose();
        printStream.Close();
    }

    protected override void OnPrintPage(PrintPageEventArgs e)
    {
        base.OnPrintPage(e);

        // Slow down printing for demo.
        System.Threading.Thread.Sleep(200);

        Graphics gdiPage = e.Graphics;
        float leftMargin = e.MarginBounds.Left;
        float topMargin = e.MarginBounds.Top;
        float lineHeight = printFont.GetHeight(gdiPage);
        float linesPerPage = e.MarginBounds.Height / lineHeight;
        int lineCount = 0;
        string lineText = null;

        // Watermark?
        if (this.Watermark)
        {
            int top = Math.Max(0,
                     (e.PageBounds.Height - imgWatermark.Height) / 2);
            int left = Math.Max(0,
                     (e.PageBounds.Width - imgWatermark.Width) / 2);
            gdiPage.DrawImage(imgWatermark, left, top,
                     imgWatermark.Width, imgWatermark.Height);
        }

        // Print each line of the file.
        while (lineCount < linesPerPage &&
              ((lineText = printStream.ReadLine()) != null))
        {
            gdiPage.DrawString(lineText, printFont, Brushes.Black,
            leftMargin, (topMargin + (lineCount++ * lineHeight)));
        }

        // If more lines exist, print another page.
        if (lineText != null)
            e.HasMorePages = true;
        else
            e.HasMorePages = false;
    }
}
}

O que está dando errado é que o nome do documento que não é adquirido e com isso no método OnBeginPrint nesta linha printStream = new StreamReader(FileToPrint); não recebe o retorno do método FileToPrint porque ele (método FileToPrint) só executa a parte get do código e não o set que onde deveria adquirir o nome do arquivo.
Desde já agradecida!
Comment: Quem escreveu essa classe `PrintDocument`?
Comment: A classe `PrintDocument` é do próprio C# para impressão.
Comment: @kaamis aplicação desktop ou web ? e descreva objetivamente qual funcionalidade você quer realizar no click desse botão !?
Comment: @ThiagoFalcão é desktop. Quero que quando o botão é clicado apareça a caixa de diálogo de impressão do Windows e realize uma impressão a partir da classe CPrint derivada da PrintDocument. Contudo, consegui achar um código para chamar a classe, que é bem simples afinal, o meu problema agora é que não imprime pois o nome do documento não é adquirido pelo método FileToPrint. Irei até editar a pergunta.
Comment: Cole aqui o código que você usa para invocar a impressão.
Comment: @FernandoNomellini segue o código que está num botão para invocar a impressão:
`CPrint printDoc = new CPrint();
            PrintDialog dlgPrint = new PrintDialog();

            dlgPrint.Document = printDoc;

            if (dlgPrint.ShowDialog() == DialogResult.OK)
            {
                printDoc.Print();
            }`
Answer: Me parece que você está usando o construtor errado.
Seu código do botão.
Print printDoc = new CPrint();
rintDialog dlgPrint = new PrintDialog();
lgPrint.Document = printDoc;
f (dlgPrint.ShowDialog() == DialogResult.OK) { printDoc.Print(); }

Você não acha que deveria ser usado este :
Print printDoc = new CPrint("NomeDoDocumentoASerImpresso");

Pois é o construtor que recebe o nome do documento e associa à propriedade privada fileToPrint
Comment: @FernandoNomellini eu salvei a imagem e peguei o nome dela. Enfim deu certo mas, depois veio outro erro e descobri que a classe derivada não dava para imprimir imagens. Aí resolvi ao invés de gerar uma imagem gerar um arquivo texto, porque eu quero imprimir etiquetas que contenham códigos de barras, e consegui usar uma fonte específica. Assim deu certo. Muito obrigada pela ajuda!
Comment: Entendi o que quis dizer, eu tenho que enviar a imagem também pois é ela que vai ser impressa. Ou só com o nome do bitmap gerado eu já consigo fazer isso? Poderia deixar o construtor que está e adicionar este que você falou? Um para chamar e receber a imagem e outro com o nome do documento?
Comment: Kaamis, você precisa imprimir um determinado arquivo, e junto com ele, a imagem, correto ? Tente alterar o programa usando o codigo que eu te passei. Troca apenas a linha que eu indiquei passando o nome de um arquivo. veja se funciona. Pelo que eu vi, a imagem já será carregada mesmo usando o construtor que recebe o nome do arquivo.
Comment: Na verdade preciso imprimir somente a imagem. Desculpe a ignorância mas como posso obter o nome da imagem gerada? Ou seria o nome da variável bitmap?
Comment: tem algumas formas, como esta: FileStream fs = new FileStream(openFileDialog1.FileName , FileMode.Open, FileAccess.Read);
dê uma olhada: http://www.macoratti.net/09/09/c_prn1.htm


Como colocar dados de db em mais de um fragment?

Question: Eu quero colocar os dados do banco em fragments, em um swipe, não uma lista, onde cada registro seja carregado em um fragment diferente.
Comment: Então. Cada fragment exibiria uma pessoa cadastrada no banco, e neste mesmo fragment teria um pequeno formulário para responde-la. Eu consegui um exemplo em um livro que apresenta os fragments em lista, mas eu precisaria que fosse um swipe. Ficou mais claro?
Answer: O ideal seria entender melhor seu objetivo final, mas você poderia conseguir este efeito criando um RecyclerView com um LinearLayout horizontal. Fazendo apenas uma consulta ao banco e alimentando o RecyclerView com o cursor. O RecyclerView é bem eficaz e econômico.
Outra possibilidade seria utilizar Swipe Views
Como falei, depende muito do seu objetivo. Acho que você poderia estudar um pouco estas opções.


Estouro Aritmético C++

Question: Olá, sou iniciante na linguagem C++, fazendo alguns exercícios me deparei com uma mensagem que não interferiu em nada minha conta, porém gostaria de saber exatamente o que ela significa e o que teria que fazer para deixar esse calculo 100% certo para o c++.
#include <iostream>
#include <locale.h>
using namespace std;

int main() {
    setlocale(LC_ALL, "");

    float r, a;

    cout << "Digite o raio de um circulo: ";
        cin >> r;

        a=3.14 * (r * r);//Erro de estouro nessa linha

        cout << "\nA área de um circulo com " << r << " de raio é igual a " << a <<"\n\n";

    return 0;
}

C26451: Estouro aritmético usando o operador '' em um valor de byte 4 e, em seguida, convertendo o resultado em um valor de byte 8. Converta o valor no tipo mais amplo antes de chamar o operador '' para evitar estouro (io.2).
Desde já, agradeço.
Comment: A constante `3.14` é considerada como do tipo `double` e você declarou `float r, a;`. Para trabalhar apenas como `float` utilize `a = 3.14f * (r * r);`. (um f ao final da constante de ponto flutuante indica que ela é do tipo float).
Answer: O tipo double tem mais precisão que o tipo float.
Você pode alterar o tipo das variáves r e a pra double ou mudar o literal para 3.14f para que seja interpretado como float. Se não colocar o sufixo f o valor vai ser interpretado como double.
Comment: Muito interessante, após algumas pesquisas consegui entender a diferença de float para double, muito obrigado pela ajuda!
Answer: O aviso C26451 é disparado para indicar que o operador atual é usado em tipos que comportam uma quantidade maior de informações, ou seja, existe a chance de perda de dados (precisão dos números resultados da expressão). Para isso, você pode tentar converter o tipo da variável durante a operação como nos exemplos do link que deixei de referência.
Comment: Ajudou bastante, muito obrigado!

Estouro Aritmético C++


How to align the output of the elements in JSP?

Question: I'm having some trouble aligning the output form the my JSP code
it looks like this
And i want it formatted in a nice way and i don't know how to do it
            <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
                pageEncoding="ISO-8859-1"%>
            <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Weather Manager</title>

                <form action=/Orange_assignment/Login>
                    Email : <input type="text" name="Email" align="left">

                    Password: <input type="text" name="Password" align="left">

                    <button type="submit" align="left"> Login!</button>
                    Login using your credentials
                </form>

                <form action='Signup.jsp' method=POST>
                    <button type="submit">Signup!</button>
                    Not a user? Signup!

                </form>

Comment: If you have eclipse, select all by `Ctrl+A` and do `Ctrl+Shift+F`, it will format automatically.
Answer: Further to previous answer using tables for layout is considered bad practice (Why not use tables for layout in HTML?) but I suppose we've all done it (all us non-designers anyway). However with the advent of the Twitter Bootstrap library we can now all make great looking forms*:
http://getbootstrap.com/css/#forms-horizontal

Designers may not share this view.
Answer:

   Email :	 <input type="text" name="Email" align="left">

   Password:	<input type="text" name="Password" align="left">

   <button type="submit" align="left">Login!</button>

Answer: You can make use of the table tag and assign border 0. This will help you indent and format the way you want. Below is the code of yours:
<!DOCTYPE html>

    Email
    <input type="text" name="Email" align="left">

    Password
    <input type="text" name="Password" align="left">

Modify it as per your requirements.
And below is the output of the code i gave you.


Find number of all spanning tree of $G_n$

Question:
Find $d_n$ which is number of all spanning tree of $G_n$ where $V =
 \left\{ 0,1,...,n  \right\} $ and $$E = \left\{ \left\{ 0,i \right\} :
 i \in [n]  \right\} \cup   \left\{ \left\{ i,i+1 \right\} : i \in
 [n-1]  \right\}  $$

This is our graph

And I found that
$$ d_n = 2d_{n-1} \text{ for } n \ge 4$$
$d_1 = 1$
$d_2 = 1$
$d_3 = 3$
But the pattern looks too simple, can somebody verify that?
Answer: I think you messed up the indices. $d_0=1, d_1=1, d_2=3$.
Looking for a recursion is a good idea (probably the right approach). But again, you made a small mistake.
Case 1: the edge $(0,n+1)$ is in the tree but $(n,n+1)$ is not. Then there are $d_n$ solutions.
Case 2: the edge $(0,n+1)$ is not in the tree but $(n,n+1)$ is there. Then there are $d_n$ solutions.
Cse 3: both edges containing $(n+1)$ is in the tree. I claim that there are $d_0+d_1+\cdots +d_{n-1}$ solutions in this case. (Think about it.)
So the recursive rule is $d_{n+1}=d_0+\cdots +d_{n-1}+2d_n$. (This also works for $n=2$.)
Seems to me that this gives $d_n= F_{2n}$ for $n\geq 1$.
Comment: You are right that I have missed case 3 but are you sure that in third case it will be $d_0+d_1+\cdots +d_{n-1}$, not just $d_n$? Previous form of graph is still obtained in $d_n$ ways.
Comment: Think about it! Make a sub case distinction in terms of where the path on the first level ends that starts with the edge $(n+1,n)$.
Comment: by $(n+1,n)$ you mean $(0,n)$, yes?
Comment: Please, draw a picture, and think about my answer before asking for further details. I meant what I wrote. (If after 10-15 minutes thinking you still don't understand, then it is OK to ask for clarification. But you are asking more immediately, without investing any effort.) I have corrected your mistake and provided all the main ideas you need for the solution. It is your turn to work now.
Comment: you have right A.Pongracz, give me some time.
Comment: I have drawn some cases and currently I understand that the third case is other than first and second because edges can be transformed (or just removed in some cases because we have already touch them): http://i.imgur.com/OdqFasP.png But I still not sure why we add $d_0$ $d_1$ etc because as I marked for example on red color: red edge (and blue from new vertex) contains: 1;0;3;4 but no 2.
Comment: $n+1$ is connected to $0$ and to $n$. Think about the edge $(n+1,n)$ as the first edge in a path. This path can end in $n$ vertices: $n$, $n-1$, ..., $1$. If it ends in $k$, then $0$ is not connected to $k, k+1, \ldots, n-1$, so that part of the tree is known. The only question left is how to connect the vertices $0,1,\ldots, k-1$. This can be done in $d_{k-1}$ ways by the definition of the sequence $d_n$. So depending on $k$, which can be $1, \ldots, n$, we have $d_0, \ldots, d_{n-1}$ possibilities, respectively.
Comment: I know where I failed! It is obvious that spanning tree doesn't contain cycles but in my thinking I didn't take into account that (because if we connect any vertex from out path to $0$ we get a cycle!!!!!!!) Thanks professor for great tips!
Comment: Can I ask you additional question - do you recommend some book, set of task to discreet mathematics with level of task similar to this?


Twitter follow Drupal

Question: I want to show a list of Twitter users who is following a post, with a button that allows the users to follow them. The list should appear as in the following screenshot.

I have tried using the Twitter, and oAuth modules but I had no luck, so far.
Comment: Source for above image, apparently from Quora: http://www.quora.com/Drupal-CMS/Has-the-Twitter-module-for-Drupal-6-been-modified-so-it-works-again-after-Twitter-recently-switched-to-oauth-only/followers
Comment: Links for you: https://dev.twitter.com/docs/api/1/post/friendships/create
Answer: It looks like from the output image above you are trying to create a widget that would show a select number of twitter users from either your own followers or from a specific list, etc. I would suggest that this is not a Drupal issue or at least you shouldn't try and treat it as one. You could do this by creating a content type and outputting it as a view using a view template, etc. but thats a lot of database overhead for data that will likely be changing frequently.
The better way to do this is to use a jQuery / javascript plugin that will pull the data as a json file from your source (either a followers feed or your list feed from twitter) and output it directly. You can use any number of existing plugins and widgets available online for this, ex. this one:
http://twittercounter.com/pages/buttons
or roll your own, but further details would be out of scope for this site.
Finally, I'd recommend that you take a look at the site you got that image from first and see if you can figure out what widget it is using, I'd bet that they are using an open widget / plugin that you can then just copy for your own site.

Twitter follow Drupal


simple inequality question involving positive integers

Question: There are two numbers $x,y$ such that $x+y=N-1$ and there are also two numbers $a,b$ such that $a+b=N$
Then it is said that there can be only two cases: $x\geq a$ or $y\geq b$
All numbers $x,y,a,b,N$ are natural numbers.
I do not understand why are these two are the only possible cases. Can someone help me visualize this?
Comment: It might help to list the possibilities for $N=5$, for example, if you want to help your intuition.  You probably don't have to list them all before you see it.
Comment: Supposing both $x\lt a$ and $y\lt b$ you have $x+y\lt a+b$.
Answer: Both of them cannot be true because that would mean $N=a+b\leq x+y \leq N-1$, which is impossible. If neither of them is true, then $x \le a - 1$ and $y \le b - 1$, i.e., $N-1 = x+y\leq a-1+b-1=N-2$, which is again impossible.


How to refactor Swift API call to use Swift 5.5 async/await?

Question: I want to refactor some API calls to use Swift 5.5's new async/await in my SwiftUI project.  However, it's unclear to me how to replace or accomodate the completions.
Here's an example function which I want to refactor:
 static func getBooks(completion: @escaping ([Book]?) -> Void) {
    let request = getRequest(suffix: "books")

    URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            fatalError("Error: \(error)")
        }
        if let data = data {
            if let books = try? JSONDecoder().decode([Book].self, from: data) {
                DispatchQueue.main.async {
                    print("books.count: \(books.count)")
                    completion(books)
                }
                return
            } else {
                fatalError("Unable to decode JSON")
            }
        } else {
            fatalError("Data is nil")
        }
    }.resume()
}

I beleve the new function signature would look something like this:
static func getBooks() async throws -> ([Book]?) {
   // ...
}

However, I have no idea what to do with the URLSession.shared.dataTask, DispatchQueue.main.async and completion, etc.
Anyone know what the new function body should look like?
Thanks
Comment: [Meet async await](https://developer.apple.com/wwdc21/10132) about minute 26:59
Comment: Watch through [WWDC 2021 – Swift concurrency: Update a sample app](https://developer.apple.com/videos/play/wwdc2021/10194/). It's an entire hour code-along video that takes you step by step through how to progressively migrate parts of an app. The parts they chose to replace have a nice variety of real-world patterns to them, so it's a reallllllly great/applicable video.
Answer: func getBooks() async throws -> [Book] {
    let (data, _) = try await URLSession.shared.data(for: request)
    return try JSONDecoder().decode([Book].self, from: data)
}

This will throw if the request fails, and if the response cannot be decoded. Since the function is marked as throwing, then the calling function has to handle the raised errors.
You don't need to declare the returned [Book] to be optional, because it will either return an honest array, or throw an error.
In your additional code, you had to call your completion handler on the main queue, because you were calling it from within the completion block of the request. You don't need to do that here.


PDFBox - Setting Cover Sheet for PDF Portfolio

Question: I am creating a PDF portfolio from scratch using PDFBox 2.0.16.  I create the PDF and add attachments.  Once the attachments are added, I then create the PDF Portfolio.  The following is the code to create the PDF Portfolio/Package.
COSDictionary collectionDictionary = new COSDictionary();
collectionDictionary.setName( COSName.TYPE, "Collection" );
collectionDictionary.setName( "PDF Filename", "T" );
PDDocumentCatalog catalog = pdfDoc.getDocumentCatalog();
catalog.getCOSObject().setItem( "Collection", collectionDictionary );
pdfDoc.save( pdfFile );

When I open the PDF, the Cover Sheet is a blank page.  I would like the Cover Sheet to be the first attachment in the PDF Portfolio/Package so that when a user opens the PDF, the 1st attachment in the portfolio is viewed.
Comment: Please read this https://svn.apache.org/viewvc/pdfbox/branches/2.0/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreatePortableCollection.java?view=markup
Comment: I followed the code and the PDF portfolio is created and opens in Adobe with the list of embedded files.  However, it opens to the page that reads "Example of a portable collection".  Is there a way for to open the first embedded file when opening the PDF?  Thanks.
Answer: What somewhat worked for me (it positioned to this file, as if I had clicked on it in the list) is this:
collectionDictionary.setString(COSName.D, "Attachment 1");

where "Attachment 1" is the name used in the name tree in this example.


Controle 'ContentPlaceHolder1_Nome' do tipo 'TextBox' deve ser inserido em uma marca de formato com runat=server

Question: estou fazendo um trabalho para a faculdade, uma aplicação web forms em Asp.net C#. Estou com um problema e até então estava indo tudo bem, mas do nada está dando este erro. Procurei algumas coisas relacionadas, e este trecho acabou "mostrando" minha página web, mas não realiza nenhuma ação:
public override void VerifyRenderingInServerForm(Control control){ }

Erro e as exceções:

Controle 'ContentPlaceHolder1_Nome' do tipo 'TextBox' deve ser inserido em uma marca de formato com runat=server.
Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.
Detalhes da Exceção: System.Web.HttpException: Controle 'ContentPlaceHolder1_Nome' do tipo 'TextBox' deve ser inserido em uma marca de formato com runat=server.
Rastreamento de Pilha:
[HttpException (0x80004005): Controle 'ContentPlaceHolder1_Nome' do tipo 'TextBox' deve ser inserido em uma marca de formato com runat=server.]
     System.Web.UI.Page.VerifyRenderingInServerForm(Control control) +9766490
     System.Web.UI.WebControls.TextBox.AddAttributesToRender(HtmlTextWriter writer) +52
     System.Web.UI.WebControls.WebControl.RenderBeginTag(HtmlTextWriter writer) +20
     System.Web.UI.WebControls.TextBox.Render(HtmlTextWriter writer) +21
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +66
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +128
     System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +13
     System.Web.UI.Control.Render(HtmlTextWriter writer) +12
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +66
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +128
     System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +13
     System.Web.UI.Control.Render(HtmlTextWriter writer) +12
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +66
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +128
     System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +13
     System.Web.UI.Page.Render(HtmlTextWriter writer) +29
     System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +66
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
     System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
     System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1303

Código do meu Login.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login_Login" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

ENTRAR

NOME

                <asp:TextBox ID="Nome" Width="200px" runat="server" CssClass="form-control" placeholder="Login" aria-describedby="basic-addon1"></asp:TextBox>

                    SENHA

                    <asp:TextBox ID="Senha" Width="200px" TextMode="Password" runat="server" CssClass="form-control" placeholder="Senha" aria-describedby="basic-addon1"></asp:TextBox>

                <asp:Button ID="Entrar" runat="server" OnClick="Entrar_Click" Text="Entrar" CssClass="btn btn-primary btn-success" />

                <asp:Label ID="Mensagem" runat="server" Visible="false" CssClass="alert alert-danger" role="alert"></asp:Label>

</asp:Content>

Login.aspx.cs
public partial class Login_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }
    }

    protected string conn = @"Data Source=PC-OSV;Initial Catalog=CadastroCompetencias;Integrated Security=True;";
    AppDatabase.SqlServerTransaction db = new AppDatabase.SqlServerTransaction();

    protected void Entrar_Click(object sender, EventArgs e)
    {
        if (ValidaUsuario(Nome.Text, Senha.Text))
        {
            // Inicializa a classe de autenticação do usuário
            FormsAuthentication.Initialize();
            //Define os dados do ticket de autenticação
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Nome.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, Session["Perfil"].ToString(), FormsAuthentication.FormsCookiePath);
            // Grava o ticket no cookie de autenticação
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
                 FormsAuthentication.Encrypt(ticket)));
            // Redireciona para a página do usuário
            Response.Redirect(FormsAuthentication.GetRedirectUrl(Nome.Text, false));
        }
        else
        {
            Mensagem.Visible = true;
            Mensagem.Text = "Oops... Login ou senha errados! Verifique se você não errou nada.";
        }
    }

    ///
    /// Autentica o usuário e retorna true se foi autenticado com sucesso
    ///
    protected bool ValidaUsuario(string nome, string senha)
    {
        db.ConnectionString = conn;
        DataTable tb = (DataTable)db.Query("SELECT * FROM Usuarios WHERE NomeAcesso='" + Nome.Text + "' AND Senha='" + Senha.Text + "' AND Estatus=1;");
        if (tb.Rows.Count == 1)
        {
            // Armazena na dados do usuário nas variáveis de sessão
            Session["CodigoUsuario"] = tb.Rows[0]["CodigoUsuario"];
            Session["NomeUsuario"] = tb.Rows[0]["NomeCompleto"];
            Session["Perfil"] = "Administrador";
            return true;
        }
        else
        {
            return false;
        }
    }

}

Conto com a colaboração de vocês! Grato desde já!
Comment: Tente abrigar o conteúdo da sua página com uma tag ``
Comment: Então Eric, eu já tenho na minha MasterPage um form contendo runat="server"
Answer: Achei a resposta pessoal!
No meu caso, a tag </form> estava em lugar errado, acabei fechando ela no final do meu conteúdo, que no meu caso, na MasterPage, tenho um . E agora está tudo funcionando corretamente!


Can excel formulas be written in a non-nested format?

Question: Does excel have an alternative method of writing nested formulas? For example, is it possible to write a continuation formula?
Comment: now if you have Office 365 you can use `LET`: `=LET(a,A3*B3,ROUND(a,2))`
Comment: Your question doesn't really make sense to me, but I suspect the answer is no.
Comment: No, you cannot refer to the same cell in which the formula is placed.
Comment: @JB-007 yes you have provided an answer with an assumption.  It is a good and well thought out answer.  One, that I happen to disagree with.  I have stated why in my comment below.  I think it a viable answer and enjoyed reading it.
Comment: @ScottCraner That's very handy! Thank you.
Comment: @Scott Craner I challenge your comment RE: "*No, you cannot refer to the same cell in which the formula is placed*" - unless I'm reading out of context (not sure I am) - here are a couple of examples: 1) row(),column(), cell() can reference same cell as function 2) offset() starting cell can refer directly to same cell as this function 3) sumifs({same col. as function}, {adjacent col. <> adjacent cell}) etc... 4) iterative calculation mode allows you to input *=A1* in cell A1 (without circular reference).
Further, you *can* always do this but may create a circular reference as a result..
Comment: Yes you are correct on those example, but in regards to what the OP is asking it cannot be done with out circular reference. And circular reference is fraught with issues and is not recommended because the allowing of circular reference is app wide and not specific to the single cell, and it changes by user and must be routinely allowed. @JB-007 Also in regards to what is being asked here a circular reference would not work either.
Comment: Hmm @Scott Craner - I do not disagree with your view RE: circular references but, with due respect,  I beg to differ RE the specific question in hand - which need not entail / involve circular references - see references at bottom of my soln for practical applications that deal with 'circularities' provided scope and calc modes are administered / applied in appropriate fashion...
Comment: I second what @ScottCraner said - this approach is fraught with issues.
Comment: Results can be meaningful and purposeful in financial mathematics (future streams of fin. payments), biology (spread of virus, quite topical) - further - complex eqns/algorithms  can be solved in a unique fashion. The question did not request advice RE applications that may be outside the scope of one's expertise - merely "can it be done" - I have successfully implemented this and when done in a refined/specific scope for a particular purpose - the examples / references provided show practical output.  (Microsoft have included this functionality for the very applications I mention)..
Comment: @ScottCraner - I have reverted.  We appear to be an impasse  - your challenges (which go way beyond scope of OP q) can be easily mitigated.  Not sure its purposeful for me to carry on bullet proofing - A) "it can be done" - tick.  B) "it has practical / purposeful applications (academic references) - tick - I know they are a headache in ordinary/routine applications - no dispute - one should not rule out use / value in maths/simulation etc. (workbook sharing aside) due to personal experiences/field of application.  Glad you enjoyed - appreciate your remarks in this regard.  have a good one!
Answer: You can indeed input such a function. Further, functionality of the feature I describe (iteration) can be paramount to several specialist fields in academia (Actaurial, Statistical - simulations, Microbiology).  There have been numerous case studies, journal articles etc. on this application within Excel (referenced below).
In your example you add the product of the A3*B3 to rounded (2dp) value of itself --  set calculation mode to iterative with max iterations = 1 (manual or auto calc modes explained below) to yield in the first computation/iteration the desired value:

Note: no circular reference issues!

Iterative calc options are deliberate : i.e. manual mode without 'recalc when saved' - every time you calculate the sheet/workbook (e.g. shift + F9 or F9 resp.(♣) this result is added back to itself (by definition).  Thus you will return values that increment by a constant 8.99 per below:

♣ See below for nuances/additional info RE: F9 (workbook) vs. Shift F9 (worksheet) & manual vs. auto calc modes)
Generalising to other popular examples
More generally, the ability to expand / represent what you refer to as 'nested formula' in continuation form depends upon the mathematical equivalence between the nested and 'continuation' representations.  As an example, consider the sum of the first 10 terms of geometric sequence with initial term = 100, constant multiplier = 1.02:
= 100 + 100*1.02^1 + 100*1.02^2 + .... + 100^1.02^10
= 1094.97

Using elementary mathematics this simplifies to the following:
= 100(1.02^10 - 1) / 0.02
(= 1094.97)

In turn, one can simply use the FV function (given this is analogous to a loan to repay the future value of a stream of 10 payment of 100, compounding at 2% interest:
=-FV(0.02,10,100)
(= 1094.97)

In the context of your question vs. iteration mode, you can automatically advance the iterative calculation for 10 iterations by setting calc mode to automatic (in which case the result increments by a further 10 terms of the geometric sequence every time the workbook is modified, opened or closed, or recalculated directly by pressing F9).  To see the calculation at each step of the iteration in auto calc mode simply calc the sheet alone (Shift +F9). RE: F9 vs. Shift F9 - the same holds true when in manual mode.
The key difference (as before) with manual is that this result will not automatically update whenever the workbook / worksheet is modified (as is the case with auto calc).
You could even set to manual with iterations = 1, and hit F9 10 times to see how sum of installments accumulate / progress over the period):

With these settings, a similar function to the round formula you presented will achieve the summation of 100 to the product of itself and 1.02 exactly 10 times... giving the exact same soln as the 3 alternative representations above, viz:

Notes: inputs are custom formatted: types for cells C3, C4: "initial term :" # and  "constant ratio: "#,##0.00 resp.  See here for further details in this regard.

Practical applications / other references
RE: iteration - see here for technical detail RE: functionality/operation and here for several usefil (incl. related/geometric + other) applications.
For VB manipulation you can specify # iterations using Application.MaxIterations = 10 (or other desired #) - see here for instance.

** Academic / specialist fields of application**
Charting exponential decay / related applications:
here
Simulation in assessing marketing risk here
Optimisation in Excel here
Numerical methods in mathematics using Excel here
Oxford Academic journals RE: various applications here
Circular references have attracted a poor stigma due to the regular/standard  way tend to crop up.  However, when utilised in an appropriate, controlled manner, the above is a small sample of several highly useful applications that would be difficult to replicate without their use (in conjunction with iteration).
Comment: Okay, now share this with someone else or open it on a different computer.  The formulas do not work and require the allowing of circular reference in the full app.  One cannot save or apply this setting to this workbook itself.  And sometimes even just closing and reopening the app will cause this setting to reset to the default. requiring every time on opening it the user must to go back in the settings and allow circular references.  You can always use vba in the Workbook_Open to set that setting, but if I opened a workbook that changed that setting for the whole app, I would be pissed.
Comment: Hi - not sure what the assumption is that you refer to in penult. comment.  Re sharing: flaws you are bringing into Q go way beyond the scope of the original Q - notwithstanding 'none-issues' - a) assume one could provide 'setup' documentation in context of email? b) If intention is to share 'carte-blanche' (odd for highly specialised/niche topic) - then basic VB should do e.g. Private Sub Workbook_Open(), .Iteration = True, .MaxIterations = 10, .MaxChange = 0.001, End With, End Sub.  If Q is now "what about my macro security settings" ... well, then you have me ! No need to use foul language.
Comment: sorry about the `pissed` I meant it no more than `I would be very upset` I was running out of characters and `upset` did not give enough importance.  as to assumption, The assumption I am refering to is that it is meant to be compounding.  I had assumed that the OP wanted to not have to refer to the same formula multiple times ie: `=IF(ROUND(A1*B1,2)>9.01,ROUND(A1*B1,2),0)` type of item.  Which is the assumption I was making.
Comment: As to the other questions.  It all boils down to that using circular references can be avoided in 99% of the cases. Why go through the nightmare of having to teach people how to adjust their settings in an app just to make the formula work, when there are other alternatives that do not require it.  Again I am not knocking your answer.  I think that there may be some that need this answer. Some others may find it useful.
Comment: cheers.  Niche area - I know.  Interesting topic - have enjoyed sharing / debating views.  You have valid pts. re concerns - I realise/appreciate this..  99% frought with issues - agree through/through.  Caveat warranted in this regard. (PS - np RE: synonym for 'upset' - I see what you mean - could see myself feeling same ! :) )


Verification mail goes to Spam Folder

Question: If the user register, the confirmation mail goes to spam folder.  After doing some R&D, I enabled "Use two e-mail fields on registration form > Set password" and tested; it goes to inbox from the web server. But as i badly need to show the demo to my supervisor from my local server instead of live, using "Acquia Dev Desktop", it goes to the spam folder. How can I prevent the message from going to the spam filter?
Comment: Email id in your Site Information and Your mailer library should be same. May be it can be reason.
Answer: You should use the SMTP Authentication Support module: http://drupal.org/project/smtp  for sending email messages. You can go there: https://stackoverflow.com/questions/8939238/gmail-smtp-configuration-for-drupal-7 to see how they can use the SMTP Authentication Support module with Google Account.

Verification mail goes to Spam Folder


When $ E(1/X) = 1/E(X)$?

Question:
Given a random variable $X$ that is nonzero a.e. and $E(X) \neq 0$,
$E(X) * E(1/X) = 1$ means $X$ and $1/X$ are uncorrelated.
Let's rule out  the case when $X$ is constant a.e.. Then $X$ and
$1/X$ are not independent. Then when are $X$ and $1/X$
uncorrelated? Or some well known cases or examples in probability
and stochastic processes?
My question comes from that in Little's law in queueing theory,  the
arrival's rate is defined as $1/E(X_i)$, where $X_i$ is an
interarrival time. Can it be defined as $E(1/X_i)$?

Thanks.
Comment: See the last sentence here: https://en.wikipedia.org/wiki/Jensen%27s_inequality#Measure-theoretic_and_probabilistic_form
Comment: Think about the following question when is $\int dx/f(x) = 1/(\int f(x) dx$?:
Answer: If $X>0$ then $E(1/X)\ge 1/E(X)$ because $1/x$ is concave up.
For example if $X$ takes three values, equally likely,
$$E(X)E(1/X)=\frac{a+b+c}3\frac{1/a+1/b+1/c}3=\frac{3+\frac ab+\frac ba+\frac ac+\frac ca + \frac bc+\frac cb}9\geq1$$ with equality when $a=b=c$.

When $ E(1/X) = 1/E(X)$?


How change user form mode programmatically?

Question: i create 2 custom user register form mode :

When i go to mysite/user/register
Drupal show me the last form mode i create :

S'inscrire

But when i go in the admin mode, for add a user, it show me the same form.
i try to display "Affichage Admin" form mode with more field.
So i try to alter the form mode programmatically.
Any idea how can i change form mode before it render ?
Comment: You display a screenshot of UI, seems like the first duplicate is right, but I've added a second one for *programmatically*
Comment: You right, i see your post, but it's for custom form, not for alter admin form
Comment: Don't understand why *custom form* or *admin form* is relevant here, you can use form modes for all entity forms. The question is UI only. If it is programmatically, can you show some code?
Comment: Oki, i ll reform this question
Comment: This post not duplicate.
Answer for this is here:
https://www.drupal.org/forum/support/module-development-and-code-questions/2017-05-14/how-to-specifymodify-form-view-mode
Answer: something like this:
<code>/**
 * Implements hook_entity_type_alter().
 */
function YOUR_MODULE_entity_type_alter(array &$entity_types) {
  // We get all form modes, for all entities, and loop through them.
  $form_modes = \Drupal::service('entity_display.repository')->getAllFormModes();
  foreach ($form_modes as $entity_type => $display_modes) {
    if ($entity_type !== 'user') {
      // We are only interested in adding a handler to the Node entity.
      continue;
    }

    $user_entity = $entity_types[$entity_type];
    foreach ($display_modes as $machine_name => $form_display) {
      if ($machine_name !== 'sinscrire') {
        // We are only interested in adding this form mode to the definition.
        continue;
      }
      // We get the default handler class. It will be enough for us.
      $default_handler_class = $user_entity->getHandlerClasses()['form']['default'];
      // We set the form class, keyed by the machine name of our custom form mode.
      $user_entity->setFormClass($machine_name, $default_handler_class);
    }
  }
}
</code>
Credit goes here: https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8


o que é tools:context nos arquivos de layouts?

Question: Bom dia pessoal.
Em alguns tutoriais que andei vendo por aí, os criadores definiam essa propriedade, 'tools:context' no gerenciador de layout principal dos xmls.
Procurei no livro do Ricardo Lecheta, mas ele não usa em nenhum momento isso.
Então.. O que é e qual é a finalidade de definir esse 'tools:context?
Exemplo:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

Obrigado!
Answer: Esse atributo é utilizado para fazer a relação do layout com uma activity.
Por exemplo. Se sua activity usa um tema personalizado você define esse tema no manifesto, se você atribuir o tools:context a essa activity, quando você colocar o Layout para editar em modo de visualização gráfica, teoricamente os layouts deverão aplicar o tema definido para essa activity no manifesto.
Mais detalhes sobre o atributo tools:... entrar aqui.
Answer: Basicamente o tools:context é usado para dizer qual Activity que o Editor de UI deve usar para escolher um tema para renderizar seu layout. E isso tem relação com o Activity Chooser na IDE (Android Studio ou Eclipse).
Resposta baseada nesta pergunta do Stack Overflow EN


AmMap - keeping the same zoom level and position after updating map data

Question: I am updating the map areas of an AmMap map, but the zoom level and position is reset whenever I do.
My function which is updating the map is:
function setData(data) {
    var parsedData = JSON.parse(data);

    map.dataProvider.areas = parsedData.areas;
    map.validateData();
}

I have tried a bunch of things, but I can't get this to work.
Cheers for any help.
Answer: before you update your data, get the current zoom values and pass them into the dataprovider. Take a look to following sample http://www.amcharts.com/tips/retaining-map-zoom-level-position-data-update/
Comment: the zoomLevel method doesn't seem to be working, I get a "Cannot read property 'scale' of undefined" error. Any ideas?
Answer: In addition to Maertz answer, remember to set zoomLatitude and zoomLongitude to zero so you won't get the "Cannot read property 'scale' of undefined" error.
Answer: Try to add var map = event.chart; at the method start.


Testing OLS Model Prediction Accuracy?

Question: How can I test the accuracy of my ordinary least squares model?
Is it a simple comparison between the predicted values of my test set and their actual values (with perhaps a maximum threshold of epsilon -> 0.00001)?
I'm not sure if this is the best approach in terms of accuracy.
Answer: Accuracy as in TP+TN/P+N is used in classification settings; because there you have correct labels and false labels and you want to know how well you are classifying. Since you are using OLS I assume you are in a regression setting. Something like MSE will be better suited I think. Are you in a classification setting with OLS?
Comment: No classification setting :). I have computed the cost after optimization which is 32.072733877455669. Sorry for such a simple question, but using this, how can I test the accuracy on each instance in my testset?
Comment: I'm not sure what you mean by cost, could you give the formulation for cost?

if you are in classification, using OLS is not the best practice for various reasons, it is a straight line that goes over 1 and under 0. You could benefit much better by using logistic regression.

but if you insist on using OLS, treat the values returned by OLS as probabilities, and then choose a cut off threshold, eg 0.5, above which your labels will be 1 and below which they will be 0. Then you can calculate the accuracy, using the above formula.
Comment: Sorry for the confusion, but I'm not in a classification setting, which is why I'm using OLS. I have a straightforward linear regression problem (Predicting house values). I'm using OLS with Batch Gradient Descent (it's a learning exercise, not an actual real-world problem). I know in Logistic Regression you can see whether your model has categorized something correctly by using the formula you mentioned in your answer as a way to test accuracy. I guess my question is what to measure for when testing a dataset against my trained model in OLS for my linear regression problem.
Comment: P.S. By cost I was referring to the computed cost of using theta as the
parameter for linear regression to fit the data points in X and Y. I obtained this by using the Least Squares formula.
Comment: Alright, so you want to measure your models performance on a validation set I suppose. MSE is a good measure, mean squared error:

https://en.wikipedia.org/wiki/Mean_squared_error

you can see it is very similar to the gradient descent cost function. Which is not accidental. Feed your testing X to the model, gather the Y_hats, then compute Y-Y_hat , square it, sum it up and divide by the number of the observations. Just like the Wikipedia page, its a standard measurement for regression problems.

Testing OLS Model Prediction Accuracy?


Is $\det(I+A)\le 1$ if $A$ is a nonnegative matrix with zero diagonals and row sum less than 1

Question:
Is $\det(I+A)\le 1$ if $A$ is a nonnegative matrix with zero diagonals and all row sums less than 1?

I am inclined to say yes. Note by Gershgorin's circle theorem all eigenvalues of $A$ has absolute value less than 1, so we have $\det(I+A)=\exp (\sum_{j=1}^\infty (-1)^{j-1}\frac{\mathrm{tr}(A^j)}{j})$. The $j=1$ term is $0$ since $\mathrm{tr}(A)=0$, and the second order term corresponding to $j=2$ is negative, and this should be the dominant term? If this is not true, what if we further impose the column sums are less than 1?
Edit: Thanks for the counterexample. Bonus question: is there any uniform bound on the entries that can make the assertion true, say 1/4? (this question actually arises in a graph theory problem, and the matrix $A$ has something to do with the squares of the reciprocal of the degree sequence, so in this case entries can have than 1/4)
Answer: As a counterexample, if $$A = \begin{bmatrix}0 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0\end{bmatrix},$$ then $\det(I+A)=2$.
If row sums should be strictly less than $1$, then take $(1-\varepsilon)A$ instead, for a determinant of $1 + (1-\varepsilon)^3 = 2 - O(\varepsilon)$.
For the bonus question: If we take the matrix $\delta A$ for any $\delta > 0$, then we have a matrix whose row sums, column sums, and entries are all bounded by $\delta$, but the determinant $\det(I + \delta A)$ is still bigger than $1$: more precisely, it is $1 + \delta^3$. (Optimizing numerically for some values of $\delta$, it seems like this is the best we can do for $3\times 3$ matrices, and conjecturally, it might be the best we can do in general.)


All squarefree semiprime numbers that less than a certain number

Question: How can i find all number $N$, where $N=p*q$. (Here, $p$ and $q$ are primes and $p<q$) ?
For example: I want a formula that help me to find all $N<1000$
Comment: $1000$ is very small, it should be easy to compute the exact result in that case "by hand" (i.e., using a computer).  In general I do not believe you'll get anything like a closed formula.  Some bounds and asymptotic behavior for the function can be found, e.g., [here](https://math.stackexchange.com/questions/1619742/what-is-an-upper-bound-for-number-of-semiprimes-less-than-n)
Answer: Apply the sieve of sundaram's logic, $$(2a+1)(2b+1)=2(2ab+a+b)+1$$ one of $a,b$ must  less than 16, because if not $a=b$ gives $$4a^2+4a+1>1000$$  Then applying it again you'll need $c$ less than 3, because you can sieve out all values that would not create primes in the product.  Finally you would double all primes less than 500.
Answer: For each prime $p < \sqrt{1000}$, you take $pq$ for each prime $q$ with $p < q < 1000/p$.
EDIT:
As requested, here is some Matlab code.
<code>A = tril(primes(500)' * primes(sqrt(1000)),-1);
sort(A(A > 0 & A < 1000)')
</code>
Comment: Can you write that as codes on MATLAB, please? I tried making that but i always had an error


How do I add an ID to the ul tag of a menu?

Question: I am able to add unique ids to menu links by either adding code to my theme's template file or by using a menu module; however, I would like to add a unique id to the ul tag that encapsulates the menu li links.  The reason that I would like to implement this is to style the menu as a whole instead of the menu's individual links.   My ultimate goal is to take the whole menu and float it to the right in the header-top region of drupal.  I am rather new to Drupal so, perhaps there is another way to achieve this?
I originally attempted custom css styles using the skinr module without success.  The skinr module was able to move the menu's title to the right, but the menu's links were still located at the left of header-top.
My setup consists of Drupal 7
UPDATE
I was able to add a custom CSS class "user-menu" to the user-menu block.  Next I added a custom css to mix-and-match-style.css
css code:
.user-menu ul li {
     padding: 0;
     float: right;
}

The css code seems to float: right the menu, but the links are not ordered properly once floated to the right.  The correct order of the links should be "My account | Log out".  When the list is floated to the right the order changed to: "Log out My account |"
Is that a bug or am I not understanding something?
Answer: You can make use of theme_menu_tree
function theme_menu_tree($variables) {
  return '
' . $variables['tree'] . '
';
}

http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/7
You can print this menu tree
template_preprocess_menu_tree

hereis api
Pre process the menu tree OR Call the menu theme to print it as you want.
Thats all.
Comment: Am I supposed to change 'tree' to the menu name?
Comment: After testing out my question I arrived to the conclusion that I am NOT supposed to change the 'tree to the menu name as doing that throws errors.  I am not exactly sure where to go from here to generate unique class or ID names.  For example, have that function generate "menu-someuniquenumber" as the ul class or id name.
Comment: template_preprocess_menu_tree will help you for sure.
Comment: Ok, I am relatively new to drupal. I am searching google for a learning tutorial about drupal's api calls for this example, but I am not receiving valuable information. I read over drupal's api and the basic example is there; however, I am still unsure how to get this to work.  So far I successfully used theme_menu_tree api.
Comment: template_preprocess_menu_tree can be used to alter the menu tree from your template.php file.
Comment: @NikhilM Where could I place your first code?


Prove the process is a martingale with respect to the natural filtration

Question: Let $\{M_n\}_{n\ge 0}$ be a symmetric simple random walk. Fix a real $b$. Prove that the process $S_n = e^{bM_n} (\frac{2}{e^b + e^{-b}})^n$, $n = 0,1,2,....$, is a martingale w.r.t. the natural filtration $\{\mathcal{F}_n\}_{n\ge 0}$.
I know that a stochastic process is called a martingale if $E[M_{t+s} | \mathcal{F}] = M_t$ but I am confused about how to start this proof. Any help or hints are greatly appreciated!!
Comment: Often the start point of a martingale proof related to Brownian motion/random walk/general Markov processes is to start by splitting $X_t$ into $(X_t-X_s)+X_s$ and looking at the increments.
Answer: Notice that $M_n$ is $\mathcal F_n$ measurable hence so is $S_n$, and $M_n$ is integrable since it is bounded.
It remains to check that $\mathbb E(S_{n+1} \mid \mathcal F_n)=S_n$. To this aim, we have to compute $\mathbb E(e^{bM_{n+1}} \mid \mathcal F_n)$. As $$e^{bM_{n+1}}=\underbrace{e^{bM_{n+1}-bM_n}}_{\mbox{independent of }\mathcal F_n}\cdot \underbrace{e^{bM_{n}}}_{\mathcal F_n\mbox{-measurable}},$$
we get
$$\mathbb E(e^{bM_{n+1}} \mid \mathcal F_n)=e^{bM_{n}}\mathbb E(e^{bM_{n+1}-bM_n}).$$
Comment: Since $(M_n)$ is a symmetric simple random walk, $M_{n+1}-M_n$ takes the values $1$ and $-1$ with respective probabilities $1/2$.
Comment: How do we know what $\mathbb E(e^{bM_{n+1}-bM_n})$ is?


Netflix Zuul stop redirecting / enable reverse-proxy

Question: I have following Zuul configuration. Also I have disabled Eureka since I have service discovery in place.
server:
   port: 7777

ribbon:
  eureka:
    enabled: false

zuul:
  prefix: /api
  routes:
    yourService:
      path: /newpath/**
      serviceId: yourService

yourService:
  ribbon:
    listOfServers: localhost:8080/rest

Now when I hit localhost:7777/api/newpath Zuul does a 302 redirection rather than reverse-proxying transparently. Please advise how to stop this redirection and get Zuul to reverse-proxy transparently.
Comment: @Fahim Farook - Did you find any solution? i too need this..
Comment: Are you sure that zuul is the one sending 302 and not your service?
Comment: Yes. I don't have auth or any other configurations. So it must be Zuul
Comment: Zuul does not do any redirecting.
Answer: Try it with trailing slash as it's in the rule:
http://localhost:7777/api/newpath/