Node.js require becomes extremely slow after OS X has been running for a while

Question: When I reboot my Mac, starting up Node.js apps is nice and fast. Later, after the Mac has been on for a few hours, it gets REALLY slow.
I've used process.hrtime() to time various things, and it seems that it's all the require calls that take time, ie loading dependencies. Once everything is loaded, my apps run reasonably fast.
The difference is extreme: just after I've rebooted, an app may take 300ms to get through the require calls, then it takes something like 30 seconds once it's been on for a few hours.
What could be causing this?
Answer: Since how fast executing require  is perfectly related to a disk loading performance.
So I suppose It's highly possible that HDD/SSD or whatever your project belongs causing that.
it's working fine right after you rebooted so maybe some background software(such as virus scan or auto downloader) is making IO blocking
You'd better start by checking your CPU/RAM/HDD status while the issue is occurring and see what happens if you move your project into USB flash drive or external HDD


Bell kit (xylophone) out of tune?

Question: My kid just got a new used bell kit (glockenspiel) for school (we were renting hers, but we just decided to buy a second-hand one from a kid who quit). The new bells have a tuning problem- every chromatic bar sounds the same as the note one half-step below. (The C# sounds like C, D# sounds like D, etc.) How can this be?
I know kids can whack these things out of tune, but it's every single chromatic note. Is there some way to adjust the rack or something that will uniformly tune the chromatics back to where they should be? Checking with the old bell kit, the natural notes (not chromatics) seem to be tuned correctly.
I don't even see how this could be possible- my kid explained the problem to me and I thought she was crazy. But there it is...
Comment: Are the sharp keys and their corresponding natural keys exactly the same length?
Comment: The kid who quit needs questioning closely!
Comment: @Tim All bars are labeled with their note names by engraved letters- not painted on, or anything like that. So the bars could not simply have been swapped or misplaced. (not a stupid question!)
Comment: Stupid question - are you certain the # and b actually should be # and b, or could someone have substituted 'white keys' for them?
Comment: Thanks for all the replies- I'm glad I'm not crazy. I returned the kit to the other mom. So I guess I'll never have my answers. For the questions:

Just by looking, the C# seemed to be the same length as the C. But I didn't measure them. It was a glockenspiel (metal). All keys had their alleged letters engraved on them. All are removable, but they were not in the wrong order.
Answer: I also don't see how this is possible, without some manufacturing mistake. Glockenspiel bars are very robust and no amount of kids banging on them could make them a half step lower, unless they used rocks or hammers.
That said, I'm afraid there's no easy solution.  Adjusting the rack makes no difference to the pitch.  The only way to fix it would be to shorten the chromatic bars on both ends, or making the ends thinner (by filing their undersides).  Unless you're equipped to do this, you're probably better off getting another glockenspiel.
Comment: Thanks! I returned it. So it's academic at this point, but I'm still puzzled. I'm glad I'm not the only one.
Comment: Who knows?  I guess anything is possible.  I've never seen a commercial metalophone with tuning marks, the bars normally have standardized lengths and are not tuned individually.  Yes, perhaps someone retuned it by hand for whatever reason.
Comment: The bars' pitch should be lowered "by making their ends thicker" or "by making their midpoints thinner", not "by making the ends thinner" - I think you just mistyped this.
Comment: I would love to see your glockenspiel, because I'm still puzzled how this could happen.
Comment: Sorry I didn't take any pictures- all of the keys had several indentures drilled into them on their bottom sides. Maybe some overzealous tuning gone awry?
Answer: It is a manufacturing defect. I also have one with every bar a half step off. To play in G, I have to play in G#. Weird but true. The bars on mine are all mismarked by 1/2 step.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://music.stackexchange.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://music.stackexchange.com/help/whats-reputation), you can also [add a bounty](https://music.stackexchange.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/75831)

Bell kit (xylophone) out of tune?


System.Data.SQlite for Visual Studio 2013

Question: The current distribution for System.Data.SQLite does not work with Visual Studio 2013 unless you deploy the VS2012 Update3 release pack (presumably) or just install (on a test machine like I did) the full version.
Does anyone know when the System.Data.SQLite team will release builds for Visual Studio 2013, both the precompiled static libraries that I would distribute to a customer and the full designer version that I would use?
The current release as of this post is 184.108.40.206, which does not include options for VS2013.
Answer: There is now a build that natively supports VS2013.  Go to http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and search for "Visual Studio 2013". As of today the install is called sqlite-netFx451-setup-bundle-x86-2013-22.214.171.124.exe.
Answer: It's currently not supported on VS 2013, but soon will be(Like most other libraries)
I believe they build every 2 weeks of the core project.
http://system.data.sqlite.org/index.html/doc/trunk/www/faq.wiki#q1
Comment: Thanks. Upon reading, I see: "22.214.171.124 - October 28, 2013." Visual Studio 2013 was out for a relatively a while by this date and no 2013 support. The pending change logs do not mention 2013, so it is not sure that the January 2014 build will include VS2013.
Comment: hmm ... only sqlite seems to build every month or so :)
Comment: It says it supports VS 2013 here http://system.data.sqlite.org/index.html/doc/trunk/www/faq.wiki#q4
Comment: mmmm not sure. I juste tried 3hours googling, installing, uninstalling, rebooting...no way to create any single data connections. SQLite driver in do not appear in my list of available drivers
Comment: It doesn't show up as a driver. Also, as of writing this, the source from the above site downloads, but won't compile on VS 2013 ultimate. It appears he/they use a generator to export the solution files/etc and is a right messy hole for code. Upon opening the project, 90% of the files are not "included" but if you include, you get duplicate errors, plus "mscorelib" shows as a bad ref prob.   v184.108.40.206


Rally Lookback API: SSO Authentication Errors

Question: Our organization uses single sign-on functionality to log into Rally automatically for each user. Wit custom apps I have created in the past which use the Web Services API, this doesn't appear to cause any troubles, however, when a user who has SSO enabled tries to run an app which uses the Lookback API, a login box appears (shown below). Neither the user's SSO credentials or their previous Rally login credentials seem to work in gaining them access to the API.

My assumption that it is SSO causing this problem is strictly based on the fact that the few of us with it disabled do not run into these problems, however those using SSO encounter it every time.
Has anyone experienced this issue before?
Comment: Hi, I'm a developer at Rally.  Yesterday, we deployed a version that should solve the problem.  We are currently testing the fix, and will give you another update later this morning.  If you like, you can also try to log in with SSO and see if the problem went away.  Sorry for the inconvience, Jake
Answer: Jake's team at Rally deployed an update that should have resolved this issue. Don't hesitate to post back if it's still occurring or if there's other concerns.
Comment: As of today, 3/27/2013, we are still experiencing this issue. It seemed to be fixed for a couple of weeks, but now we're hearing from many people that the issue is back again. Did something change?
Comment: Thanks for letting us know Conner, I'm checking in with Jake's team to investigate the issue.
Comment: Looks like the Rally authentication team has fixed the issue. Let us know if you still see any issues.


Prove by Simple Induction that $12^n − 1$ is divisible by $11$ for each $n \in \mathbb N.$

Question: Since $12^n-1$ is divisible by $11$ for small $n$ cases i.e. $(1,2,3,\ldots$, etc), I want to prove that $12^{n+1} -1$ is also divisible by $11$.
what I wrote down:
<code>assume 12^n - 1 % 11 = 0
then 12^(n+1) - 1 = [(12)(12^n)] - 1
  then [(12)(12^n)] - 1 = (12)(12^n) - (12/12)
    then (12)(12^n) - (12/12) =  [(12)(12)(12^n)/12]/12 - 12/12
     then = (12)(12^n) - 12
       then = 12(12^n - 1)
    since we assume that 12^n - 1 is divisible by 11, then 12(12^n-1) is divisible by 11.
</code>
is there any mistakes in what i did?
Comment: Yes. How did you get to $ (12)(12^n) - 12 $ ?
Comment: Hint: $12^{n+1}-1 = 12\times 12^n-1 = (11+1)\times 12^n - 1 = (12^n - 1) + 11\times 12^n$.
Comment: Make sure you include your base case, then properly explain how you are using induction. It also is not a very good idea to use 'then' repeatedly like that.
Comment: @ChantryCargill ahh crap. I just caught that...my mistake..gonna have to fix that
Answer: Here is the inductive step:
$$12^{n+1}-1=\overbrace{12\cdot12^n}^{=12\;times\;12^n}-1=(12^n-1)+11\cdot12^n$$
and both the parentheses (by the ind. hyp.) and the other term are divisible by eleven so we're done
Answer: Modulo $11$, $12^n-1=1^n-1=1-1=0$.
Comment: Since we're on the topic of alternative proofs, one can first prove via induction that $a^n-1 = (a-1)\left(\sum_{k=0}^{n-1}a^k\right)$ for all $n \in \mathbb{N}$, and then mention that $12-1$ is a divisor of $12^n-1$.
Comment: thanks for a simpler way of doing it, but my course is basically an intro to proof writing and i guess they want me to do it a different way :p.


How to choose the frequency value without knowing the seasonality of the data in R ts() package

Question: I am trying to analyze the S$P 500 data on Kaggle.
I have a daily values of the opening stock prices.
As frequency is the number of observations taken in a cycle, I am guessing I need to know the seasonality of the data before deciding upon the frequency value.
I have read that I can use msts and give multiple frequencies as inputs. Will R check which among the multiple frequencies is the best and then estimate the seasonality and trend?
And also can someone tell me what happens when I set frequency='periodic' in ts() function?
Comment: What seasonal cycles do you expect to see in the US stock market?  (If you haven't any idea, then consider analyzing some other kind of data instead.)
Comment: How do tell whether there is seasonality in the data.What should I look at to confirm the absence of seasonality or trend?
Comment: For one approach, search our site for [SARIMA](https://stats.stackexchange.com/search?q=sarima).  You can also search generally for [seasonal decomposition](https://stats.stackexchange.com/search?q=season*+decomp*).
Answer: If you are examining data that you believe contains one or more periodic signals, with unknown frequency, a natural thing to do is to plot the intensity of the data in the frequency domain (via a Fourier transform).  This can be implemented in R using the intensity function in the ts.extend package (see also this paper explaining the package).  When you plot the intensity of the signal in the frequency domain you will see "spikes" at the frequencies where there are periodic signals.  You can also test whether these spikes are sufficiently large to distinguish from noise using the spectrum.test function.
Answer: You can safely assume 5 to begin with ( make sure you have NO MISSING DAYS i.e. fill in a local average for any day that there are no observed values. Good software can detect other cycles if they are present for example a monday effect or the first week-of-the-month effect et al .
Make sure you detect anomalies and suitably adjust the data for their effect otherwise memory effects will/can be occluded.
In response to your question .. 1) adjust for anomalies  ... 2 ) use 4 daily dummy indicators ....3) examine the residuals for persistent effects suggesting a cycle greater than 5 via the acf and/or intervention detection schemes in a trial and error manner.
Comment: Hi.Can you tell me how to generally select the value for frequency.What should I be looking at?
Comment: And also can you tell me what happens when I set frequency='periodic' in ts() function.Thanks!
Comment: I have no idea as to what happens as I have no familiarity with anything that would use  a periodicity of 365.25 as we generally do not do on day x of the year what we did last year on day x EXCEPT for major holidays.


Tag synonym "301-redirect" -> "redirect"

Question: I was just going through the various "rewrite" and "redirect" tag variations to get them in order and found that it is not possible to suggest a tag synonym for 301-redirect to redirect.
StackExchange falsely recognizes "301-redirect" as version specific synonym:

Could a moderator take care of that? I hope you agree that there's no value in specific "301" or "302" redirect tags.
Answer: I got your back:
https://magento.stackexchange.com/tags/redirect/synonyms


Find the probability that a random variable is "good" and find the expected value of the number of "good" random variables.

Question: Suppose that $X_1,\cdots,X_n$ are i.i.d. continuous random variables. $X_k$ is called good if we have $X_i < X_k$ for all $i<k$.
1) Find the probability that $X_k$ is good.
2) Find the expected value of the number of good random variables. Show that this value approaches infinity when $n \to \infty$.
Please do not give me a full solution first. Just hints. My major issue with this problem is that I do not understand what the question is asking mathematically. So, a random variable is just a function from some probability space to real numbers. What kind of probability density are we assuming on the space of random variables? What is our probability space here?
Comment: What is the probability that $X_2$ is good?  This is just $P(X_1<X_2)$  Can you write the event that $X_3$ is good in a similar fashion?
Comment: @saulspatz: Well, it's going to be $P(X_1<X_3, X_2< X_3)$. Right?
Comment: Yes that's true, but I was thinking along the lines that it's $P(X_1\leq X_2<X_3\vee X_2\leq X_1<X_3)$  In this form, it's easier to see what the value is.
Comment: @saulspatz  Thanks for your help. Why do you want to write it like that? Could you please be more specific?
Comment: Because then we see that by symmetry, the probability that $X_n$ is good is $1/n$.  Or for another way of looking at it, what is the probability that $X_n$ is the largest of $n$ i.i.d r.v.'s?  (Note that, since the r.v.'s are continuous, the probability that any two of them are equal is $0$ so we can ignore this possibility.)
Comment: @saulspatz  I don't see the symmetry clearly. :( I mean, For example for $X_k$, we should consider all permutations of $X_1, \cdots, X_{k-1}$. Shouldn't we? Why is it $\frac{1}{k}$ then? And not $\frac{1}{(k-1)!}$?
Comment: No, it's all permutations of $X_1\dots X_k$ and only the ones with $X_k$ last are acceptable.
Comment: @saulspatz: Exactly. So, the $k$-th element in the permutation is fixed. We still need to permute $k-1$ of them. Right? That gives that the probability of $X_k$ being good to be $\frac{1}{(k-1)!}$ according to your analysis if I understood it correctly. Why $1/k$ then? Could you expand your comment please?
Comment: I think I'll write an answer.  Give me a few moments
Comment: @saulspatz Thank you.
Answer: If we sort the variables $X_1\dots X_k$ in increasing order, there are $k!$ possible orders.  Only the ones where $X_k$ comes last make $X_k$ good.  There are $(k-1)!$ such arrangements.  Since, by symmetry, all orders are equally likely, the probability that $X_k$ is good is $${(k-1)!\over k!}={1\over k}$$
We ignore the possibility that two of the variables have the same value.  Since the X_i are continuous r.v.'s, the probability that two of them are equal is $0.$
The expected number of good $X_k$ is just $$\sum_{k=1}^\infty P(X_k\text{ is good})=\sum_{k=1}^\infty{1\over k} = \infty$$
Comment: Thanks. Sorry for being so confused at first. Now I understand what you meant by symmetry.
Comment: No need to apologize.  I was glad to help.


Umpire induces appeal play?

Question: What do the umpires do when a game ends on a scoring play, when an appeal (not video review) by the defense would succeed?
For example:  bottom of the ninth, tie score, one out, runner on third.  The batter hits a deep fly ball, caught by the right fielder.  Runner on third tags up and scores the winning run.  Game over. Everyone leaves the field.
But you're the third base umpire, and you know, without any doubt, that the runner on third left early, and, if the defensive team appeals, you need to be there to call the runner on third out with no run scored and the inning over.
On the other hand, to avoid giving hints to the defensive team, wouldn't you need to do the same thing (hang around third) if the runner had tagged up correctly?  To avoid warning the defense in those cases where there is a successful appeal available?
Answer: The umpires don't just go take a nap after the game - there's plenty of time between the run actually scoring and them leaving for the opposing manager to let them know they'd like to appeal the play.
The only restriction is that the defensive team must make the appeal before leaving the field (rule 5.09(c)):

Any appeal under this rule must be made before the next pitch, or
  any play or attempted play. If the violation occurs during a play
  which ends a half-inning, the appeal must be made before the
  defensive team leaves the field.

If the defensive team's manager plans to appeal the play, he/she should let an umpire know in a timely manner.

Umpire induces appeal play?


My Neural Net can overfit but not generalize

Question: I have created a Neural network that gets its training data from a complicated physics simulation. I run the simulation by randomizing 7 different inputs. Each input can be 1 of 4 discrete values. I have decided to use an input vector with 28 binary nodes (7 inputs * 4 possibilities per input). The output layer is just 1 node, a continuous number. This is a controlled simulation so there must exist a true relationship between these inputs and my output, right?
No matter what architecture or method I use, the accuracy seems to hit a wall at 20%. Without going into the specifics of my cost/accuracy function, that is about the number I expect if the neural net just outputs a random number in the range of all my target data (not good). Now the neural net can perfectly fit the training data if I make it very deep. But bad results notwithstanding, I get the lowest TEST score reliably by making the network as shallow as possible, i.e. a single hidden layer with 1 or 2 nodes. Clearly things are amiss.

If I give the hidden layer ~20 nodes the test score starts moderately low (accuracy ~20%) and rises as overtraining kicks in. The output looks something like this. No matter what this network accuracy hits a wall around that 20% area.

And 2 nodes for reference

Increasing the training set seems to have diminishing returns

Please help, I am eager to see if anyone else has had behavior like this. I will readily provide any other information you need to better understand the problem.
Many thanks in advance.
-Joel
Addendum:
If I change the inputs to 7 (different) continuous variables then the relationship can be captured reasonably well with many hidden nodes. If I mix in the discrete variables with those continuous variables then the generalization falls apart again. This is an elusive problem, but if I had to guess it seems that the big issue is using these discrete variables, represented a stacked one-hot vectors. It would be really nice to find their relationship to the output because they are important inputs to the simulation. Perhaps it would help to see examples of Neural Networks that have worked using similar, discrete inputs represented as one-hot vectors or otherwise.
Comment: General rule: total number of free parameters in your model should be less than 10% of the number of training points. Hopefully a lot less, like 1% or 0.1%. To do this, make the model shallower and/or narrower until your training error is about equal to your test error. Then try to look deeper into the problem and develop a model with the fewest number of free parameters. It is likely that your best model won't involve neural networks at all, but physical principles instead! Hurray!
Comment: You can overtrain any learning model to memorize the training set, but memorization is the opposite of learning. You can memorize uncorrelated Gaussian noise, for instance, but if you try to learn it, a successful model should give the only mean and have a steady L2 loss equal to the variance. The fundamental goal of learning is for loss-in-training to be approx equal to loss-in-testing. Yes, a well designed NN should achieve that goal, even and especially if your data is pure noise. Try developing a model from trivially simple up. E(train) ~< E(test) at the start. Try to keep it that way.
Comment: Hey Peter: Even if the relationship can be boiled down to phsyical principles right now I am trying to do a proof of concept. The Neural Network is clearly not capturing the relationship at the moment. Even if a Neural network is overkill, it still SHOULD be able to model the behavior of the relationship, right?
Comment: That gets to the heart of my problem. With the shallowest network possible (1-2 hidden nodes) I can get my training and test costs to flatten out at around 10 epochs, whereas with the deeper network the training cost continued to drop while the test cost rose. But my accuracy keeps hitting the 20% ceiling, which as I said is probably not much higher success than guessing the output at random. Have you ever seen such behavior, i.e. a floor/ceiling for the test cost/accuracy, largely irrespective of choice for the hyperparameters? I just added another picture for 2 hidden nodes.
Comment: Hello, can you please describe what your output is? is it a classification problem? From what you described, it seems one of the 2 following things is happening: your simulation is wrong and the input does not carry any information about the output. Or it does but you are overfitting right away. I would first test if it is indeed number 1 by trying an algorithm with less complexity such a linear/logistic regression or trees/svm for instance. If you get better results, then you may want to look again at your NN.
Comment: I agree with Peter that you can improve your efficiency by representing domain knowledge using parametric structure.  By all means, do that.  But you can also fit a neural net with way more parameters than data.  Just use an early stopping callback, and update your hyperparameters after each run.
Comment: Hey Tom: The output is a continuous value, ranging from 0-1 after normalization (I divide by the maximum value. The original simulation, from which this output is extracted, simulates an NMR spectrum given a set of coordinates for atoms. The output is specifically the maximum height/intensity in the spectrum. Those 7 inputs that I mentioned are the phase of an rf-pulse in the NMR experiment; there are only 4 types because the phase can only be x, -x, y, or -y. In the actual simulation this will be elicited as a unique matrix multiplied as the calculation is being made.
Comment: generic_user: If I make the hidden layer 1 node, then technically I have made a parametric, linear equation with 7 parameters to be fit. Still when I do that I hit the ceiling of 20% accuracy.
Comment: Try a random training set and an equally random test set. Is the performance the same? If so, then perhaps your training set has no actual information in it. Hmmm.
Comment: Peter: I think that's what I do everytime. I read in a data matrix of training samples, permute them and then split into 2 sets. You might be right, but its hard to believe they contain no information since changing them while keeping everything else the same alters the final answer. I feel like it is a shortcoming of representing discrete variables (check out the postscript I just added to main message), but I'm just grasping at straws at this point. Thanks for the pointers.
Answer: It might be that the problem is so hard that the training points you have are not enough to estimate the underlying decision function(e.g. in a checker-board pattern, you would only expect to obtain a decent estimate once you are covering a big part of the squares). Have you played around with the number of training points? How many points do you have available?
have you tried other approaches? Neural networks are probably the most fickle model to throw on an arbitrary problem. What does logistic regression say? How about a random forest? Both algorithms have some basic ways to analyze their decision function and measure how important certain variables are to the decision boundary.
Comment: Hey Ulfgard: I just tried running it many times by dividing my 1000 samples into smaller and smaller sets, and unfortunately the relationship with test cost looked pretty flat. You might be right that the problem is too hard/relationship too weak. Like I said earlier, changing the discrete value refers to change of pulse phase in the simulation, which means an entirely different matrix is being applied in the calculation. But I worry this is a larger problem with representation of discrete inputs, and can think of one other example of a NN failing in the same way, possibly for the same reason.
Comment: discrete inputs are always challenging. any chance providing the network with the original, non-discretized values?
Comment: When you say "original, non-discretized values?", what are you referring to? Unfortunately I don't think there is any way of representing these attributes of the simulation as continuous values.


Python aiohttp pars

Question: I want to parse a lot of links using iohttp, but it doesn't work in real time, parse each one in turn. How do I make it so that I parse each one continuously?
import aiohttp
import asyncio

list = ['value1', 'value2', 'value3', ..... 'value6000']

async def main():
    async with aiohttp.ClientSession() as session:
        while True:
            for i in list:
                async with session.get(f"https://example.com/{i}") as response:
                    print(response.json())

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Comment: It's not what your issue is, but don't overwrite builtins such as `list` unless you know what your doing. It will cause issues down the road.
Answer: If you are looking for processing a list, you should check asyncio.gather().
Example of usage:
import asyncio
import os

from aiohttp import ClientSession, ClientError, TCPConnector
from asyncio import TimeoutError, gather

async def asyncmain(your_list):

    async with ClientSession(
        connector=TCPConnector(limit_per_host=SESSION_LIMIT_PER_HOST)
    ) as session:
        tasks = (your_async_call(session, title) for title in your_list)

        return await gather(*tasks)

Python aiohttp pars


A question about survey sample size

Question: I am looking at the formula on this page, it says the formula for estimating the sample size of a survey is:
$$Sample\;size = \frac{\frac{z^2 \;\times \;p(1-p)}{e^2}}{1 + (\frac{z^2 \; \times \; p(1-p)}{e^2N})}$$
where
- $e$ is the margin of error
- $N$ is the population size.
I have the following questions:

What does $p$ represents?
Why is the variance of a Bernoulli distribution (i.e. $p(1-p)$) used here?
Let's say

N= 10,000
e=3%
confidence interval = 95%
based on the numbers above, the sample size is 965

How would you interpret the result? I am 95% confident that by surveying 965 people, it will be enough to present the entire population? (what about the margin of error?)
Answer: This sample size calculator seems to assume you're trying to determine the proportion of units in your population has a particular characteristic.

$p$ represents the proportion in the population that has the characteristic you're studying. The calculator probably assumes $p=0.5$ since this gives the most conservative (largest) sample size.
The variance of a Bernoulli random variable is used because each unit in the population is either has the characteristic you're studying or doesn't. If you're not just calculating proportions - for example if you're trying to estimate average height, then you replace the $p(1-p)$ with an estimate of the variance of the characteristic you're collecting (e.g. do some initial research to estimate the variance of heights in your population).
That result is saying that if you repeated the survey many times, then 95% of the time, the proportion of units in your survey that have that particular characteristic will be within about 3% of the true proportion in the population.
Comment: Yes, you can say that the sample mean is pretty close to the population mean. How you say that is quite precise though, which is why I put it in that strange way in point 3.
Comment: Hi @RoryT, thanks a lot for the answer! In a survey, a list of questions are usually asked. How should I interpret the result if I want to explain an individual survey question? For example, "What's your favourite color?", "red, yellow, blue or green". Let's say 60% people answered "yellow". If I survey enough people according to the calculator, I can say about 60% of the population I am interested in like "yellow"?

A question about survey sample size


Samba not running as AD DC

Question: I am trying to set up my Debian box as an active directory domain controller using Samba 4.5. After going through samba-tool domain provision --use-rfc2307 --interactive the Samba service does not start and issuing systemctl start samba says that samba service is masked and systemctl unmask samba does nothing, the service is still masked afterwards.
According to https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=837679 then the masking of the Samba service is by design but as I understand it then after provisioning the server as AD DC then that service should be unmasked but it does not happen for me and I am wondering why? And as I understand it then that service needs to be running to run all the other services that are needed so my clients can find the server as a DC and hook up to the domain which they are not doing now.
Here is my smb.conf if that helps
# Global parameters
[global]
        netbios name = SERVER
        realm = SERVER.DOMAIN.LAN
        workgroup = DOMAIN
        dns forwarder = 192.168.168.1
        server role = active directory domain controller
        idmap_ldb:use rfc2307 = yes

[netlogon]
        path = /var/lib/samba/sysvol/server.domain.lan/scripts
        read only = No

[sysvol]
        path = /var/lib/samba/sysvol
        read only = No

My final aim is to use this server as AD DC, file server and email server but will settle for AD DC to begin with as a starting point :-)
Answer: The name of the service in Samba 4 after provisionning is "samba-ad-dc"
You can try to mask first the old services and start the new one:
#systemctl stop smbd nmbd winbind
#systemctl disable smbd nmbd winbind
#systemctl unmask samba-ad-dc
Removed /etc/systemd/system/samba-ad-dc.service
#systemctl start samba-ad-dc
#systemctl status samba-ad-dc

Comment: Thanks for that, this got Samba service up and running, still have problems and will make new questions out of those.

Samba not running as AD DC


Combining Error Terms into a General Error Term

Question: Lets say I have 4 error terms:
$$e_1,e_2,e_3,e_4$$
Each of these error terms come from different simulations of data using different classification methods.
Let $\gamma$ be the number of empirical data and $\delta$ be the number of simulated data and $d$ is the difference of the two. The error terms are $\frac{d}{\gamma}$. An example is as follows (in this case the difference $d$ is always 5):
$$\gamma = 500, \delta = 505 \implies e_1 = \frac{5}{500} =1\% $$
$$\gamma = 50, \delta = 45 \implies e_2 = \frac{5}{50} = 10\% $$
$$\gamma = 30, \delta = 35 \implies e_3 = \frac{5}{30} =16\% $$
$$\gamma = 1, \delta = 6 \implies e_4 = \frac{5}{1} = 500\% $$
I want to combine these error terms into one general error term, however I want to make an emphasis on certain error terms. Because, using the average of these terms would make an error result that is too susceptible to outliers. $e_3$ is the most accurate in my opinion. Is it suitable to create a linear combination of these error terms to define a general error term?
If so, it would look like this:
$$ E = \alpha_1 e_1 + \alpha_2 e_2 + \alpha_3 e_3 + \alpha_4 e_4 , \forall \alpha_i\in\mathbb{R}$$
If this is allowable, what would be the best way to define alpha values s.t. $0<=E<=1$ OR $0\%<=E<=100\%$ ?
(Note: This is not the same as using a regression model).
Answer: A common error calculation is MAPE (Mean Absolute Percent Error) which is often used in demand forecasting.
$$\rm \frac{\sum|(actuals-forecasts)|}{\sum(actuals)}$$
In your case it seems that the simulations are the forecasts and the empirical data are the actuals.
It is similar to what you are doing except all the numerators are summed up and all the denominators are summed up before dividing so that your last error term won't have such a dramatic effect. There are also several variations of MAPE such as weighted MAPE which you may find helpful if you have another variable such as sales that you want to weight your error terms with.
Comment: I don't think we can do it this way because each error term is from different methods
Comment: Also, that would be the same thing as taking the average, which i mentioned wouldn't really help in terms of the sensitivity to outliers


Correlation and independence of two random variables

Question: Let $X\sim N(0,1)$ and $Y=(-1)^J \cdot X$, where $P(J=1)=\frac{1}{2}=P(J=0)$. Furthermore X and J are independent.
I already showed that $Y\sim N(0,1)$ by calculating the cdf of Y. Now I want to show that X,Y are dependent and uncorrelated.
I tried showing the dependence by giving a counterexample for independence, but I'm not sure about it:
$P(X\le-1,Y\le-1)=P(X\le-1,J=0)=P(X\le-1)P(J=0)=\frac{1}{2}P(X\le-1)$
$$P(X\le-1)P(Y\le-1)=(P(X\le-1))^2$$.
We see they're obviously not the same, so not independent.
For the Correlation, I first wanted to calculate the covariance:
$$\mathrm{Cov}(X,Y)=E(XY)-E(X)E(Y)=E(XY)$$ but at this point I'm stuck because I don't know how to compute E(XY), we haven't proven Total law of expectation yet, so I'm not allowed to use it here and we also haven't spoken about Chi^2-distribution.
So to sum up I have two questions:
1.) Is my approach for the independence of X,Y correct?
2.) How can I calculate E(XY)?
Thanks in advance!
Answer: Yes! Your proof of dependence is correct.
To compute the covariance, you could try the following:
$$\mathbb{E}[XY] = \mathbb{E}[(-1)^{J}X^2] = \mathbb{E}[(-1)^{J}]\mathbb{E}[X^2],$$
where the last equalty follows by independence.
Note that to compute each expectation you may use the fact that for any random variable $X$ and nice enough function $g$:
$$\mathbb{E}[g(X)] = \begin{cases}
\sum_{x\in \operatorname{Rg}(X)} g(x) p_X(x) &\text{ if }X\text{ is discrete, and}\\
\int_{\mathbb{R}} g(x) f_X(x) dx &\text{ if }X\text{ is (absolutely) contninuous}\\
\end{cases}$$
to finish the proof. Both $x\mapsto x^2$ (because it is Borel-measurable) and $a\mapsto (-1)^{a}$ can be used with this result.
Comment: Thank you very much! Now it is clear to me! :)


Why I can't invoke lambda in the Jetpack Compose

Question: I want to invoke a Int value when I click on the each tab but I have an error. I used  LaunchEffect() and Coroutine scope but it's not solved. how can I fix it?
Screen code:
@ExperimentalPagerApi
@Composable
fun Tabs(
    pagerState: PagerState,
    modifier: Modifier,
    state: MyJobsState,
    onTabSelected: @Composable (tabPage: Int) -> Unit
) {
    val scope = rememberCoroutineScope()
    ScrollableTabRow(
        selectedTabIndex = pagerState.currentPage,
        indicator = { tabPositions ->
            TabRowDefaults.Indicator(
                modifier.pagerTabIndicatorOffset(pagerState, tabPositions),
                height = 0.dp,
            )
        },
        edgePadding = 0.dp,
        divider = {}
    ) {
        state.items?.forEachIndexed { index, _ ->
            Tab(
                text = {
                    Text(
                        text = state.items[index].title ?: "")
                },
                selected = pagerState.currentPage == index,
                onClick = {
                    scope.launch {
                        pagerState.animateScrollToPage(index)
                    }
                    onTabSelected.invoke(index)
                }
            )
        }
    }
}

I get this error:
Answer: onTabSelected is marked as @Composable, that's why you can't invoke it inside onClick.
You can only invoke @Composable inside an other @Composable, not in side effects. Remove this annotation, and you probably need to redesign the view which is using Tabs.
You're doing the same mistake again: onTabSelected is a side effect. You can't add composable views to the view hierarchy inside side effects.
Instead, you should use a state variable, and change the view depending on this state, e.g.:
var selectedTab by remember { mutableStateOf(0) }

ScrollableTabRow(
    selectedTabIndex = pagerState.currentPage,
    indicator = { tabPositions ->
        TabRowDefaults.Indicator(
            modifier.pagerTabIndicatorOffset(pagerState, tabPositions),
            height = 0.dp,
        )
    },
    edgePadding = 0.dp,
    divider = {}
) {
    state.items?.forEachIndexed { index, _ ->
        Tab(
            text = {
                Text(
                    text = state.items[index].title ?: "")
            },
            selected = pagerState.currentPage == index,
            onClick = {
                selectedTab = index
            }
        )
    }
}

when (selectedTab) {
    0 -> {
        FirstView()
    }
    1 -> {
        SecondView()
    }
}

You can find more info about state in Compose in documentation, including this youtube video which explains the basic principles.
Comment: If I remove the @Composable I can't use the callback value: https://ufile.io/20ellc7p
Comment: @saeednoshadi see updated answer
Answer: Remove the @Composable from your onTabSelected parameter. You can't call composables directly from a click event or any other non-composable function.


Prove that the map $f:\mathbb{R}\to \mathbb{R}^2$ given $f(t)=1/2(e^t+e^{-t},e^t-e^{-t})$ is an embedding

Question: I'm not able to prove that the below map is embedding.
Prove that the map $f:\mathbb{R} \to \mathbb{R}^2$ given $f(t)=1/2(e^t+e^{-t},e^t-e^{-t})$ is an embedding and $M=f(R)$ is a $1$-manifold and graph it.
Answer: Hint:
You have( see hyperbolic functions)
$$
f(t)=\left(\frac{e^t+e^{-t}}{2},\frac{e^t-e^{-t}}{2} \right)= (\cosh t,\sinh t)
$$
and, since $\cosh^2 t-\sinh^2 t=1$ this is  the parametric equation of an hyperbola.


Leatherman tool for administrators?

Question: I have only been able to find threads about software tools on this subject.
Is there any multi-purpose tool out there for it-administrators? I am thinking of something like a leatherman tool - perhaps with screwdriver, ethernet-checker, usb checker and similar.
I am tired of finding and opening different toolboxes to find the equipment I need.
Has anyone heard or seen anything like it?
Comment: This should probably be a wiki article and carry the subjective tag.
Answer: i use a leatherman wave and it does what i need.  i think you are looking for something that would not be pocketsized.
Comment: @caspert: it's not the features.  It's the quality.  You can get a generic tool with all the same features for only $20, but it won't be built near as well.
Comment: +1, the wave is good, i use it all the time
Comment: Love the wav ... and so do the TSA agents that check my bags when i fly ... grrr on number 4 at this point.
Comment: Love my wave :)
Comment: I've always liked the Wave. I'm carrying the Skeletool now because I work from home (and use it less). It's much lighter, but less useful.
Comment: I see a lot of people recommend it - that is very good.
The price seems quite big though - are the cheaper models too cheap on features to be considered instead?
Comment: Love my Skeletool - it's light enough to carry around in my handbag all the time (the Wave isn't). The best multitool is useless if you don't have it with you when you need it.
Answer: may i suggest the cybertool from Swiss army?
http://www.thinkgeek.com/gadgets/tools/3653/
My co-worker just got one and I am a little jealous. May not be what you are looking for though.
Comment: Victorinox is in Switzerland. Here is a link to their whole line of the CyberTool series: http://victorinox.ch/index.cfm?site=victorinox.ch&page=13⟨=E
Comment: I'd be more concerned about the quality of the Leatherman than of Victorinox
Comment: I own that. It's nice. But it doesn't have an ethernet- or usb-checker.
Comment: I like that one. I was concerned that it was of cheap quality, but since some one recommends it... :)
Do you know if you can buy it elsewhere? They do not ship to Europe :(
(I live in Denmark)
Comment: @caspert: Here you can find out where to get it: http://www.victorinox.dk/
Answer: I'd have to say that it depends on the type of racks that you're dealing with, and the servers.  I actually carry a few tools (SOG Power Pliers, Gerber MultiPliers and a Latshaw Pocketwrench II).  In my computer bag, I also keep for laptops and internal parts, a Husky HD-74501 W and an HD-74502 W.  (small screwdriver and torx set, single handle with a total of 8 tips each, but very small; the torx goes down to T4, and they fit into spaces a 1/4" drive screwdriver won't).  At my desk, I keep a monkey wrench, a socket set, a Stanley Wonder Bar II, and a screwdriver/nutdriver set.
The Pocketwrench is great for just holdings nuts while you tighten from the other side (and tightening rails from Sun where you have no clearance to get a wrench in there).  The reason for the SOG and the Gerber is that they have different size philips bits -- the Gerber I use for rack screws, the SOG for removing cards and such.  I also find that two plier-like devices also comes in handy when dealing with bolts, as the pocketwrench doesn't always give me the leverage I need for breaking nuts free.  The Wonder Bar is the only thing people look at me funny for -- but it's a god send when you have to shift a server up slightly, so you can fit in something below it.  (the pocket wrench works okay, but the Wonder Bar has much better leverage).
Oh -- and I've accidentally flown with the pocket wrench, and security turned my bag inside out looking to figure out what it was.  As there weren't any sharp edges on it, they let me get on the plane with it.
Comment: Hehe reading your post I was about to say what in the world do you need a Wonderbar for but that makes sense.  I have a phone hammer on my desk....it doesn't fix things but it does make you feel better.
Comment: er that should have read foam hammer :)
Comment: I **love** my Pocketwrench II. BTW, I don't think it goes by the name "Latshaw" any more. @3dinfluence: A "phone" hammer would definitely make me feel better some days.
Comment: @3dinfluence: I've also used the wonderbar when I had to change out the batteries in a UPS, but they had swelled, and I had to take the top off of the case, and pry them out one by one.  (two times so far, same brand).  It's also something that you can use to put under a heavy UPS / server / whatever that you're unracking and need to set it down -- you then step on it to lift it up a quarter inch so you can get a grip on it.  I highly recommend it in your toolkit, even if it isn't something to carry with you.
Answer: You aren't going to find one tool that does everything on your list. And if you did, you'd probably regret it. Ethernet and USB cable testers should definitely be separate from your pliers, for instance.
If I was going to admin stuff today, I'd grab my Leatherman Wave and a combo cable tester (something like this).
Answer: I own both a leatherman Charge TTi and a Paladin PowerPlay PT-540.
The leatherman is great for general utility, and I love the s30v blade - it's the first multi-tool I've owned that holds a decent edge, and the pliers are usable. More info here -
I got the Paladin tool to keep in my laptop bag for the occasional wiring work so I wouldn't have to lug around a separate set of tools. It's made by SOG, and I was amazed at how solid it is (I've generally been disappointed with Paladin tools), and the compound-leverage sprocket mechanism is smooth as butter. I wish they had figured out how to put in an RJ-11/45 crimper, instead of the electrical lug crimper, though. I've had it for about 8 months and just haven't needed it much, so far. More info here -
http://www.paladin-tools.com/view_tool.php?id=490&parent_id=362
I'm not familiar with any integrated USB/cat5 cable testers; sorry.
ch
Comment: Ditto on the TTi. Seems to be the best suited to my needs. I'm planning to get a Leatherman Crunch as well.
Answer: I gave up on finding "1 tool" but if I had to choose, I'd stick with the Leatherman Wave that's already been mentioned.
I currently use a small tool roll like this:
http://www.duluthtrading.com/store/departments/tools-shop/tool-bags-tool-belts/tool-bags/92099.aspx?feature=product_15
(I think mine is smaller)
It fits in my knapsack and keeps the things I need in it.  The main stuff I make sure I have:

rack tool for popping nuts in and out
leatherman
assorted bits
a couple small vice grips (as good as an extra
set of hands in some cases in the
datacenter)
velcro strapping small
LED flashlight

This roll has the benefit of keeping it all together and it's pretty easy to tell at a glance if anything has "walked off" (as opposed to digging through various tool boxes.

Leatherman tool for administrators?


If a website doesn't have an API - what to do?

Question: There is a website called:
Engrade.com.
It's pretty cool, you can monitor what your grades are in your current classes. But I want to make an objective-c app that can log in as me and get my grades. Then probably, it would alert me to any bad grades, etc.
Problem!!! It doesn't have an API, so I'm stuck. Does anyone know how I would do this?
Thanks,
Elijah
Answer: You can always just download the page and parse it yourself - be warned that this approach is fraught with peril.  You can read about web scraping in general on Wikipedia.


Open multiple tabs of gnome-terminal, each trigger command with N seconds delay

Question: I have a simple bash script:
<code>#!/bin/bash
gnome-terminal --working-directory=xxx/yyy/zzz --tab -e "command 1" --tab -e "command 2" --tab -e "command 3" --tab -e "command 4"
</code>
I need each of these tabs to trigger the command with few second delay so I tried this:
<code>#!/bin/bash
gnome-terminal --working-directory=xxx/yyy/zzz --tab -e "command 1" --tab -e "sleep 2" -e "command 2" --tab -e "sleep 4" -e "command 3" --tab -e "sleep 6" -e "command 4"
</code>
To give them 2 seconds difference, but these are still being triggered at the same time, is there any way to do this? Thank you
Answer: Try something like
<code>gnome-terminal --working-directory=xxx/yyy/zzz --tab -e "command 1" --tab -e "sh -c 'sleep 2; command 2'" --tab -e "sh -c 'sleep 4; command 3'" --tab -e "sh -c 'sleep 6; command 4'"
</code>


C lib calling on global variable in another lib

Question: I have two libraries, to simplify:
libA.lib, libB.lib
libA has function:
void read(num,*val){
*val=Globalval[num];
...
}

libB:
void write(num,val){
Globalval[num]=val;
...
}

that is the gist of what I want to achieve. The two libs are included in my main project files and the functions are called individually. So how do I have this work out? If the two libs were of the same lib, a simply global variable would be all I need.
I'm using microsoft visual studios
Comment: What have you tried and what isn't working?  This scenario works - you can declare global variables in a shared header file, define them in one lib, and use them from anything staticly linked in.
Comment: How about the more obvious statement that this is bad library design?
Comment: @asveikau I'm not doing exactly what is stated, just trying to figure out how to call variables from other libs. If the act of doing such is called bad design, then why would such functions be allowed? Please comment if you have more constructive criticisms.
Comment: A language allows you to do all sorts of bad designs.  This should not be taken as an endorsement.  The drawbacks of globals are well documented.
Comment: I'm well aware the inefficiencies of globals, but there are instances where there are no alternatives. Otherwise, why would globals be part of the language?
Answer: In one of the files, probably the write one (libB), put something like this:
int Globalval[SIZE];

In its header file, which should be included by libA, put this:
extern int Globalval[];

If your example really is what you're doing though, keep both functions in the same file, and call them from wherever you need to. In that case, you just put the function prototypes in the header.
Comment: yea i'm not going for exactly read and write, this is simply the easiest way to get my point across.
Answer: You should be able to use EXTERN
in one of your libs header file:
extern int g_myGlobal;

in one of your libs cpp file:
int g_myGlobal;

You would then have to include the header file from one lib in the other (or any other file) that wants to use g_myGlobal
Comment: I've tried this method before however the global value never updated from write to read. I had a common header file with the extern declaration, and in write i set it to 1. However in my read functions, when I call for it, the value I get back is 0, the default
Comment: Perhaps it is a threading / syncronization issue, try prepending the definition with "volatile"
Comment: just to be clear on if I'm setting things up right. I have a global.h file with the extern declaration. This is included in both libs. In libB, the source has the int g_myGlobal definition. In libA I also have to define g_myGlobal as int. LibB's function sets g_myGlobal=1 and libA's function printfs it. From this I get 0 for the global. I'll try volatile though
Comment: no, you do NOT define it in libA, you use the libB's header file (which has the EXTERN) in in your LibA's cpp file.
Comment: @mugetsu: Are you sure you `#include "global.h"` in libA? You shouldn't define `g_myGlobal` as int in it. Perhaps you have a linker problem.
Comment: but i had to that, otherwise I get the undefined symbol error. In libA I have the header file, but thats just a declaration, the file needs a definition as well.
Comment: @nmichaels yep I did do the include, you might be right about the linker issue. How can I further troubleshoot/fix this?
Comment: @mugetsu: You've moved from C to Microsoft's linker. I can't help you there.


leaps: small vs. large (learning counterpoint)

Question: I'm reading Harmony in Context by Roig-Francoli as a first theory text to teach myself composition.  In his Introduction to Species Counterpoint chapter, he mentions that the melody should consist of steps and small leaps, with large leaps rare and with special rules regarding them [large leaps].
My question is what is small and large for a leap?
Comment: I don't think there is embedded Latex on this site, is there?
Comment: As an aside, what am I doing wrong here trying to get the embedded LaTeX to render with: What i makes $\^{n} \rightarrow \^{(n+i)}$
small or large?
Comment: Only some StackExchanges have the embedded LaTeX?
Answer: Typically in counterpoint movement is broken down into three different types including steps, skips, and leaps.
I'm guessing in the case of Harmony in Context a small leap is the same as a skip. The intervals for each of these moments are as follows:

Step: 2nd
Skip: 3rd or 4th
Leap: 5th or greater

Wikipedia has a lot on the rules and process of counterpoint and under first species counterpoint defines a step skip and a leap. Hope this helps.
Comment: Dom, I upvote here but disagree with a portion of your answer. I would say that a leap is a 4th or larger as the interval of a 4th is dissonant in counterpoint and voices must be resolved in the opposite direction.  Therefore 4ths are used less frequently and thus fall into the "rare" category (or at least used with certain rules.)
Comment: @jjmusicnotes I understand that the interval of a 4th is dissonant in counterpoint, but when looking up the definition of skip in counterpoint the definition was : "In the present context, a "step" is a melodic interval of a half or whole step. A "skip" is an interval of a third or fourth. (See Steps and skips.) An interval of a fifth or larger is referred to as a "leap"." The source is the Wikipedia page linked in my answer. I knew the 3rd was a skip and 5th a leap, but wasn't sure about the fourth so I looked it up.
Comment: @Dom, regardless of how a 4th is classified (you'll find different answers depending on where you look), the important thing is to understand how to treat it. My teachers always classified it as a leap because (in addition to the rules I mentioned earlier) it made you think twice about using 4ths (a good habit to get into). Mark, to answer your question directly, a large leap would be anything larger than a P5th.
Comment: I missed that section while reading Wikipedia, thank you for the link.  Pending clarification of fourth intervals, I'll regard them as "rare due to dissonance, unclassified large or small," in my mental notes.
Comment: I'm a noob to counterpoint so I might be wrong about this, but if I'm not I think it's probably important to note that two consecutive 3rds in one direction is considered a leap and needs to be resolved by a step in the opposite direction.


Are "*_squash" (all_squash/no_all_squash, root_squash/no_root_squash, anon_uid/anon_gid) options in NFSv4 still rellevant?

Question: Nowadays NFSv4 uses /etc/idmapd.conf to do the mapping of usernames between server and client machines. So I don't get the point of having these "*_squash" options, which seems very "NFSv3-flavoured" and redundant, if I'm not wrong.
There's any reason for keeping using these options in a NFSv4 shared folder?
Thanks a lot.
Answer: As the end result of mapping through idmapd you get uid/gid(s), this all options are still valid.
Comment: Hello, thanks for answering. But...are you sure of this? I think the mapping is done by the "Nobody-User"/"Nobody-Group" and "Method" lines in idmapd.conf file. If last one has the value "nsswitch" (the default one), I understand the mapping is done via nsswitch.conf file, which normally points to /etc/passwd and /etc/shadow files. So here the UID/GID would be irrellevant. What's the point I'm missing? Thanks!!


User getting duplicate emails from Peoplesoft

Question: One particular user is associated with 2 roles and those 2 roles are there in Workflow email list and so the user gets the same email twice. Is there anyway I could avoid this duplicate emails
Thanks
Gautham
Answer: Only a little late... :/ but saw the question so thought i'd give my 2 cents and hope this helps someone.
One option is to create dynamic 'shell' roles to drive your work flow. This way you can use queries on the roles users have and build your work flow roles separate from security roles.
The first query can look for the multiple roles and others look for singular, excluding the multiple.


How does a Voice Box guitar effect work?

Question: I heard an old Barnstorm album where Joe Walsh made his guitar talk. How did he do that?
Comment: You might also check out what is probably the most famous example: https://youtu.be/V9Yq5m9eLIQ
Comment: Just realised this has a dupe - [How does The Talkbox work?](https://music.stackexchange.com/questions/2795/how-does-the-talkbox-work) & another with a pic of Frampton's actual talk box from Comes Alive - https://music.stackexchange.com/questions/48809/air-tube-to-change-the-sound-of-guitar?
Answer: It's actually unbelievably simple.
The guitar signal feeds to an on-stage box, which contains a small speaker. A hollow plastic tube comes from that box up to the performer's mouth.
The performer puts the end of the tube in his mouth & can shape the signal straight into his vocal mic.


Identify current session within Windows Forms application: session ID?

Question: In ASP.NET, each session can be identified by its SessionID variable. Currently, I'm working on a project for which I want to be able to identify each separate user session. In other words, I'm looking for a session identifier or an equivalent variable.
I've looked in the Application, Environment and AppDomain classes, but I couldn't find such a variable. So my question is: how should one identify the session(s) an application is currently handling?
Answer: Maybe System.Diagnostics.Process.GetCurrentProcess().Id would cover your needs? That will give you a number that uniquely identifies the currently running process on the system. The number is valid only while the process runs, and when it has quit any other process may be assigned the same number when it is started.
Comment: Sounds like a step in the right direction. However, I've no guarantee that the next time a user starts an application, the process ID is not identical to the ID of the first start ('session')?
Comment: No, in theory you can start the application twice in a row and get the same process id. The only guarantee that you have is that on a given system, there will never be two processes running at the same time with the same id. That should not be a problem if you remove session-related info on application close.
Comment: I've looked into System.Diagnostics.Process.GetCurrentProcess() and although there is a property SessionID, the property StartTime largely covers my needs. One can identify a session based on its start time. For the project I'm working one, this will suffice. Thanks.
Answer: I'm not quite sure I follow you, but if you're trying to track each instance of the application's lifecycle, you could create a GUID as an instance member somewhere appropriate. Whenever you feel a new "session" has been created, you can create and store this GUID - probably when the user logs in (or the main form loads if you don't have a login mechanism).
I'm assuming of course you have a multi-user enviroment with some kind of server attached, otherwise I can't really see a need for sessions.
Answer: You could check some of the options in the Environment class such as Environment.UserName, Environment.MachineName or Environment.UserDomainName
Comment: This is what I currently do. However, I also want to distinguish two application start events from the same user.


Disabling javascript with htmlunit through a remote webdriver

Question: When getting a page with selenium from a python script, using htmlunit through a remote webdriver, I get this error:

WebDriverException: Message: u'TypeError: Cannot find function addEventListener in object [object HTMLDocument]. (https://xxx.xxx.com/static/js/jquery-2.0.3.min.js#4)

So to avoid this exception I tried to disable javascript when initializing my webdriver, but I can't manage to do it...
I tried to set the desired_capabilities with webdriver.DesiredCapabilities.HTMLUNIT (vs HTMLUNITWITHJS), but nothing changed. So I tried to define the capabilities manually, but it didn't help.
Here are some examples of what I did, with the results:
In [45]: driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)

In [46]: driver.desired_capabilities
Out[46]:
{u'browserName': u'htmlunit',
 u'cssSelectorsEnabled': True,
 u'javascriptEnabled': True,
 u'platform': u'LINUX',
 u'version': None,
 u'webdriver.remote.sessionid': u'3aa1c9c0-9d85-4e22-ad2b-1116950cf86d'}

In [47]: driver = webdriver.Remote(desired_capabilities={'browserName': 'htmlunit', 'javascriptEnabled': False, 'platform': 'ANY', 'version': ''})

In [48]: driver.desired_capabilities
Out[48]:
{u'browserName': u'htmlunit',
 u'cssSelectorsEnabled': True,
 u'javascriptEnabled': True,
 u'platform': u'LINUX',
 u'version': None,
 u'webdriver.remote.sessionid': u'426aef71-2b7c-45c5-9313-c3dbbec07c7f'}

So here I am. If someone has any idea... :)
Answer: Partial answers, in case someone else encounters the same kind of issue:
1/ Having a look at the server logs, it appears that my instructions regarding the javascriptEnabled setting are actually taken into account by the selenium server. The desired_capabilities dictionary displayed by the client is not relevant.
15:21:35.575 INFO - Executing: [new session: Capabilities [{platform=ANY,  javascriptEnabled=false, browserName=htmlunit, version=}]])
15:21:35.576 INFO - Creating a new session for Capabilities [{platform=ANY, javascriptEnabled=false, browserName=htmlunit, version=}]
15:21:35.590 INFO - Done: [new session: Capabilities [{platform=ANY, javascriptEnabled=false, browserName=htmlunit, version=}]]

2/ Reading this discussion, it appears that what I expected from the javascriptEnabled setting isn't what it is meant for. This doesn't disable javascript execution in the browser, but javascript 'injection' from a client script.
Disabling javascript execution doesn't seem possible using HTMLUNIT. So this question can be closed as it isn't relevant.
The only solution is to get HTMLUNIT to work with jquery-2.0.3. I upgraded it to the latest version, but it didn't help...
[Edit] Finally a suitable solution was found here: preventing HTMLUNIT from throwing an exception on a javascript error.
In [14]: driver = webdriver.Remote(desired_capabilities={'browserName': 'htmlunit', 'javascriptEnabled': False, 'platform': 'ANY', 'version': '', 'setThrowExceptionOnScriptError': False})

I can now load my url! :)


checking variable null-safety with ! and?

Question: I trying to understand the basics of null-safety in dart
what is the best use for this:
// model
class MyModel {
  String? name;
  MyModel({this.name})
}

// view-controller
MyModel? response;

// do some async operations here, on success response get a value

if(response!.name == null){
}

if(response?.name == null){
}

// what is the best practice? and what should i use in this case?
// ! or ?

Comment: If `response` can be null, you don't have a choice. `response!` asserts that `response` is not `null` and will crash your program if that assertion is wrong.
Comment: i got what i was looking for with a good explanation here
https://flutterbyexample.com/lesson/null-aware-operators

the syntax is called null-aware operator
Answer: Go through this codelab excersie and you will get with basics of using '?' vs '!'.
For reference I am explaining both a bit:
suppose you want to have a string variable which could be, at any point null or can be used to store null value. For this case you can't use String to initialize your variable, instead you need to do it like this way :-
String? str
And now the '!' part which is called 'null assertion operator'. Sometimes flutter sdk thought that maybe any variable you have used might be null at runtime and so it throws you error that the object is nullabe. So for that case if you are sure that, the object could never be null at runtime so you need '!' operator to show flutter that it couldn't never be null.
If you have any confusion then do check that codelab exercise for sure.


How to complete this particular proof of $cl(cl(A)) = cl(A)$ for a subset $A$ of topological space $X$?

Question: I want to prove that $cl(cl(A)) = cl(A)$ for a subset $A$ of topological space $X$. Given a subset $A$ of a topological space $X$, I have at hand the following two equivalent definitions about the closure of $A$ (denoted $cl(A)$):

Definition 1: The closure of $A$ is the intersection of all closed sets containing $A$.
Definition 2: $x \in cl(A)$ if and only if every open set $U$ containing $x$ intersects $A$.

Based on the first definition, I can prove the statement by first showing that $A = cl(A) \Leftrightarrow A \textrm{ is closed}$. The statement $cl(cl(A)) = cl(A)$ follows from the fact that $cl(A)$ is closed.
However, I failed to prove the statement using the second definition directly, especially the $cl(cl(A)) \subset cl(A)$ part.

My trial of $cl(cl(A)) \subset cl(A)$: Take any $x \in cl(cl(A))$, we have (by definition 2) every open set $U$ containing $x$ intersects $cl(A)$. Suppose that $x \notin cl(A)$ by contrapositive, then there exists an open set $V$ containing $x$ that does not intersect $A$. Therefore, we get an open set $S$ containing $x$ such that (1) $S \cap cl(A) \neq \emptyset$ and (2) $S \cap A = \emptyset$.

So, how should I obtain the contradiction?
Answer: The basic fact that you might be missing is the following:  If $\newcommand{\cl}{\mathrm{cl}}U \subseteq X$ is open and $A \subseteq X$ is arbitrary, then $U \cap A = \varnothing$ implies that $U \cap \cl ( A ) = \varnothing$.  (This is due to the fact that $U$ is an open neighbourhood of each of its elements which is disjoint from $A$, and so no element of $U$ can be an element of $\cl ( A )$.  Also worth noting is that $X \setminus U$ is a closed set and $A \subseteq X \setminus U$, and so $\cl ( A ) \subseteq X \setminus U$ by definition of $\cl ( A )$.)

You can also do this pretty directly.  Suppose that $x \in \cl ( \cl ( A ) )$, and let $U$ be any open neighbourhood of $x$.  Then $U \cap \cl ( A ) \neq \varnothing$, so pick some $y \in U \cap \cl ( A )$.  Note that $U$ is an open neighbourhood of $y$ and $y \in \cl ( A )$, and so $U \cap A \neq \varnothing$.
Answer: If $x\in S\cap cl(A)$ then $S\cap A\neq\emptyset$ by definition 2 because $S$ is an open set containig $x\in cl(A)$.
Answer: Take $x\in cl(A)$ and an open set $U$ such that $x\in U$. Because $x\in cl(cl(A))$, every open set containing $x$ will intersect $cl(A)$. Therefore, you have some $y\in cl(A)\cap U$. Because $y$ is in $cl(A)$, this means that $U$ intersects $A$. Therefore, $x\in cl(A)$


How to do an embedded select (with count()) with the Drupal 7 database api?

Question: Another day, another challenge with the Drupal 7 database API.  I'm trying to do something like this:
<code>select n.nid,
     (select count(*) as count
          from {node_cnt} nc where nc.nid = n.nid) as node_count
from {node} n
</code>
That is, I want to get back a set of node id's and the number of times that each id appears in the table node_cnt.  I'm going to be laying in some other conditions and pager stuff, so I think I need to do this with db_select.  This should be simple, I suppose, but I just haven't figured out the right way to think about this stuff yet.  Any advice out there?  Thanks!
Answer: I don't think there's any existing method that will let you add a structured sub-query as an expression, so you're probably going to be left with something like this:
<code>$query = db_select('node', 'n')
  ->fields('n', array('nid'));

$sub_query = '(select count(*) as count from node_cnt nc where nc.nid = n.nid)';
$query->addExpression($sub_query, 'node_count');

// Build the rest of the query.
</code>


multiple definition of 'true' - but its not?

Question: I have a double type bool so have added to a header:
typedef double bool;
extern bool true;
extern bool false;

with:
bool true = 1.0;
bool false = 0.0;

in the corresponding C file.
However I now have  the errors multiple definition of true, and the same for false, pointing to the first line of the first function in the C file. the error that says 'previous declaration was here' points to the same line... it doesnt make any difference which function is placed first in the file it always points to it.
My header files, though included via a common header file, do have include guards so I hopefully shouldn't have multiple declaration of true and false there.
I have changed the typedef to tBool with vars tTrue and tFalse, which solves the problem, but I don't get why it occurred in the first place? As there are still some bool types using true and false in the code it seems like the compiler may have a definition for true and false as ints already... though I didn't think C did this
Im using dev-c++ 220.127.116.11 IDE that uses mingw, though Im not sure which version mingw.
Anyone know why this happened?
Comment: Are you (explicitly or otherwise, perhaps through an IDE-generated precompiled header) including stdbool.h? http://pubs.opengroup.org/onlinepubs/007904875/basedefs/stdbool.h.html
Comment: Even if the identifiers `bool`, `true` and `false` were not already reserved by `stdbool.h` for the purpose that you can easily imagine, declaring them with a base type of `double` is the weirdest attempt to emulate a Boolean type that I have ever seen. Just don't do cruft like that.
Comment: @Toby - *may have lots of parameters for so I dont want to have to create different typed arrays for each type of possible parameter and then have to keep track of indexes of each array to correlate the parameters to their other relevant info* - That would indeed be very bad.  However, this is probably worse.  If you need to pass a lot of parameters into a function, you should use a `struct`!  This will allow you to create named 'indexes' into the parameter.  Alternatively, you should think about completely refactoring your code; it sounds like you've got a lot of issues.
Comment: Just tried this in  an eclipse based IDE that uses a different compiler with no problem, so I guess its mingw.
Comment: @Graham Maybe. I have stdlib, string and stdio included, but just tried commenting each and all out with no change. In fact commenting them all out doesn't produce any additional errors and the program still works so I guess these are being added by the compiler  which prob means stdbool is being added similarly...ta
Comment: @Jens, yeah I guess it is, and I've tried to avoid it but in this case bool is a type of parameter where the parameter may also be a double number. I may have lots of parameters for so I dont want to have to create different typed arrays for each type of possible parameter and then have to keep track of indexes of each array to correlate the parameters to their other relevant info. this is ugly but better in my opinion.
Comment: You are not by any chance compiling this as `C++` code?
Comment: Are you sure that you didn't include your *.c file (this would be a very bad idea) ?
Comment: @Toby, I don't get a word of your explanation. In any case, don't name your stuff such that everybody would suspect it to be a Boolean type, when it isn't.
Comment: Are you compiling as C or C++? In C++ those words are already reserved, and in C they can be defined in the header ``. Also, by use `double` as the boolean type? Normally it's either `char` or `int` or an enumeration.
Comment: @JoachimPileborg pretty sure Im compiling as C. all files are named .c
build commands are like: $(CC) -c SCPI_Parser.c -o SCPI_Parser.o $(CFLAGS)
so guessing it is def C compiled
Answer: It sounds to me like your parameter is not really a Boolean value at all.  You have a floating point parameter with special cases for the discrete numbers 0.0 and 1.0.  Create two double constants instead of a type.
C99 added definitions for the type _Bool, a macro bool, a macro true, and a macro false.  Try inserting the following in your header:
#if __bool_true_false_are_defined
# error "stdbool.h has been included"
#endif
#ifdef bool
# error "bool is already DEFINED"
#endif
#ifdef true
# error "true is already DEFINED"
#endif
#ifdef false
# error "false is already DEFINED"
#endif

If any of these fire, then you are including stdbool.h somewhere.  You should be able to #undef the three macros and then set up your types safely.  Of course, this will probably break if someone else expects bool to be a small integer value and has more style problems that you can shake a stick at.
ISO/IEC 9899:1999 does make a concession to the fact that many groups have already defined their own Boolean types before it was added to the Standard.  This is the rationale for defining bool, true, and false as macros instead of new keywords.  However, the following warning is explicitly included:

7.26.7 Boolean types and values <stdbool.h>
The ability to undefine and then perhaps redefine the macros bool, true, and false is an obsolescent feature.


Reconciling using background-size: cover while building a website from a psd file?

Question: When I use background-size: cover; it causes the image to scale larger to fit the screen. This scaling means the background image doesn't match the dimensions from the psd file I'm trying to replicate. How do I keep the responsiveness that background-size: cover; provides, while maintaining the exact measurements from the psd? Thanks a lot for any help.
html:

css:
.bg-img {
    position: absolute;
    background: url(../images/site-bg.jpg) no-repeat;
    background-size: cover;
    width: 100%;
    height: 100%;
}

Answer: If your intention is to have the background image be able to grow to the maximum 'natural' size of the source image and then not be scaled any larger, this would likely have to be achieved through some combination of media queries (testing both portrait, landscape and square window sizes at various sizes), CSS, or JavaScript.
You could consider using a max-width and/or max-height attribute, along with top: 0; bottom: 0; left: 0; right: 0; margin: auto;. This may yield acceptable results, though it may be that JavaScript is where you would need to look for the most reliable result.
Comment: I feared this. Thanks for the insight.
Answer: background: url(../images/site-bg.jpg) no-repeat center center;

?
Comment: This just makes the image even larger, far larger than `background-size:cover`. Thanks for the help!


collision between a particle array and a box

Question: Im working on a school project and I need to get collision between an array of particles and a box, here is my current code:
for(var i : int = 0; i < particles.length; i++)
{
    particles[i].update();

    if(Particle.hitTestPoint(Square))
    {
        particle = particles.shift();
        particle.destroy();
    }
}

I get an error telling me that im trying to call an undefined method (hittestpoint) through a reference with static type class.
Any help would be greatly appreciated, thank!
Here is the code for the Particle.
package

{
    import flash.display.*;
public class Particle
{
    public var clip : DisplayObject;

    public var xVel : Number = 0;
    public var yVel : Number = 0;

    public var drag : Number = 1;

    public var gravity : Number = 0.0;
    public var shrink : Number = 1;
    public var fade : Number = 0;
    public function Particle(symbolclass : Class, target : DisplayObjectContainer, xpos : Number, ypos : Number)
    {
        clip = new symbolclass();

        target.addChild(clip);

        clip.x= xpos;
        clip.y= ypos;

    }
    public function update() : void
    {
        clip.x += xVel;
        clip.y += yVel;

        xVel *= drag;
        yVel *= drag;

        yVel+=gravity;

        clip.scaleX *= shrink;
        clip.scaleY *= shrink;

        clip.alpha -= fade;
    }
    public function destroy() :void
    {
        clip.parent.removeChild(clip);
    }

}

}
I used this tutorial for the particles, and my goal is to add collision to them
Comment: In the first line in the loop, you refer to `particles[i]`, but then you refer to `Particle` or `particle`. Why don't you just try to be more consistent, and see what happens?
Comment: Thanks for the suggestion, I made the change and it comes up with an error saying property hittestpoint not found on Particle
Answer: The Particle class must extend MovieClip to have the hitTestPoint method. Try changing the class to:
import flash.display.MovieClip;
public class Particle extends MovieClip
{
    //code here

and import specific classes in your code (see MovieClip class as that's the one you are using and it's methods) for better results as good practice.
Comment: Both answers are correct. Note, that the `Particle` class doesn't have to extend `MovieClip` it can simply extend `DisplayObject` (that's where the `hitTestPoint()` method is defined).  Finally, when calling `hitTestPoint()` you should pass in the proper parameters, the method signature is: `hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean`
Comment: CheeseWarlock  is also right: he needs to test object collision if "square" is an actual square object. Also you should pass at least x, y parameters when using hitTestPoint() method.
Answer: I'm not sure what particle refers to in that code since it's not defined in what you posted, but particles[i] is the particle you want to test.
Your Particle class doesn't have a hitTestPoint function- but it contains a DisplayObject that does. So with those two things in mind, you can call hit tests using particles[i].clip.hitTestPoint.
Next problem: you're trying to pass the class Square to the hitTest rather than an instance. And still, hitTestPoint takes a single point as its argument, not an object like what a square would represent. So you will probably want to use hitTestObject instead.
Comment: Thank you for the help! I was able to fix the program and got the collision working.
Answer: Edit: Updated my answer now that Particle code was posted.
Your Particle class doesn't define hitTestPoint.  In addition to that, you are calling a static method which I don't think you want here... you want an instance method.
Make sure you define hitTestPoint in your Particle class.  Then, instead of Particle.hitTestPoint, try particle.hitTestPoint (note upper case, which refers to the class is changed to lower-case which refers to the instance.
Try this:
for(var i : int = 0; i < particles.length; i++)
{
    var particle:Particle = particles[i];
    particles.update();

    if(particle.hitTestPoint(Square))
    {
        particle = particles.shift();
        particle.destroy();
    }
}

Comment: That definitely makes sense, I tried it with the changes you suggested and paying close attention to the capitalization, still getting an error saying "call to an undefined method" source is (particle.hitTestPoint(Square)).
Comment: @FieryAvocado Well, you posted your `Particle` class, which is great... but there is one problem... `Particle` does not define a function called `hitTestPoint`.  That is your problem.  Editing my response.
Comment: Thank you! I was able to get the program to work with your help!
Comment: @FieryAvocado Then make sure to mark the answer correct, please.


Email Campaign Manager Reports?

Question: I am working on Email Campaign Manager reports sections and I am unable to understand few things in reports.

What is Value and how this Value generates for a message?
Value per visit?
Value per Email?
Visit per email?

Please see attached screenshot.
Answer: I suspect this may not entirely answer your question, but from the ECM Marketer's Guide (page 16):

Value per sent email – The average value that a message has generated.
Value per visit – The value per visit this message generated.
Visits per email sent – The average number of visits to the website that a message induced.

So that leads to the next logical question: What is "value"?  Value is something that you define from within Sitecore.  You score your content and assign value to it.  Content that is deemed more important for the business will have a higher value than content that is not as important.  When a user visits your site as a result of an ECM email, DMS tracks the visit and as they navigate around content that has value associated with it, the value is accumulated.
Check out the Marketing Operations Cookbook for more information on assigning value to your content.
Hope this helps a bit.
Comment: Here's a very interesting post on engagement value, and what it actually is (and how to use it). http://www.sitecore.net/Learn/Blogs/Best-Practice-Blogs/Jill-Grozalsky/Posts/2014/05/Sitecore-DMS-Engagement-Values.aspx - that may answer your last question
Comment: Thanks Craig, yes I also found these things in same document but Value is not understandable in that document. But I think you are correct here I'll check in this document and let you know.
Comment: One other thing that this Value is Profile Value or Engagement Value Can you please confirm. I think this should be something profile values on page

Email Campaign Manager Reports?


Bash script to organize files based on their name

Question: I need help getting a bash script set up to move files to folders based on the beginning of their name (up til the first .), so for example:

aaa.123.txt
aaa.124.txt
aaa.156.txt
aaa.122.txt
bbb.1424.txt
bbb.13.txt
bbb.13.txt
ccc.222.txt

this would generate the following folders, with the appropriate text files inside

aaa/

aaa.123.txt
aaa.124.txt
aaa.156.txt
aaa.122.txt

bbb/

bbb.1424.txt
bbb.13.txt
bbb.13.txt

ccc/

ccc.222.txt
Comment: `for i in *.*.txt; do d=${i%%.*}; mkdir -p "$d"; mv "$i" "$d"; done`  This won't create any folders for you, but you probably meant to say "directories".
Comment: @WilliamPursell making difference between the terms *folder* and *directory* is unnecessary and just confusing - whats the impact of this?
Comment: @alecxs I disagree. Folders are an artifact of the gui. In the physical world, folders contain files. Directories do not. The belief that directories contain files is one of the common fundamental misunderstandings.
Comment: whats the impact of this wrong belief? i read [this](https://stackoverflow.com/questions/5078676/what-is-the-difference-between-a-directory-and-a-folder) and still don't get it, there is no benefit of that kind of knowledge
Comment: "no benefit"!?  Seriously?  You dont see the benefit of understanding how the filesystem works?  You dont see the harm of misunderstanding it?  Look at iTunes and observe the phenomenal waste of disk resources caused by its pandering to this misunderstanding.  The ability to work with files is one of the core purposes of a computer.  Not understanding how that system works leads to inefficient, inelegant solutions. The word "folder" was introduced by marketing and has no place in a technical discussion that isnt about a gui.
Comment: we are talking about folders and directories (not files)
right? unless you can tell alternative cmd like `mkdir` (but for creating folders) i can't see whats the problem in mixing up terms. if i want to create a folder but in real i do make a directory and i don't even know that this not what i believe, that makes absolutely no difference
Comment: funny thing is i don't even know how to create a *"folder"* or a *"subfolder"* (because i can just create directories with `mkdir`). so iTunes waste disk resources caused by misunderstanding folders and directories? is there any example for inefficient inelegant solution with folders instead of directories?
Answer: Here you go.
MYDIR="${PWD}";

for FLE in ${MYDIR}/*.txt;
do
FNAME=$(echo $(basename ${FLE}) | cut -d "." -f 1);

mkdir ${FNAME};

mv ${FLE} ${FNAME};

done

Change ${PWD} to whatever the path should be. Or just execute the script from the directory where the files are.
Comment: *Change ${PWD} to whatever the path should be.* except path with spaces


How can I get the kernel Matrix values of the CNN?

Question: I am new to machine learning. I am working with a Neural Network that implements the U-Net.
The thing which I understand is when a convolutional layer is created:
createsconv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)

let the in_channel = 3 and out_channel = 64 then,
for kernel_size = 3 it computes with a 3*3 Kernel.
But my question is what are the values of this kernel? How it gets the values?
Comment: Here's a search to get you started: https://stats.stackexchange.com/search?tab=votes&q=%5bbackpropagation%5d%20how%20cnn%20answers%3a1%20score%3a1
Answer: Those are the learnable parameters which are learnt through the usual back-propagation algorithm. They can be accessed before and after the learning phase via nn.weight as described in the PyTorch manual.


SQL Group rows together based on specified Value

Question: I'm looking to group rows together based on a set value. so I have a query that has 100 rows I would like to group them by every 10 rows and assign a number starting with 1.
So
First 10 rows would be assigned 1, next 10 get 2 next 10 get 3 and so on.
I have tried working this out with row_number, rank etc but not been able to do it.
is this possible?
Cheers
Patrick
Comment: Possible duplicate of [In SQL, how can you "group by" in ranges?](https://stackoverflow.com/questions/232387/in-sql-how-can-you-group-by-in-ranges)
Answer: Based on ROW_NUMBER and integer division:
<code>(Row_Number () Over (ORDER BY whatever) -1) / 10 + 1
</code>


Como criar listas em for?

Question: Queria saber se tem como criar varias listas em for.
exemplo, o cara coloca no input (num_jogadores) "2" então eu queria cirar
2 listas ------ lista1 = [] e lista2 = []
num_jogadores = int(input("digite o numero de jogadores: "))

for i in range(0, num_jogadores):
  lista[i] = []
#criar listas com o tanto de num_jogadores

Comment: Troque `lista[i] = []` por `lista.append([])`. Porém acredito que o ideal seria trabalhar com lista de objetos.
Answer: O melhor jeito de fazer isso é utilizando uma List Comprehension.
n = int(input('Digite o número de jogadores: '))

lista = [[] for _ in range(n)]

Como criar listas em for?


Authorize parou de funcionar

Question: Segue os meus códigos
Login :
public ActionResult Login(login login, string returnUrl)
    {
        if (ModelState.IsValid)
            {
                if (new AllFictionMembershipProvider().ValidateUser(login.email, login.senha))
                {
                    FormsAuthentication.SetAuthCookie(login.email,false);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
        return View(login);
    }

Membership provider
public override bool ValidateUser(string username, string password)
        {
            EntidadesAllFictionBD db = new EntidadesAllFictionBD();

            var query = (from l in db.login
                         where l.email == username && l.senha == password
                         select l).SingleOrDefault();
            if (query==null) {
                return false;
            }

            else {

                return true;
            }

            }

Role provider:
 {
        public override string[] GetRolesForUser(string username)
        {
            using (EntidadesAllFictionBD db = new EntidadesAllFictionBD())
            {
                usuario user = db.usuario.FirstOrDefault(u => u.email.Equals(username, StringComparison.CurrentCultureIgnoreCase));

                var permissao = from p in db.permissao
                                from u in db.usuario
                                where p.idpermissao==u.usuario_idpermissao
                                    select p.permissao1;

                if (permissao != null)

                    return permissao.ToArray();
                else
                    return new string[] { }; ;
            }
        }
        public override bool IsUserInRole(string username, string roleName)
        {
            using (EntidadesAllFictionBD db = new EntidadesAllFictionBD())
            {
                usuario user = db.usuario.FirstOrDefault(u => u.email.Equals(username, StringComparison.CurrentCultureIgnoreCase));

                var permissao = from p in db.permissao
                                from u in db.usuario
                                where p.idpermissao == u.usuario_idpermissao
                                select p.permissao1;
                if (user != null)
                    return permissao.Any(p => p.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
                else
                    return false;
            }
        }

E esse é o controller que eu quero bloquear:
[Authorize(Roles="admin")]
    public class BancaController : Controller

Ontem, ao acessar qualquer action desse controller, era mostrado um formulário de login, e qualquer usuário que não possuísse a permissão admin, era redirecionado para a pagina de usuário. Hoje, quando eu acesso essa pagina, ele exibe o mesmo formulário de login, porém, qualquer usuário pode acessar as actions agora.
O que estou fazendo de errado? Não fiz nenhuma mudança de ontem para hoje.
Comment: Também não. Só adicionei um usuário com a permissão de admin. Porém, só estou logando com o usuário que possuí a permissão user.
Comment: Descobri o problema, só não sei resolve-lo. Quando eu adiciono um usuario com permissão de admin, por algum motivo, todos outros usuarios ganham o mesmo acesso, mesmo que ele tenha uma permissão de usuario comum. Alguma ideia de como resolver isso?
Comment: @CiganoMorrisonMendez Estou com o erro Cannot implicitly convert type 'System.Guid' to int nessa linha aqui    userRole.UserRoleId = Guid.NewGuid(); Estou utilizando um daqueles exemplos que você postou na pergunta sobre o login. Você quer que eu realize uma nova pergunta, ou você poderia responder por aqui mesmo? Valeu.
Comment: @RyanSantos Simplesmente remova a linha que funciona.
Comment: @CiganoMorrisonMendez De fato. Consegui resolver, agora cada usuário tem de fato sua permissão. Mais uma vez, obrigado!
Comment: Nem trocou a role do usuário para fazer um outro teste e esqueceu de voltar a uma role que não seja de admin?
Comment: @RyanSantos Já colocou um breakpoint na primeira linha de `GetRolesForUser` pra ver o que está acontecendo?
Comment: @CiganoMorrisonMendez Então, eu consigo visualizar o email de quem está tentando acessar, mas não consigo visualizar os valores dos outros atributos.
Comment: @RyanSantos Atualize sua pergunta com o método `AddUsersToRoles` do seu `RoleProvider`, por favor.
Comment: @CiganoMorrisonMendez eu não cheguei a implementar esse método. Como estava carregando as roles direto do banco, achei que não seria necessário.
Comment: É aí que está a raiz do seu problema. Possivelmente alguma coisa está inserindo permissões para todo e qualquer usuário inserido.
Comment: @CiganoMorrisonMendez Entendi. Vou implementar aqui.
Answer: Apenas formalizando uma resposta:
Verifique o método AddUsersToRoles do seu RoleProvider. Aparentemente é um bug na implementação dele.
Answer: Me parece que seu select está trazendo todas as permissões de todos os usuários, já chegou a debugar o retorno dele?
var permissao = from p in db.permissao
                from u in db.usuario
                where p.idpermissao==u.usuario_idpermissao
                select p.permissao1;

Não conheço sua estrutura, mas talvez o correto seja usar um join:
var permissao = from u in db.usuario
                join p in db.permissao on p.idpermissao equals u.usuario_idpermissao
                where u.id == user.id
                select p.permissao1;

Authorize parou de funcionar


C++ C26495 warning shows up but I don't know how to solve

Question: Here is my code:

<code>#pragma once

#include "Card.h"

class Foundation {

    Card* cards[13];
    int current;
    char suit;
    friend ostream& operator<< (ostream& os, Foundation& f);
public:

    Foundation(char suit = 'H');
    bool isPlacable(Card* c);
    void put(Card* c);
    bool isFull();
    void clear();
};

/* Warning  C26495  Variable 'Foundation::cards' is uninitialized. Always initialize a member variable (type.6) below. */

Foundation::Foundation(char suit) {

    this->suit = suit;
}
</code>

What is the problem?
Comment: What do you not understand in the warning? The problem is very exactly described,
Comment: [C26495 MEMBER_UNINIT](https://learn.microsoft.com/en-us/cpp/code-quality/c26495?view=msvc-160) and [Warning C26495 on structures?](https://stackoverflow.com/questions/55667784/warning-c26495-on-structures) -- self-expanitory...
Comment: Ok I admit the problem was kinda obvious lol. I didn't read clearly.
Answer: You get the warning because you don't initialize the member in the constructor or use an initializer list.
probably this can fix your warning:
<code>class Foundation {

    Card* cards[13] = {};
    int current;
    char suit;
    friend ostream& operator<< (ostream& os, Foundation& f);
public:

    Foundation(char suit = 'H');
    bool isPlacable(Card* c);
    void put(Card* c);
    bool isFull();
    void clear();
};
</code>
Comment: actually this is array default empty initializer
```c++
int arr[5] = {};    // results in [0, 0, 0, 0, 0]
```


How posix system support unicode?

Question: I have seen a lot of API posix system, for example Linux & Mac & android, which accept const char* as the argument for file path.
One of example is dlopen, as the document show, the first argument is const char*, so does it support Unicode file path, for example path with Chinese?
Comment: FYI: There are multiple Unicode encodings: UTF-8, which is favored for interchange and on Unix systems for everything, UTF-16 which Windows uses due to baskwards-compatibility-constraints and UTF-32 which can represent every Unicode Codepoint as a unit of constant length. All others are only interesting in niche applications.
Comment: Go for all UTF-8, that way has the least gotchas. Even on systes having a UTF-16 API, everything else is done in UTF-8, so you are forced to convert there anyway. Just be sure you always use the native Unicode API always, perhaps with a specialised widen/narrow converter. http://utf8everywhere.org
Comment: @Deduplicator, I want to wrapper an cross platform Unicode API, I don't want to consider performance and memory usage, because the difference will be small. So for productivity and easy usage, any thoughts about the pros and cons for UTF-8 or UTF-32?
Answer: POSIX is not required to support Unicode filenames. (See: https://stackoverflow.com/a/2306003/481267) However, provided that they are encoded in UTF-8, there are no technical obstacles to supporting Unicode. Many modern file systems allow any character in a file name except \0 and /.
The POSIX API deals with null-terminated byte sequences, and when a string is encoded in UTF-8, no code point's representation contains a zero byte. Furthermore, all characters outside the ASCII range (0x00-0x7f) are encoded entirely using bytes with the high order bit set (0x80-0xff) so there is no chance that the system will be confused into thinking that there is a directory separator in the middle of some Unicode character.
Comment: When a string is encoded in UTF-8, NUL encodes to a zero byte.  [RFC 3629](https://tools.ietf.org/html/rfc3629) says `UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4` and `UTF8-1      = %x00-7F`.  You might be thinking of UTF-8 like [variants](http://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html#modified-utf-8) but they are explicitly non-conforming around NUL.
Comment: Yeah, sorry, I meant that for all code points except for NUL itself.
Answer: It's assumed that in modern Linux/Unix systems unicode filenames are expressed in UTF-8 locale which is byte-oriented (although some of underlying filesystem stores internally filenames in UTF-16).

How posix system support unicode?


X=Y+Z, know the distribution of X, under which conditions can I recover(pin down) the distribution of Y and Z?

Question: You may add any conditions you want if this is doable. Otherwise, it would be great if you could provide any impossibility result.
Also greatly appreciate it if you could guide me to related problems, results or papers.
Many thanks:)
Answer: In general you can't say which distributions gave you $X$.
However, with some additional restrictions you can tell something about the family of that distribution.
An example is family of Gaussian distributions.
Famous Cramer's theorem says that if $X$ has normal distribution, then $Y$ and $Z$ also must have normal distribution.
See Cramer's theorem
Also there is Raikov theorem which tells the same for Poisson distributed random variable.
And there is theorem about sums of normal and Poisson distribution. So that if you know that $X$ has the same distribution as Poisson+Normal, then $Y$ and $Z$ are necessarily like that (one of them is Poisson one is normal).
Hope that helped.
Comment: @kolobokish You seem to take independence very lightly. I consider your answer as wrong and misleading because you claimed Cramer's Theorem to hold without independence. Please edit your answer.
Comment: Thank you so much. This is quite helpful!! I read the theorem link you provided, which says that this problem relates to decomposition theory for random variables as sums of independent variables.
Comment: Yes of course. This is only for independent random variables. One additional note. Even In a general class of infinite divisible distribution or stable distribution (in both cases) you can't for sure say which distributions gave rise to $X$, even though Poisson and normal are in that classes.
Comment: I see. Thanks for the note. Indeed, except for a few quite restrictive special cases, in general we cannot reverse engineer the distribution of Y and Z.
Comment: Sorry. I meant "not only". I'm sorry.