Como desconsiderar parcialmente NA em operações no R com uma série histórica de dados?

Question: Possuo um conjunto de dados de chuva medidos a cada hora e preciso somar esses dados ao longo do dia. Para isso, estou utilizando os comandos abaixo:
library(dplyr)
df %>% group_by(data) %>%
summarise_all(funs(Media=sum(., na.rm=TRUE)))

Porém, meu df apresenta três características: i) dias sem NA, ii) dias com alguns NAs, e iii) dias apenas com NA, conforme exemplo abaixo:

Com isso, se eu considerar na.rm=TRUE, os dias que possuem apenas NA, como o dia 03/01/10, retorna com um valor 0 após a soma. O que está errado, pois não sei se não choveu mesmo, uma vez que não tenho o dado. Pelo contrário, na.rm=FALSE, desconsidero tanto os dias que possuem apenas NA quanto os dias que possuem alguns NAs e algumas medidas, o que também é ruim.
Na saída apresentada abaixo, o dia 02/01/2010 deveria apresentar um valor diferente de 0.0 e o dia 03/01/2010 deveria apresentar NA. Quando calculo a média Media=mean o resultado é correto, porém para Media=sum não consigo corrigir isso.
data    "rain_mm_ToT"
01/01/2010  19.7
02/01/2010  0.0
03/01/2010  0.0
04/01/2010  0.5
05/01/2010  0.0
06/01/2010  0.0
07/01/2010  6.3
08/01/2010  1.9
09/01/2010  1.4
10/01/2010  0.0
11/01/2010  0.0

Como a série é muito longa, não consigo fazer uma avaliação minunciosa de onde estarão os erros. Desse modo, gostaria de saber se existe uma alternativa para considerar "parcialmente" os valores NAs, isto é, retornar com NA apenas nos dias que não apresentam nenhuma medição e realizar a soma naqueles que possuem tanto NA quanto medição?
Obrigada!
Comment: Pode, por favor, **editar a pergunta** com a saída de `dput(df)` ou, se a base for muito grande, de `dput(head(df, 20))`?
Answer: Esta resposta trata os casos em que pelo menos um elemento do vetor cuja média deve ser calculada é NA com na.rm = TRUE. Mas ao contrário do que está escrito na pergunta, quando todos os elementos são NA o valor da média é NaN, não é 0. Isto faz sentido uma vez que se removermos todos os dados temos a soma de zero elementos dividida por zero, o comprimento desse vetor de zero elementos. Ora 0/0 dá NaN.
library(dplyr)

df %>%
  group_by(data) %>%
  summarise_all(list(Media = ~mean(., na.rm = anyNA(.))))
## A tibble: 3 x 2
#   data  Media
#  <int>  <dbl>
#1     1   2.5
#2     2   2.33
#3     3 NaN

Esta segunda forma de calcular as médias por grupos tendo em conta os valores em falta, NA, considera o caso de todos os valores serem NA à parte e tem como resultado NA. Mas pelo motivo explicado acima creio que o primeiro código é o mais correto.
df %>%
  group_by(data) %>%
  summarise_all(list(Media = ~mean(., na.rm = !all(is.na(.)))))
## A tibble: 3 x 2
#   data Media
#  <int> <dbl>
#1     1  2.5
#2     2  2.33
#3     3 NA

Dados de teste.
df <- data.frame(data = rep(1:3, each = 4),
                 `chuva(mm)` = c(1:4, c(1,2,NA,4), rep(NA, 4)))

Comment: Obrigada pelo comentário! Quando calculo valores médios de chuva para o dia o resultado não apresenta problemas (Media =~mean). Porém, quando preciso dos valores acumulados ao longo do dia (Media=sum) é que tenho dificuldades. Pois a função retorna com 0.0 tando onde tenho apenas NA quanto nos dias em que tenho algumas medições e alguns NAs.


order of execution of hook_node_presave and custom submit function

Question: Does hook_nood_presave execute before or after a custom form submit handler in the same node ? and I need to perform some action after the node contents have been saved in the database. So, where should put this code ?
Answer: In the core system hook_node_presave() is only ever invoked once, from inside node_save() itself. In the context of a node add/edit form it's called by the original form submit handler, which unless you've explicitly engineered otherwise, will be run before the call to your custom submit handler.
Similar to your other question the submit handler isn't really the best place for this logic, as that code will literally only run when a form has been submitted (not when a node has been added programmatically for example).
After node_save() has saved the node data to the database, it invokes one of two other node hooks...hook_node_insert() and hook_entity_update() (obviously depending on the current operation).
One of those hooks will be called after the data has been committed to the db so will be perfect for your needs.
Comment: All the form values are dumped onto the node object, so if there's a form field called `$form['my_field']`, you'll have access to `$node->my_field` in the presave hook
Comment: hmm.. ok I'll move my code to the hook_node_presave(), but one of the issues I was thinking about is how to access form data inside the hook ? as only $node is passed as an argument. Whereas in my custom submit function I can access it through $form_state['values'].
Comment: gr8 thanks a lot.. talking to u clears a lot of doubts.. thanks again, really appreciate it


How to model a probability distribution to phone call duration?

Question: I was plotting the phone call durations, and the result seems like a right-skewed histogram. Shape-wise,  Poisson, Raylegh, Chi-2 can be candidates for modeling that.
But is there a more rigorous way of modeling? Like a real-world intuition behind one of those options? In addition, how to tune the parameters to fit the curve? Do you know a tool for that? Should I use moments of the distribution?
Any suggestion is welcomed. I have attached the histogram.
Comment: What problem are you trying to solve and how does describing the distribution of phone call lengths with a small number of parameters help you solve it?
Comment: What is the purpose of estimating a probability distribution for this data?
Comment: @Sycorax I need to describe it with just a handful of parameters.
Comment: Is this data available to the public?
Comment: Looks to me like a lognormal distribution, possibly erlang. I would like to use this data as an illustration in a report I am writing. Would it be possible for me to have the original data please, so I can run it through my own charting and curve-fitting code. Due acknowledgement will be given of course.
Answer:
But is there a more rigorous way of modeling?

Visually comparing a theoretical distribution to an observed histogram is an important practice toward being rigorous in our inferences.

Like a real-world intuition behind one of those options?

This would require domain-specific knowledge about phone calls that perhaps I don't have. There are multiple distributions that appear similar to yours prima facie, and I do not know which specific theoretical distribution is 'best' according to my background information. But perhaps there isn't an available way to know other than to evaluate and compare models trained on the data. Some speculations I might have about the general shape:

Unimodality is suggesting there is no evidence here of clusters of phone calls.
Hypothesis: The tiny strip near zero might be those automatic calls along with the occassional "oh s**t I just dialed the wrong number" calls.
Most of the rest of the weight not being close to zero even on the left-side of the mode might be suggestive that for most calls there is a minimum length that is useful to humans for verbally getting information across.
The right skew suggests that occasional calls go much longer than the typical call length. For me these longer calls are catching up with old friends that I don't see often, but it could be for other reasons in general.
Sanity check: Phone calls should not have negative duration, and the histogram agrees with that constraint.

In addition, how to tune the parameters to fit the curve?

There are too many ways to summarize for how to fit the parameters of a distribution to data. The choices often depend on whether you are approaching this from a Bayesian or likelihood perspective. Let me mention two estimation techniques in these broad areas, though I cannot emphasize enough that this barely scratches the surface.

Maximum a posteriori estimation
Maximum likelihood estimation

Do you know a tool for that?

For the simple cases, which yours might be, I often use SciPy to fit distributions to data. By default it uses maximum likelihood estimation, but method of moments can be used by passing method="MM" into the fit method. You could use the code in this answer to train (all?) the available SciPy distributions on your data, but this seems wasteful (if not asking for spurious results).
Taking a more practical stance of training only specific distributions, let's consider how you can do this with the gamma distribution as an example.
from scipy.stats import gamma

data = <an array of your data goes here>

parameters = gamma.fit(data) # include `floc=0` if you don't want the location parameter.

A list of available statistical functions is found in this reference.
If SciPy doesn't have a distribution you are interested in, like if you wanted to construct mixture model, you can build your own using using scipy.stats.rv_continuous or scipy.stats.rv_discrete as base classes. See this Stack Overflow Q/A for an example.
In your case you can probably model you distribution as a mixture distribution between a Dirac delta distribution centered at zero with something like gamma distribution. SciPy's base class should work for that with some customized code, but for building custom mixtures I have become a fan of pymc.Mixture.

Should I use moments of the distribution?

If the best-fitting distribution has finite moments to some sufficiently large order, then you can use them to report typical moments such as the mean, variance, skewness and kurtosis. Eye-balling your histogram, my guess is that the mean and variance are finite, but there are methods for examining whether your distribution is fat-tailed. I believe videos 11-14 cover tails and their estimation in this (fairly good in my opinion) video series on quantitative risk management. Which moments you use, and how you use them, will depend on what you are trying to accomplish with the analysis.
Answer: Treating time as continuous, candidate distributions that come to mind are log-normal, gamma, and Weibull.  You can use a time-to-event regression package to fit various models and compare the AIC for which provides the best fit.  You can plot the Kaplan-Meier estimator of the survival function and overlay the fitted parametric curve.  If there is no censoring you could plot a histogram and overlay the fitted density.  It looks like there is a spike at time=0.  You could model only the non-zero times or try a finite mixture model that includes 0.
Answer: It is usually a bad idea to fit a probability density function, bot in the least because the shape and the results would be very sensitive to the choice of the bin size.
Robust and simple options for comparing empirical distribution with parametric ones include QQ-plot (mostly to get the intuitive idea) and the Kolmiogorov-Smirnov test (both based on comparing cdf rather than the pdf.)
Answer: From a practical point of view, whether a proposed calculation or test or assumption makes sense depends on the purpose. What are you going to do with the distribution once you have fitted it? If you want to use the distribution as input to simulation, then you could just use the empirical model. If you want to input the distribution to a queueing-theory model then some thought has to be given to the actions that might be taken based on the results. Some queueing-theory results are not particularly sensitive to service-time distribution, and call-center planning has to contend with forecasting error and agent attendance variability as well. If you want to apply queueing-theory, as opposed to simulation, then the question is not "what is the best-fit distribution", it is "what is the best fit of the distributions that are mathematically tractable", which may steer you to Erlang, mixed-Erland, Gamma, or LogNormal. Gamma-family is attractive mathematically, lognormal is often a good fit. Plus, "how much does the fitted or assumed distribution affect resulting management decisions?".


Some confusion in differentiation

Question: $$f(x) =
\begin{cases}
x^2\cos\left(\frac{1}{x^2}\right),  & \text{if }x \neq 0 \\
0, & \text{if }x=0
\end{cases}$$
1) Compute $f'(0)$.
2) Is $f'(x)$ a continuous function? Justify the answer.
I am quite confused on this. How should I do?
Comment: For evaluating $f'(0)$, you may want to use the First Principle. For $x\neq 0$, simply evaluate $f'(x)$ as you might normally.
Answer: To compute $f'(0)$, you won't be able to simply compute $f'(x)$ from the non-zero formula, and then plug in $0$, or even take a limit as $x\to 0$. (Doing that would be assuming the derivative is continuous.) Instead, you have to go back to the definition of a derivative at a point.
$$f'(0)=\lim_{h\to 0}\frac{f(h)-f(0)}{h}$$
This limit can be calculated, because we know that $f(0)=0$, so it simplifies to:
$$\lim_{h\to 0}\frac{h^2\cos\left(\frac{1}{h^2}\right)}{h}=\lim_{h\to 0} h\cos\left(\frac{1}{h^2}\right)$$
This expression inside the last limit is bounded between $h$ and $-h$ as $h\to 0$, so we can evaluate its limit by the Squeeze Theorem.
That takes care of $f'(0)$. To address the continuity of $f'$, you can apply differentiation rules to find $f'(x)$ when $x\ne 0$, and then see whether the limit of the resulting expression exists, and matches your answer from the first part.
Comment: it helps a lot. Thank you very much!!

Some confusion in differentiation


Proving the sum rule of probability limits

Question: I'm trying to show that if $X_n$ converges in probability to 0 and $Y_n$ converges in probability to 0, then $X_n+Y_n$ converges in probability to $0$, ie the sum rule for probability limits.
What I'm trying to do is to show it directly using $\epsilon, \delta$ arguments as opposed to appealing to the CMT, to improve my understanding of convergence. But I get stuck almost immediately because I don't know how I can use bounds for the probability each sequence exceeds some value to get a bound for the probability the sum exceeds some value...
Here's where I get stuck:
For every $\epsilon>0$ and every $\delta>0$ I have an $N$ s.t $n>N \implies P( |X_n|>\epsilon)<\delta$ and $P(|Y_n|>\epsilon)<\delta$. I also know that $|X_n+Y_n| \leq |X_n|+|Y_n|$ and that therefore $P( |X_n+Y_n|>\epsilon) \leq P( |X_n|+|Y_n| >\epsilon)$. Now it seems obvious that if $P( |X_n|>\epsilon)$ and $P(|Y_n|>\epsilon)$ can be made as small as we want, the RHS can be bounded, but I can't quite work out how. I can't seem to relate the probability of the sum to the probabilities I can bound.
Answer: You can argue like this.  If $\left| X_n \right| + \left| Y_n \right| > \epsilon$, then it must be the case that  $\left| X_n \right| > \frac{\epsilon}{2}$ or $\left| Y_n \right| > \frac{\epsilon}{2}$.  Because if both $\left| X_n \right|, \left| Y_n \right| \leq \frac{\epsilon}{2}$, then:
$$ \left| X_n \right| + \left| Y_n \right| \leq \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon $$
So now you can use the union bound
$$ Pr( \left| X_n \right| + \left| Y_n \right| > \epsilon ) \leq Pr \left( \left| X_n \right| > \frac{\epsilon}{2} \lor \left| Y_n \right| > \frac{\epsilon}{2} \right) \leq Pr \left( \left| X_n \right| > \frac{\epsilon}{2} \right) + Pr \left( \left| Y_n \right| > \frac{\epsilon}{2} \right) $$
which you can bound in terms of $\delta$.
Comment: Thanks! Learned something new about sums today, namely that they imply this very useful disjunction...:)


Meta-analysis based on cohort studies only

Question: I am planning a meta-analysis based on cohort studies only. There are dozens of papers reporting results of treatments A and B. But the treatments were never compared with each other. Besides, there is no common reference treatment C to allow performing network meta-analysis of A vs B vs C; to be exact, there are too many reference treatments.
Thus, I have to use the results on treatments A and B as the results of single-arm studies, just ignoring other arms in the previous studies.
The outcome is binary. What are available methods for such a meta-analysis? I have found some answers in Network Meta-Analysis: Single Arm vs Contrasts Strategy Pros and Cons , but that question is somewhat different.
So, what am I to use? Mixed effects logistic meta-regression? Is it necessary to account for baseline characteristics in those single-arm studies if I am going to incorporate, say, 50 papers into meta-analysis?
Comment: Hard to see any reason not to go ahead. As you say you may want to use any moderators you can find although with 50 studies you cannot use too many. Obviously it is not as good evidence as within study comparison but if such studies are not there you have limited options.
Answer: A mixed effects logistic regression (if the outcome is binary/binomial) is certainly one plausible approach that could deal with the situation that all studies were essentially identical, in identical populations and there's just a bit of random variation in what you'd have expected to happen on a control group (if one had been in included in all studies). It is even a coherent method for combining randomized and single-arm studies.
However, there's some big issues with doing such an analysis that is not solely based on randomized comparisons. You'd definitely want to account for

differences in study population (esp. those that might change the outcome you're looking at such as disease severity, background medications, age, baseline measurements related to disease state...) and
time period when studies were conducted (are outcomes for newer treatment just better because recently patient outcomes are just better due to better medical care, shifts over time in how early diseases get diagnosed) and
study design such as

inclusion criteria (if I enroll only those with a hypertension diagnosis and baseline blood pressure > 140 mmHg, I will get a larger within group change [for the same exact intervention] from baseline than if I recruit all with a hypertension diagnosis - the same if I look at achieving SBP <= 140)
treatment/study duration (if you turn the outcome into binary dead/not dead, then a longer study will just have a higher proportion of deaths)
allowed concomitant medications
outcome definitions/measurement methods...

Any one of these could otherwise due to the lack of randomized comparisons massively bias comparisons between single-arm outcomes (to the extent that they could make a completely ineffective intervention look better than a highly effective one). In a way, this might be a much worse scenario than an observational study, where you at least usually have a common data source with all data from the same time period and access to individual patient data (important confounders might still be unavailable).
Note that you don't need to account for just for the things you have data published for, but all the relevant things that might meaningfully matter. If you cannot get information on really important differences (or if some study design differences are completely confounded with evaluated intervention, e.g. because all studies for one intervention are old and all studies for a new intervention are new, and this leads to a complete confounding vs. substantially changed standard of care), you might just not be able to trust your analysis. If it's relatively few studies and a lot of potentially important differences between studies, one solution might be to set prior distribution in a Bayesian analysis (because you probably do have some a rough idea how much certain things could potentially change outcomes in what direction).
Answer: Do you have raw individual data with 0/1 responses in each study? If so, you can use each study as a group indicator in random intercepts and slopes in binary regression with mixed effects. If the studies have multiple measurements on each patient, you can also have two layers of nested random effects lme4::glmer(y ~ treatment * time + (1 | study/patient), family = binomial) or use conditional fixed-effect estimator such as survival::clogit in R. Baseline characteristics should be added as predictors even if treatment assignment was random because it will reduce the standard error of treatment effect. We should also add study design characteristics as predictors that can potentially affect the response and treatment effect, such as country, randomization, and screening. See an example meta-analysis Lehner, S., & Peer, S. (2019). The price elasticity of parking: A meta-analysis. Transportation Research Part A: Policy and Practice, 121, 177–191. https://doi.org/10.1016/j.tra.2019.01.014
If individual data are not available, it will be difficult to compare treatment efficacy. Binary regression coefficients from summary tables are not usable across different studies because they are standardized by an unknown factor that varies among different models. See Williams, R., & Jorgensen, A. (2023). Comparing logit & probit coefficients between nested models. Social Science Research, 109, 102802. https://doi.org/10.1016/j.ssresearch.2022.102802. We will need to translate model coefficients into average marginal effects on probability. This requires at least the variance-covariance matrix of model coefficients. Because logit and probit are nonlinear transformation, the effect of treatment on the event probability is also nonlinear in dosage and dependent on the value of other predictors. Thus, for binary regression models among different studies to be comparable, we need to state the effect in terms of the changes in event probability between treatment groups at specific values of other predictors (e.g., age, sex).
If only summary data are available, one feasible way is to model the collective response count as a binomial process where each study contributes two observations, one for Treatment A where event happens to n1 patients out of nA in the group and another for Treatment B where event happens to n2 patients out of nB in the group. If each patient was measured multiple times, more summary observations for each group should be added. This can still be modeled by a mixef-effects logit or probit model, such as lme4::glmer(cbind(case, total) ~ treatment + (1 | study), family = binomial).


how to find out if running inside KVM guest

Question: Is there a way to find out if OS(linux) is running inside KVM guest..
Comment: related: https://unix.stackexchange.com/questions/89714/easy-way-to-determine-virtualization-technology
Answer: Grep dmesg, there should be at least one line containing kvm. On my machines:
[    0.000000] kvm-clock: cpu 0, msr 0:5dd801, boot clock
[    0.000000] kvm-clock: cpu 0, msr 0:1023801, primary cpu clock

Alternativly check /proc/cpuinfo, it contains a line:
model name : QEMU Virtual CPU version 0.9.1

But, the problem is: You can't be sure you are an KVM guest (on top of QEMU) or only a QEMU-Guest.
Comment: You may want to add `dmidecode` to the list of ways that might show if you are running virtualized, it works well with VMWare.
Comment: kvm-clock clocksource might be not present or disabled for stability reasons.
Comment: The first worked for me but the second shows the regular intel model name
Answer: You can check if imvirt or virt-what which are available for several Linux distros, including Ubuntu, can help you.
Comment: In my experience `imvirt` is more accurate.
Answer: systemd-detect-virt

returns on this Ubuntu 18.04 KVM setup:
kvm

and on my host:
none

See also: https://unix.stackexchange.com/questions/89714/easy-way-to-determine-virtualization-technology
Tested on an Ubuntu 18.04 host.
Answer: Current versions of lscpu also show if a hypervisor is detected:
# lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    1
Socket(s):             2
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 23
Model name:            Intel Core 2 Duo P9xxx (Penryn Class Core 2)
Stepping:              3
CPU MHz:               2659.936
BogoMIPS:              5319.87
Hypervisor vendor:     KVM
Virtualization type:   full
...

Answer: Another possibility is dmidecode -s 'system-product-name'
[samveen@vm1 ~]$ sudo dmidecode -s 'system-product-name'
KVM

Comment: @CiroSantilli新疆改造中心六四事件法轮功 Please check the other DMI information fields as well. I dont have access to an Ubuntu based KVM host to test. In most cases, the`system-product-name` identifier gives the expected answer, even in cases like `VirtualBox` and `VMWare`.
Comment: Did not work with this Ubuntu 18.04 on Ubuntu 18.04 setup: https://askubuntu.com/revisions/1046792/15 , it just output: `Standard PC (i440FX + PIIX , 1996)`.


BeautifulSoup find_all Method not Generalising

Question: I'm a bit stuck on a problem with BeautifulSoup. This piece of code is a snippet from a function I'm trying to debug. The scraper worked fine and suddenly stopped. The strange thing is that the class I'm searching for "ipsColumn ipsColumn_fluid" is in the "post_soup" file that is produced in the second step of the loop.
As part of my debugging, I wanted to see what was produced which is the reason for the text file. However, it is empty. I have no idea why.
Any ideas?
post_pages = ['https://coffeeforums.co.uk/topic/4843-a-little-thank-you/', 'https://coffeeforums.co.uk/topic/58690-for-sale-area-rules-changes-important/']

for topic_url in post_pages:
    post_page = urlopen(topic_url)
    post_soup = BeautifulSoup(post_page, 'lxml')
    messy_posts = post_soup.find_all('div',  class_='ipsColumn ipsColumn_fluid')
    with open('messy_posts.txt', 'w') as f:
        f.write(str(messy_posts))

edit: you can swap in this variable to see how it should work. These websites are built on the same platform so the scrape should be the same (I would think):
post_pages = ['https://forum.cardealermagazine.co.uk/topic/8603-customer-comms-and-the-virus/', 'https://forum.cardealermagazine.co.uk/topic/10096-volvo-issue-heads-up/']

Comment: What is the expected output?
Comment: Try with css selectorr it will work because space it does not find desired outptut
Answer: The class_ takes a list for multiple classes and not a string for an OR operation. You could change it from
 class_='ipsColumn ipsColumn_fluid'

it to this and it should work.
class_=['ipsColumn', 'ipsColumn_fluid']

and it should work.
Alternatively, if you are going for an AND(where you want a div with both classes). I advise you to use select as such:
post_soup.select('div.ipsColumn.ipsColumn_fluid')

This would return the div that includes both classes
Comment: That is not true. `class_='ipsColumn ipsColumn_fluid'` is completely fine if OP wants to exactly match the string value of a HTML tag's class attribute. Your proposed change `class_=['ipsColumn', 'ipsColumn_fluid']` uses a logical OR filter, i.e. matches `class='ipsColumn'`, `class='ipsColumn_fluid'` or`class='ipsColumn ipsColumn_fluid`.


Factory for a View in MVVM

Question: There is an user control for ContextMenu which will be re-used in other user controls. The problem is the controls which would like to use this Contextmenu needs to create the ContextMenuViewModel and populate its DataContext which is the normal practice.
Is there a way to create a factory for the View so it will be created on the fly and not worried about its data context from the control which is consuming it?
Comment: I see you're in the mvvm world, does that include prism?  It gets real simple with prism, but is also doable with straight mvvm.
Comment: :) no it doesn't include prism.
Comment: Where do you want the context menu's data context to come from?
Comment: Context menu's data will be provided by the user control that uses this context menu
Comment: Would it be solved by using the control as a template?
Answer: You can use Locator pattern
Ex:
uses of a "Locator" such as:
DataContext="{Binding Main, Source={StaticResource Locator}}">

There is locators created in the application.
<Application x:Class="XXX.App"
             xmlns:views="clr-namespace:XXX.Views"
             xmlns:vm="clr-namespace:XXX.ViewModels"
             StartupUri="MainWindow.xaml"
             >
    <Application.Resources>
...
        <vm:ViewModelLocator x:Key="Locator"  />
...
    </Application.Resources>
</Application>

The class "Locator":
public class ViewModelLocator
{
   private static MainViewModel _main;

   /// Initializes a new instance of the ViewModelLocator class.

   public ViewModelLocator()
   {
      _main = new MainViewModel();
   }

  /// Gets the Main property which defines the main viewmodel.

  public MainViewModel Main
  {
     get
       {
       return _main;
       }
  }

}

Comment: Thanks for the answer let me verify this and get back to you :)
Comment: "ViewModel-Locator" is considered an anti-pattern because the lifetime of a ViewModel should match the View, not the length of the container - and because this approach doesn't support N-ary views (e.g. an MDI). Instead, a better example is demonstrated here https://stackoverflow.com/questions/50017579/wpf-mvvm-ioc-alternative-to-service-locator-pattern-need-dependency-in-view-c/50024624

Factory for a View in MVVM


Roots of factorization with expressions for constants

Question: When faced with the factorization $$(\alpha - 1 -\lambda)(\mu - 1 -\lambda)=0$$ the roots of $\lambda$ can simply be said to be $\alpha - 1$ and $\mu - 1$. Why is that answer different to the following working?
$$\begin{align*} \alpha\mu - \alpha - \alpha\lambda - \mu +1 + 2\lambda - \lambda\mu + \lambda^2 &=0 \\
\lambda^2 + (2-\alpha - \mu) \lambda + \alpha\mu - \alpha - \mu + 1 &=0
\end{align*}$$
$$\begin{align*}
\lambda &= \frac{\alpha + \mu - 2 \pm\sqrt{(2-\alpha-\mu)^2 - 4(\alpha\mu - \alpha -\mu + 1)}}2 \\
 &= \frac{\alpha + \mu - 2 \pm\sqrt{4 - 4\alpha -4\mu + \alpha^2 + 2\alpha\mu + \mu^2 - 4(\alpha\mu - \alpha -\mu + 1)}}2 \\
  &= \frac{\alpha + \mu - 2 \pm\sqrt{\alpha^2 - 2\alpha\mu + \mu^2}}2 \\
  &= \frac{\alpha + \mu - 2 \pm\sqrt{(\alpha - \mu)^2}}2\\
  &= \frac{-\alpha + 3\mu }2\qquad\text{or}\qquad \frac {3\alpha - \mu}2
\end{align*}$$
Comment: The problem is that the last line of your work, contains error
Comment: it seems you confused $2\pm\sqrt{(\alpha-\mu)^2}$ with $2\times\sqrt{(\alpha-\mu)^2}$, taking $\pm$ for a multiplicative sign, this explain the disappearing of constant term $-1$ and the factors $3$.
Comment: $(2-\alpha-\mu)^2=4-4(\alpha-\mu)+(\alpha-\mu)^2=4-4(\alpha-\mu)+\alpha^2-2\alpha\mu +\mu^2$, it is the sign in $\alpha\mu$
Answer: $$\lambda_{1,2}=\frac{\alpha+\mu-2\pm\sqrt{(\alpha-\mu)^2}}{2}=\frac{\alpha+\mu-2\pm(\alpha-\mu)}{2}\\ \implies\lambda_1=\frac{2\alpha-2}2=\alpha-1\\
\implies\lambda_2=\frac{2\mu-2}2=\mu-1$$
What seems to be the problem?  I cannot be sure how you ended up with the solutions that you did.
Comment: Oh, I was _multiplying_ 2 with $(\alpha - \mu)$. Thanks!


Easiest way to store Excel invoice data into SQL Server database?

Question: I want to link an invoice template in Excel to a SQL Server database.
The invoice currently contains only a few very basic fields like user/customer/date/item-id/description/quantity/Total etc.
In future more fields will be required.
What's the easiest way to store all that invoice data in realtime to a SQL Server database when the user presses enter in the invoice?
How many tables will I need to create in SQL Server?
The end users are not tech savvy at all, I need to deploy this solution without any technical requirements from them.
Thank you.
Answer: The best way to do this is to create an SSIS package that sucks up the excel spreadsheet and captures the data say once a day. The excel file will need to be in the same location, say a network folder and the structure will also have to be the same, meaning the columns and their names once setup will have to also be the same. Otherwise, it's best to have something like a web front end or a fat32 client (basically build an app in Visual Studio or something) that allows data input directory to the SQL server.
Check out this link to learn about it:
http://knowlton-group.com/using-ssis-to-export-data-to-excel/


Executable exiting preemptively when ranging over an empty channel

Question: I recently encountered a coding exercise which I solved in python in which I had to port an "algorithm". I don't know how it is called which is why I am describing it:
Each new line was a description of the previous line by the amount of the same number printed in sequence and the associated number.
Here is an example:
1
11
21
1211
111221
312211
etc

I started learning Go with its channels and concurrency features. So I came back to this exercise to try to solve it more efficiently in parallel with Go.
This is what I got so far:
package main

func main() {
    channel := make(chan uint8)
    go treeCalcRoutine(channel, 0)
    channel <- 1
    close(channel) //defer is not an option in this case because the channel has
    //to be closed before main exits
}

func treeCalcRoutine(in <-chan uint8, generation int) {
    if generation > 10 {
        return // return after 10 recursive iterations
    }
    out := make(chan uint8)
    defer close(out)
    num := uint8(1)
    previous := <-i
    go treeCalcRoutine(out, generation+1)
    for val := range in {
        switch {
        case val == previous:
            num++
        default:
            num = uint8(1)
            out <- num
            out <- val
        }
        previous = val
    }
    out <- num
    out <- previous
}

While trying to debug the program using Delve, I figured out the Program quits without an exception (and exit status 0) while trying to range over an empty/closed channel. I expected the program just to skip the for loop altogether in this case.
I still want to solve this challenge myself so I would appreciate if someone could just point me in the right direction instead of producing a functioning solution. Moreover, please point out any other issues/cases which could be done better (like the generation limit).
EDIT:
Since people asking me to post the error: There is no error at all for some reason. The program just exits once it reaches the for loop.
Comment: Please post the actual error and the line triggering it. There is no error for "ranging over an empty channel" - it just waits until there is something to receive.
Comment: Why could `close(channel)` as the last statement in `main` do anything? I think you have some fundamental misunderstanding about channels.
Comment: @Swiftb0y no that's not it. Closing channel will close the channel in that case you cannot send more value on the channel if it is closed, compiler will throw an error saying cannot send value on closed channel.
Comment: @Swiftb0y: closing the channel will cause a for range loop to exit, but at the end of `main` the program is exiting, so it doesn't really matter.
Comment: @JimB As far as i know, the `for range` loop would never stop looping unless the channel gets closed.
Comment: @Himanshu yes, it does that primarily but as https://gobyexample.com/range-over-channels suggests it will terminate the for loop as well.
Comment: @Swiftb0y yes it does will close the for loop. But better is to check if there is a value in the channel using switch with `ok`. If it has then flush it on the receiver end. But even if you do not close the channel if does not effect your code. One more thing where are you printing your values in the function to check if your code is going correct.
Comment: It still doesn't matter. Closing at the end of `main` is superfluous. When `main` returns, the program exits. No channels/goroutines/anything else will survive.
Comment: Ohhh I think I know what the issue is: The Program is quiting because once the for loop is done, the main routine is done as well and it will kill all the other goroutines as well. So really the question is how I can prevent the main routine from exiting until the first if clause evaluates to true. Is this assumption correct?
Comment: @Himanshu The compiler does not detect send on a closed channel.  Perhaps you meant to say that send on a closed channel panics.
Comment: @Swiftb0y somehow the assumption is not upto the mark because the go routine will run on a thread. Main will exit because it is not waiting for the go routine to finish
Comment: @ThunderCat yes I mean to say that it will panic if we try to send on a closed channel.
Comment: Ok. I understand the issue now. But how can I prevent the main routine from exiting until the routines finished?
Comment: @Swiftb0y use `wait groups` it will wait for all the go routines to finish.
Comment: Ok thank you very much.
Answer: So the issue was not actually that the for loop was exiting when it was encountering the closed channel but the main routine exited at that exact time which caused every other goroutine to terminate as well. I was advised to use waitgroups in this case.


Retornando valor do select com javascript/jquery

Question: Estou desenvolvendo um software e preciso saber qual a opção o usuário selecionou e retornar no console.log, porém já tentei várias funções  e nenhuma funcionou. Como eu faço para conseguir esse retorno?

    function verificar() {

        //  aqui seria a função que reconhece o select escolhido e retorna um console.log
    }

    function habilitarColchao() {

        var radios = document.getElementsByName("colchao[]");
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].checked) {
                var checked_value = radios[i].value;
                if (checked_value == 'colchao[]' || checked_value == 'tempo') {
                    document.getElementById('proximo').disabled = true;
                    document.getElementsByName('tempo-colchao')[i].disabled = true;
                } else {
                    document.getElementById('proximo').disabled = false;
                    document.getElementsByName('tempo-colchao')[i].disabled = false;
                    document.getElementById('proximo').style.cursor = "pointer";
                }
                break;
            }

        }
    }
<!DOCTYPE html>

    <title>Quiz - Dr. Lava Tudo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link rel="stylesheet" href="css/main.css">

    colchão

    <form class="form-inline">

            <input type="checkbox" class="custom-control-input" name="colchao[]" value="2" onclick="habilitarColchao()">

        <select class="custom-select" id="colchao" name="tempo-colchao" disabled="disabled">
            <option selected hidden>Selecione</option>
            <option value="colchao-1">Menos de 6 meses</option>
            <option value="colchao-2">De 6 meses a 2 anos</option>
            <option value="colchao-3">Mais de 2 anos</option>
        </select>
    </form>
    <button type="submit" onclick="verificar()" class="btn btn-block calcular" id="proximo" disabled="disabled">calcular</button>

Comment: O valor so select? Tentou `document.getElementById('colchao').value`?
Comment: eu estava tentando um `if (document.getElementById('colchao-1').selected == true) { console.log("colchão selecionado - menos de 6 meses"); }` @bfavaretto
Answer: Fácil, só pegar a opção selecionada através ID > option > selected Utilizando o Jquery que você já tem importado no seu projeto:
$("#colchao option:selected").each(function() {
    console.log($(this).val()); // valor
    console.log($(this).text()); // texto
});

Segue o exemplo:

function verificar() {

  $("#colchao option:selected").each(function() {
    console.log($(this).val()); // valor
    console.log($(this).text()); // texto
  });
}

function habilitarColchao() {

  var radios = document.getElementsByName("colchao[]");
  for (var i = 0; i < radios.length; i++) {
    if (radios[i].checked) {
      var checked_value = radios[i].value;
      if (checked_value == 'colchao[]' || checked_value == 'tempo') {
        document.getElementById('proximo').disabled = true;
        document.getElementsByName('tempo-colchao')[i].disabled = true;
      } else {
        document.getElementById('proximo').disabled = false;
        document.getElementsByName('tempo-colchao')[i].disabled = false;
        document.getElementById('proximo').style.cursor = "pointer";
      }
      break;
    }

  }
}
<!DOCTYPE html>

  <title>Quiz - Dr. Lava Tudo</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <link rel="stylesheet" href="css/main.css">

  colchão

  <form class="form-inline">

            <input type="checkbox" class="custom-control-input" name="colchao[]" value="2" onclick="habilitarColchao()">

    <select class="custom-select" id="colchao" name="tempo-colchao" disabled="disabled">
            <option selected hidden>Selecione</option>
            <option value="colchao-1">Menos de 6 meses</option>
            <option value="colchao-2">De 6 meses a 2 anos</option>
            <option value="colchao-3">Mais de 2 anos</option>
        </select>
  </form>
  <button type="submit" onclick="verificar()" class="btn btn-block calcular" id="proximo" disabled="disabled">calcular</button>

Referencia direto da página do Jquery(recomendo mt consultar lá antes de perguntar, agiliza sua vida) : https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
Comment: obrigado!!! vou conferir sempre essa página!
Comment: @JoaoPedro se resolveu por favor, marcar como resposta correta !
Answer: Com JavaScript puro
var index = document.getElementById("mySelect").selectedIndex;
var value = document.getElementsByTagName("option")[index].value;

Caso queira retornar o value do option selecionado
var index = document.getElementById("mySelect").selectedIndex;
console.log(document.getElementsByTagName("option")[index].value);

Caso você queira retornar o value de cada option
var allOption = document.querySelector("#mySelect").children;
for (var i = 0; i < allOption.length; i++) {
        console.log(allOption[i].getAttribute("value"));
    }


lightweight access point?

Question: Im moving from an all in one to a router + access point. In doing googling and reasearch and talking to friends I ended up with

router - cisco rv016
wifi access point - airnet 1142 lightweight access point. (lap1142n)

In trying to set all this up and reading I think I bought the wrong access point. It seems I need a wireless controller? Can someone confirm that I should not have bought the lightweight one?
Comment: Without saying what you were trying to achieve, I wouldn't think anyone will be able to say what choice you should have made.
Answer: You need a Cisco Wireless LAN Controller to configure and deploy a LAP. They don't run full-blown iOS, but rather a slimmed down OS that only boots the radios and physical interfaces and then "calls out" to a controller for the remainder of their configuration.
You can purchase autonomous (stand-alone) 1142s, Their part/model number is just AP1142. Anything that starts with LAP is a Lightweight Access Point and requires a controller.

tl;dr - You bought the wrong thing.
Comment: It's a PITA and doesn't always work as advertised. I recently converted about 200 standalone APs to lightweight (so the other direction) and ended up ~188 that were fine and about a dozen bricks that had to be sent back to Cisco. Just return what you ordered and get what you need right from the bat.
Comment: so If I plan to add another later, am I better off buying a controller? Or just return this and get a non lightweight one?
Comment: That's a tough question. Adding just one more? Probably not worth investing in a controller (they can be spendy). If you're planning on growing to 3, 4, 5 APs, then a controller starts to make sense. Especially if you want to ever use NCS to do usage heatmaps, interference mapping, etc.
Comment: also looks like you can convert it to a regular autonomous ap using software https://supportforums.cisco.com/docs/DOC-14960 any thoughts on that?

lightweight access point?


Dúvida ao gerar um arquivo .doc com C#

Question: O método abaixo faz o download do documento que é gerado dinamicamente, porém quando o arquivo é aberto mostra uma opção de conversão de arquivo,
deixando marcado por default o item Unicode(UTF-8).
O que fazer para não mostrar essa mensagem?
    public static void gerarRelatorioAtoDoc(string texto)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.ContentType = "application/msword";

        String strNomeArquiv = "RelAtoGerado" + DateTime.Now.ToShortDateString().ToString() + ".doc";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strNomeArquiv);

        StringBuilder strHTMLContent = new StringBuilder();
        strHTMLContent.Append(texto);
        HttpContext.Current.Response.Write(strHTMLContent);
        HttpContext.Current.Response.End();
        HttpContext.Current.Response.Flush();
    }

Comment: O que tem em texto? Aliás, qual o impedimento de usar uma biblioteca que gere um documento formatado?
Comment: [Falo de alguma coisa tipo isso aqui](http://www.codeproject.com/Articles/660478/Csharp-Create-and-Manipulate-Word-Documents-Progra). Seu esquema funciona, mas vejo ele mais como um improviso. Fica mais difícil formatar o documento desta forma.
Comment: Certo vou pegar essa biblioteca e implementar aqui, pra ver como se comporta.
Comment: eu passo um parametro pro metodo, texto pode ser qualquer coisa, no caso ai se trata de um comunicado vindo de um
Comment: e qual seria a biblioteca em questão, que gera o documento?
Comment: ele tem uma procedimento que salva em um diretorio específico, tanto que nao consigo apontar pra um diretório existente em meu drive; mas pelo que parece ser é bem simples e útil. vou testar em casa. mesmo assim muito obrigado man!
Answer: Com a ajuda de cigano-morrison-mendez e usando a biblioteca DocX v184.108.40.206 solucionei o problema da seguinte maneira:
    public static void gerarRelatorioAtoDoc(string texto)
    {
        string fileName = @"C:\Users\seu-nome\DocXExample.docx";
        var doc = DocX.Create(fileName, DocumentTypes.Document);
        doc.InsertParagraph(texto);
        doc.Save();
        Process.Start("WINWORD.EXE", fileName);
    }

O parâmetro texto pode ser qualquer coisa, no caso acima ele recebe o conteúdo de um Textbox.

Dúvida ao gerar um arquivo .doc com C#


Using pure JavaScript trying to change the default option of select box, but having an uncaught TypeError: Cannot read property '0' of undefined

Question: Using vanilla JavaScript I am trying to change the default option of a select box.
var temp = "Approve";
var mySelect = document.querySelector('[id^="select_leave_action_"]').id;

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}

When I execute the above code I get the following error:

Uncaught TypeError: Cannot read property '0' of undefined at :4:39`

What is wrong with my code?
I tried to use getElementsByClassName instead of querySelector, but still have the same problem.
Answer: Remove .id.
The ID is a string and won't have an options property. You want to store the select element itself (not its ID) to access its options.
(Also it's even simpler to just set mySelect.value = temp, the only difference to your current method will be how the case is handled where temp is not existing in the options that exist. Depending on the browser, setting the value directly may display the box empty if no fitting option exists.)
Comment: Additionally, you could just do `mySelect.value = temp;` instead of that loop.
Comment: Yes. There is a small difference though. I added it to the answer.


Mostrar a maior média dentre todas as médias calculadas

Question: Criei um algoritmo para calcular a média de um surfista, mas ele pode pegar quantas ondar quiser se ele quiser parar o algoritmo tem que apresentar a maior média dessas calculadas e passar para o segundo surfista. Alguém sabe como eu conserto isso?
import java.util.Scanner;
public class trabalhosurf {
  public static void main(String[]args) {
   int cod;
   double juiz1,juiz2,juiz3,juiz4,juiz5,soma,media1,media2,menor,maior,surfista1,surfista2,mediafinal1,mediafinal2;
   Scanner ler=new Scanner(System.in);
   do {

       System.out.println("Informe a nota do juiz 1 para o surfista 1");
    juiz1 = ler.nextDouble();
    menor = juiz1;
    maior = juiz1;
    System.out.println("Informe a nota do juiz 2 para o surfista 1");
    juiz2 = ler.nextDouble();
    if (juiz2<menor) {
     menor = juiz2;
     if (juiz2>maior) {
     maior=juiz2;
     }
    }
    System.out.println("Informe a nota do juiz 3 para o surfista 1");
    juiz3 = ler.nextDouble();
    if (juiz3<menor) {
     menor=juiz3;
     if(juiz3>maior) {
     maior=juiz3;
     }
    }
    System.out.println("Informe a nota do juiz 4 para o surfista 1");
    juiz4 = ler.nextDouble();
    if (juiz4<menor) {
      menor=juiz4;
      if (juiz4>maior) {
      maior=juiz4;
      }
    }
    System.out.println("Informe a nota do juiz 5 para o surfista 1");
    juiz5 = ler.nextDouble();
    if (juiz5<menor) {
     menor=juiz5;
     if (juiz5>maior) {
     maior=juiz5;
    }
    }
    soma = juiz1+juiz2+juiz3+juiz4+juiz5 - menor - maior;
    media1= soma/3;
    mediafinal1=media1;
    if
    (mediafinal1>media1);{
    mediafinal1=media1;
    }
    System.out.println("Media da onda do surfista 1 :"+ mediafinal1);
    System.out.println("Deseja repetir o calculo da media do surfista 1?");
    System.out.println("1)sim");
    System.out.println("2)nao");
    cod=ler.nextInt();

   }while(cod!=2);
   System.out.println("Nota final do sufista 1 é " + mediafinal1 );
    int codl;

    do {
       System.out.println("Informe a nota do juiz 1 para o surfista 2");
    juiz1 = ler.nextDouble();
    menor = juiz1;
    maior = juiz1;
    System.out.println("Informe a nota do juiz 2 para o surfista 2");
    juiz2 = ler.nextDouble();
    if (juiz2<menor) {
     menor = juiz2;
     if (juiz2>maior) {
     maior=juiz2;
     }
    }
    System.out.println("Informe a nota do juiz 3 para o surfista 2");
    juiz3 = ler.nextDouble();
    if (juiz3<menor) {
     menor=juiz3;
     if(juiz3>maior) {
     maior=juiz3;
     }
    }
    System.out.println("Informe a nota do juiz 4 para o surfista 2");
    juiz4 = ler.nextDouble();
    if (juiz4<menor) {
      menor=juiz4;
      if (juiz4>maior) {
      maior=juiz4;
      }
    }
    System.out.println("Informe a nota do juiz 5 para o surfista 2");
    juiz5 = ler.nextDouble();
    if (juiz5<menor) {
     menor=juiz5;
     if (juiz5>maior) {
     maior=juiz5;
    }
    }
    soma = juiz1+juiz2+juiz3+juiz4+juiz5 - menor - maior;
    media2 = (soma)/3;
    System.out.println("Media da onda do surfista 2 :"+ media2);
    System.out.println("Deseja calcular uma nova media para o surfista 2 ?");
    System.out.println("1)sim");
    System.out.println("2)nao");
    System.out.println("Nota final do sufista 2 é " + media2 );
    codl=ler.nextInt();
   }while(codl!=2);
    double campeao;

    {
    if (media1>media2) {
   campeao=media1;
   System.out.println("O vencedor é surfista 1 com nota: "+ campeao);
    }else if (media1<media2){
   campeao=media2;
   System.out.println("O vencedor é surfista 2 com nota: "+ campeao);
    }else if(media1==media2){
     System.out.println("empatados");
    }

  }

 }
}

Comment: Consertar o que?
Answer: O seu principal problema é isso:
if (juiz3<menor) {
 menor=juiz3;
 if(juiz3>maior) {
 maior=juiz3;
 }
}

O que você queria é isso:
if (juiz3 < menor) {
    menor = juiz3;
}
if (juiz3 > maior) {
    maior = juiz3;
}

Ou seja, era para colocar um if depois do outro, e não um dentro do outro.
O seu código tem um monte de duplicações, o que é muito ruim. Veja o código abaixo que as elimina. Os comentários explicam o que o código faz:
import java.util.Scanner;

public class TrabalhoSurf {

    public static void main(String[] args) {

        Scanner ler = new Scanner(System.in);
        int numeroJuizes = 5;
        int numeroSurfistas = 2;

        // Faz tudo isso uma vez para cada surfista.
        for (int surfista = 1; surfista <= numeroSurfistas; surfista++) {

            // Faz quantas vezes forem necessárias enquanto o usuário quiser repetir o cálculo da nota deste surfista.
            s: while (true) {

                // Utilizado para armazenar as notas dos juízes.
                double[] notas = new double[numeroJuizes];

                // Lê as notas dos juízes.
                for (int juiz = 1; juiz <= numeroJuizes; juiz++) {
                    System.out.println("Informe a nota do juiz " + juiz + " para o surfista " + surfista + ".");
                    notas[juiz - 1] = Double.parseDouble(ler.nextLine());
                }

                // Obtém a maior e a menor nota e também a soma das notas.
                double maior = notas[0];
                double menor = notas[0];
                double soma = notas[0];
                for (int juiz = 2; juiz <= numeroJuizes; juiz++) {
                     double nota = notas[juiz - 1];
                     if (nota > maior) maior = nota;
                     if (nota < menor) menor = nota;
                     soma += nota;
                }

                // Calcula a média, descartando a maior e a menor nota.
                double media = (soma - maior - menor) / (numeroJuizes - 2);

                // Mostra a média.
                System.out.println("Media da onda do surfista " + surfista + ": " + media);

                // Prende o usuário num loop até o usuário responder 1 ou 2.
                while (true) {
                    System.out.println("Deseja repetir o calculo da media do surfista " + surfista + "?");
                    System.out.println("1) Sim");
                    System.out.println("2) Nao");

                    // Lê a opção escolhida pelo usuário.
                    String escolha = ler.readLine();

                    if ("1".equals(escolha)) continue s; // Refaz com o mesmo surfista.
                    if ("2".equals(escolha)) break s; // Vai para o próximo surfista, se houver.

                    // Mostra a mensagem de erro. O while garante que o programa insiste.
                    System.out.println("Desculpe, não entendi a sua escolha. Tente novamente.");
                }
            }
        }
    }
}

Enfim, o segredo é você sempre procurar eliminar código copiado-e-colado. Use arrays para guardar sequências de números que tenham algum significado ao invés de criam um monte de variáveis de propósito parecido.
Answer: Se bem entendi o q vc quer é só criar uma variável lá double maior_media dai atribui:
if(media > maior_media) maior_media = media;

Imprime este quando necessário e lembre de zerar a variável antes da próxima interação.


First difference or seasonal difference in VAR/VECM

Question: I have monthly data on house price, rental price, wage index and interest rates. I want to use VAR to produce impulse response function.
Is there any reason why I should use first difference, x(t)/x(t-1) - 1 instead of e.g. x(t)/x(t-12) - 1 for montly time series?
Answer: The question is quite specific, but an answer can be based on general principles. If the data generating process happens to be better approximated* by an integrated VAR model than by a seasonally-integrated VAR model, your may be better of with the former when forecasting.
When could this be the case? Whenever your time series are not seasonally integrated but vanilla-integrated. (Note that seasonal integration is just a special case of seasonality.) Tests of seasonal integration and vanilla-integration as well as macroeconomic theory can help you decide on that.
You may also need to consider (seasonal or vanilla) cointegration to account for possible long-term equilibrium relationships. VECM could be used instead of VAR then. Again, statistical tests and macroeconomic theory can be of help.

*Considering (1) the true vs. modeled functional form and (2) estimation accuracy. According to Shmueli "To Explain or to Predict", (2010)), when interested in explanation, you may care more about getting the functional form right and less about estimation accuracy. Meanwhile, if your interest is in forecasting (I see you have added the forecasting tag), both functional form and estimation accuracy matter as per bias-variance decomposition.


Correct Path To Castle Riddle

Question: I'm working on the following riddle that I found to be kind of interesting, but I can't figure it out. The problem is as follows:

A prince visits an island inhabited by two tribes. Members of one tribe always tell the truth, and members of the other tribe always lie.
The prince comes to a fork in the road. He needs to know which road leads to the castle so as to avoid the fire-breathing dragon and rescue the princess from the wizard holding her captive in the castle.
Standing at this fork in the road is a member of a tribe who has time to answer only one yes or no question, but the prince can't tell which tribe he belongs to. What question should he ask to find the road to the castle?

Is there a way to solve this problem without involving another member of a tribe. I believe there is an easy solution to this problem if you have more than one member of a tribe to ask, but can this be solved if you only have one member to ask?
Comment: See my answer to similar question at: http://math.stackexchange.com/questions/179968/what-is-the-name-of-the-logical-puzzle-where-one-always-lies-and-another-always/184907#184907
Answer: Point along one of the two roads and ask: 'If I were to ask you whether this is the road to the castle, would you say yes?'
If you work out the possibilities, you'll see that the indicated road is the road to the castle if and only if the speaker says yes. For instance, suppose that it's the right road, and the speaker is a liar. Then his answer to the question 'Is this the road to the castle?' would be no, since he lies; but being a liar, he lies about his answer and says yes to the actual question.

Correct Path To Castle Riddle


Dependency injection in WebApiConfig class

Question: Can I Inject an instance of a class using Ninject in WebApiConfig class of a Asp.net Web Api project?
This is my attempt
    public static class WebApiConfig
    {
        private static IAccountsService _accountsService;

        [Inject]
        public static IAccountsService AccountsService
        {
            get { return _accountsService; }
            set { _accountsService = value; }
        }

        public static void Register(HttpConfiguration config)
        {
            var authentication = CreateAuthenticationConfiguration();
            config.MessageHandlers.Add(new AuthenticationHandler(authentication));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.EnableSystemDiagnosticsTracing();
        }

        private static AuthenticationConfiguration CreateAuthenticationConfiguration()
        {
            var authentication = new AuthenticationConfiguration
            {
                RequireSsl = false,
                EnableSessionToken = true
            };

            // Basic Authentication
            authentication.AddBasicAuthentication(AccountsService.ValidateAccountUsingSiteCredential);

            return authentication;
        }
    }

However, I am getting Object reference not set to an instance of an object on this line authentication.AddBasicAuthentication(AccountsService.Validate);
Answer: We are using something similar to the following in our global.asax to inject dependencies.
DependencyResolver.Current.GetService<WebApiConfig>()
     .Register(GlobalConfiguration.Configuration);

Edit: Forgot to mention that our WebApiConfig class is not static.
Comment: Also, instead of setter injection I did constructor injection.
Comment: I added that to `Application_Start` and removed static from the  class and the methods in `WebApiConfig`. Now, ninject seems to be working now. But the Web Api routes don't seem to be registering at all. I am getting `404` for everything. Do we have do anything else for the routes?
Comment: I had to add `DependencyResolver.Current.GetService().Register(GlobalConfiguration.Configuration);` to the top of `Application_Start`, that fixed routing.
Answer: Couple of things which could help you
1) Use the Ninject.Web.Common package which runs the following methods
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]
As you can see PreApplicationStartMethod runs before AppStart and when you add the "Ninject.Web.Common", there will be a guide on how you need to WireUp your Services.
2) I usually prefer to Implement an Interface called INeedInitialization which has a method call Initialize(IKernel ninjectKernel)
This way I can dynamically locate all implementations at run-time and pass the instance of Ninject's StandardKernel and perform the Binding in a plug and play manner.
3) Expose the IKernal instance from the NinjectWebCommon as "KernelInstance"
after all modules have been loaded
4) You can use the following to Bind "YourMessageHandler" to itself
kernel.Bind().ToSelf().InSingletonScope() in one of your implementations of "INeedInitialization" or wherever you have your Binding logic.
All dependencies can be injected via constructor injection in .
5) Register "YourMessageHandler" handler like this config.MessageHandlers.Add(NinjectWebCommon.KernelInstance.Get<YourMessageHandler>());
6) Fire up your application and let NInject do its magic


solving a system with homogeneous coordinates

Question: I have an equation  $$\boldsymbol{r - Pr_P} = (\boldsymbol{Qr_Q - Pr_P})t$$
where, $$\boldsymbol{P} = \begin{bmatrix}1&0&0&0\\0&1&0&0\\0&0&1&z_P\\0&0&0&1\end{bmatrix}\begin{bmatrix}cos\phi&0&sin\phi&0\\0&1&0&0\\-sin\phi&0&cos\phi&0\\0&0&0&1\end{bmatrix}$$
$$\boldsymbol{Q} = \begin{bmatrix}1&0&0&0\\0&1&0&0\\0&0&1&z_Q\\0&0&0&1\end{bmatrix}$$
$$\boldsymbol{r} = \begin{bmatrix}x\\y\\z\\1\end{bmatrix}, \boldsymbol{r_P} = \begin{bmatrix}\chi\\\psi\\0\\1\end{bmatrix}, \boldsymbol{r_Q} = \begin{bmatrix}a\\b\\0\\1\end{bmatrix} $$
I am trying to solve for $a$ and $b$ by eliminating $t$ but, what I get as an answer is different from the correct answer given, which is $$a\:=\:x\:+\:\frac{\left(z\:-\:z_Q\right)\left(x\:-\:\chi \right)}{z_{P\:}-\:z\:+\:\chi tan\phi }$$,  $$b\:=\:y\:+\:\frac{\left(z\:-\:z_Q\right)\left(y\:-\:\psi \right)}{z_{P\:}-\:z\:+\:\chi tan\phi }$$
The problem is in my computation (provided the answer is truly correct) but I am unable to figure out where. For example, what I get as $a$ and $b$ are:
$$a=\frac{xz_Q\:-z_Q\chi cos\phi \:-\:xz\:+z\chi cos\phi }{z\:-\:z_P\:+\:\chi sin\phi }$$
$$b\:=y+\:\frac{\left(y\:-\psi \right)\left(z\:-\:z_Q\right)}{z_P\:-z\:+\:\chi sin\phi }$$
Answer: I got
$$a=x+\frac{(\chi \cos(\phi)-x)(z - z_Q)}{z - z_{P} + \chi \sin(\phi)}$$
and
$$b=y+\frac{(\psi-y)(z - z_Q)}{z - z_P + \chi \sin(\phi)}$$
apparently, there is something wrong with your allegedly correct solution.


How to find the function from fixed points?

Question: A fixed point of a function $f$ is a number $t$ where $f(t)=t$. Geometrically, this means that the graph of $f$ crosses the line $y=x$ at the point $x=t$. Similarly, the graphs of $f\circ f$ and $f\circ f\circ f$ etc. also across the line $y=x$ when $x=t$.
How do we conclude linear functions at most can have one fixed point (with the exception of $f(x)=x$) while quadratics have at most two?
I have plotted an example in the case $f(x)=x^2-2$:
Comment: I am saying a maximum of one (with the exception of f(x)=x). It can be 0.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: By definition, $f:\mathbb R\to\mathbb R$ has a fixed point at $t$ if and only if $f(t)=t$. If $f$ is a linear function, i.e. $f(x)=ax+b$, then finding the fixed points of $f$ amounts to solving the equation $at+b=t$ for $t$. This equation is equivalent to $(a-1)t=-b$. This in turn is equivalent to $a-1=b=0$ (which corresponds to the case where $f(x)\equiv x$) or $t=-b/(a-1)$  (which is the unique solution if $f(x)\not\equiv x$).
Comment: $f(x)=x+1$ is a linear function and doesn't have one fixed point.
Comment: $f(x)=x$ is a linear function and has an infinity of fixed points.
Comment: Are you sure that $f(x)=x$ is the only exception?
Comment: Yes. Feel free to disprove :)
Comment: @bsd-boo: I have edited your question for MathJax, and to increase clarity. Hopefully the improvements will prevent it from being closed.
Comment: @bsd-boo: Your graph has a small error in it: $-2$ is not a fixed point of $f(x)=x^2-2$, since $(-2)^2-2$ equals $2$, not $-2$.
Answer: If $f(x) = ax + b$ is linear function, then equation $f(x) = x$ can be rearranged to
$$ ax + b = x \iff (a - 1)x = -b.$$
If $a\neq 1$, then we have unique solution $x = \frac b{1-a}$, while when $a = 1$ we either have infinitely many solutions when $b = 0$ (exception mentioned in the comments) to equation $0x = 0$ or no solutions when $b \neq 0$ to equation $0x = -b$.
When $f(x)$ is polynomial of degree $n \geq 2$, then
equation $f(x) = a_n x^n + a_{n-1}x^{n-1} + \ldots + a_1 x + a_0 = x$ where $a_n \neq 0$ can be rearranged to
$$
a_n x^n + a_{n-1}x^{n-1} + \ldots + a_2 x^2 + (a_1-1) x + a_0 = 0,
$$
so fixed points of $f(x)$ are precisely the roots of polynomial (of degree $n$)
$g(x) = f(x) - x$. According to fundamental theorem of algebra, such polynomial can have at most $n$ real roots, so $f$ has at most $n$ fixed points.
The case $n = 1$ was special, because degree of $f(x) - x$ could be different than degree of $f(x)$.
Comment: This answer is mostly correct, but I think you have made a few small errors in the part about linear functions. The unique solution when $a\neq1$ is $x=b/(1-a)$. If $a=1$ and $b=0$, then the equation has infinitely many solutions (no exceptions here). However, if $a=1$ and $b\neq0$, then there are no solutions.


mock datareader failing on second call

Question: In the test below, the mocked datareader returns the desired value the first time, but then returns the same value when the index should be 1.
Am I misusing the dataReader or Rhino stub syntax? What is the fix?
Cheers,
Berryl
failing test
[Test]
public void NullSafeGet_GetsBothProperties()
{
    var sessionImplementor = MockRepository.GenerateStub<ISessionImplementor>();
    var userType = new DateRangeUserType();

    var reader = MockRepository.GenerateStub<IDataReader>();
    var start = new DateTime(2011, 6, 1);
    var end = new DateTime(2011, 7, 1);
    reader.Stub(x => x[0]).Return(start);
    reader.Stub(x => x[1]).Return(end);    ***<==== returns Jun 1 instead of Jul1

    var result = userType.NullSafeGet(reader, userType.PropertyNames, sessionImplementor, null);
    Assert.That(result, Is.EqualTo(new DateRange(start, end, DateRange.MaxSupportedPrecision)));

}
Expected: <6/1/2011 12:00 AM - 7/1/2011 12:00 AM>
But was:  <6/1/2011 12:00 AM - 6/1/2011 12:00 AM>

SUT (NHib CompositeUserType method)
public override object NullSafeGet(IDataReader dr, string[] names, ISessionImplementor session, object owner) {
    if (dr == null) return null;

    var foundStart = (DateTime)NHibernateUtil.DateTime.NullSafeGet(dr, names[0], session, owner);
    var foundEnd = (DateTime)NHibernateUtil.DateTime.NullSafeGet(dr, names[1], session, owner);

    var precision = DateRange.MaxSupportedPrecision;
    var startDp = _getDatePoint(foundStart, precision);
    var endDp = _getDatePoint(foundEnd, precision);

    return new DateRange(startDp, endDp, precision);
}

Answer: You are not mocking everything that is called by NHibernate. This is roughly what NHibernate does with a reader:
...
int index = reader.GetOrdinal(name);
...
if (reader.IsDBNull(index)) {
    return null;
} else {
    ...
    val = rs[index];
    ...
}

Stub generated by Rhino will return 0 in response both GetOrdinal calls and it this is why it will return June1 both times. You can try to fix it by mocking GetOrdinal as well as indexer. Like this:
var reader = MockRepository.GenerateStub<IDataReader>();
var start = new DateTime(2011, 6, 1);
var end = new DateTime(2011, 7, 1);

reader.Stub(x => x.GetOrdinal(userType.PropertyNames[0])).Return(0);
reader.Stub(x => x.GetOrdinal(userType.PropertyNames[1])).Return(1);

reader.Stub(x => x[0]).Return(start);
reader.Stub(x => x[1]).Return(end);

But it might be worth reconsidering whether you really need to unit test UserType. It does not have a lot of responsibility other than calling NHibernate. Unit testing this class requires you to mock type you don't own (MS IDataReader). What's even worse is that this mock is used by another thirdparty (NHibernate). Essentially you need to look at NHibernate source code (which is what I did) to create a correct stub. Take a look at this article. It goes into a lot more details about why you should avoid mocking types that you don't own. You may be better off writing integration test for this class, using in-memory sqlite database.
Comment: @Dimitry. Thanks for a great answer, which works! I think the unit test is justified here, as since the overriden methods do contain substantial logic that are much easier and cheaper to test in isolation, but I agree with the difficulties you point out. Cheers

mock datareader failing on second call


Making user reference field in Drupal 7?

Question: I have searched in Google with queries like "User reference drupal 7" or "User taxonomy vocabulary drupal" "user field drupal 7" "cck drupal 7" but I couldn't find any way to make a field that links for a user profile page... Do you know how to make this as a simple field can be done with CCK in Drupal 6? thanks.
Comment: are you trying to link to a nodes author? to a particular user? from where are you linking it? and what is the purpose - you need to provide more information
Comment: I just want to pick a user (preferably from autocomplete but select list would be great also), than I want to select it as I would select any taxonomy term and link to it's profile page...
Comment: from where? a node? a view? a custom module? a block?
Answer: Another alternative to References is the Entity Reference module. It can do user reference fields as well.
Answer: You may look into References module

This project provides D7 versions of the 'node_reference' and 'user_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts.


There is no ViewData item of type 'IEnumerable' that has the key 'Usuario.T003_FK_COORDENACAO'

Question: Estou com um problema no DropDownListFor, ele está populado com dados do banco.
Código Controller.
var coordenacaoList = db.VW004_LISTAR_COORDENACAO.ToList();
        ViewBag.CoordenacaoList = new SelectList(coordenacaoList, "ID_COORDENACAO", "TITULO_COORDENACAO");

View.
@Html.DropDownListFor(model => model.Usuario.T003_FK_COORDENACAO, (SelectList)ViewBag.CoordenacaoList, " Selecione uma Coordenação", new { @class = "form-control" })

Só que quando vou fazer o post em uma procedure, me da esse erro.

Controller.
[HttpPost]
    public ActionResult Cadastrar(T001_USUARIO obj)
    {
        try
        {

            SqlParameter param1 = new SqlParameter("@MATRICULA_CADASTRADA", obj.T001_MATRICULA);
            SqlParameter param2 = new SqlParameter("@NOME", obj.T001_NOME_USUARIO);
            SqlParameter param3 = new SqlParameter("@PERFIL", obj.T002_FK_PERFIL);
            SqlParameter param4 = new SqlParameter("@COORD", obj.T003_FK_COORDENACAO);
            var db = new AppModel();

            var data = db.Database.ExecuteSqlCommand("SP001_CADASTRA_USUARIO @MATRICULA_CADASTRADA, @NOME, @PERFIL, @COORD", param1, param2, param3, param4);

            return RedirectToAction("Listar");

        }
        catch
        {
            return View();
        }
    }

Controller GET.
public ActionResult Cadastrar()
    {

        AppModel db = new AppModel();

        var coordenacaoList = db.T003_COORDENACAO.ToList();
        ViewBag.CoordenacaoList = new SelectList(coordenacaoList, "T003_ID_COORDENACAO", "T003_DESC_COORD");

        var perfilList = db.VW005_LISTAR_PERFIL.ToList();
        ViewBag.PerfilList = new SelectList(perfilList, "T002_ID_PERFIL", "T002_DESC_PERFIL");

        return View();
    }

Comment: Lucas, por favor, coloque o código do seu model.
Comment: public partial class T001_USUARIO
    {
        public int T001_ID_USUARIO { get; set; }
        public string T001_MATRICULA { get; set; }
        public string T001_NOME_USUARIO { get; set; }
        public Nullable T001_ATIVO { get; set; }
        public Nullable T002_FK_PERFIL { get; set; }
        public Nullable T003_FK_COORDENACAO { get; set; }
    }
Answer: Lucas, Boa tarde
Acredito que esse erro esta acontecendo no retorno do seu metodo Post, pois a lista "(SelectList)ViewBag.CoordenacaoList" deve estar null, garanta que todas as listas tem valores antes de retornar a view.
No seu metodo HttpPost
[HttpPost]
public ActionResult Cadastrar(T001_USUARIO obj)
{
    try
        {
            AppModel db = new AppModel();

            SqlParameter param1 = new SqlParameter("@MATRICULA_CADASTRADA", obj.T001_MATRICULA);
            SqlParameter param2 = new SqlParameter("@NOME", obj.T001_NOME_USUARIO);
            SqlParameter param3 = new SqlParameter("@PERFIL", obj.T002_FK_PERFIL);
            SqlParameter param4 = new SqlParameter("@COORD", obj.T003_FK_COORDENACAO);
            var db = new AppModel();

            var data = db.Database.ExecuteSqlCommand("SP001_CADASTRA_USUARIO @MATRICULA_CADASTRADA, @NOME, @PERFIL, @COORD", param1, param2, param3, param4);

            return RedirectToAction("Listar");

        }
        catch (Exception ex)
        {

            var coordenacaoList = db.T003_COORDENACAO.ToList();
    ViewBag.CoordenacaoList = new SelectList(coordenacaoList, "T003_ID_COORDENACAO", "T003_DESC_COORD");

    var perfilList = db.VW005_LISTAR_PERFIL.ToList();
    ViewBag.PerfilList = new SelectList(perfilList, "T002_ID_PERFIL", "T002_DESC_PERFIL");

            return View(obj);
        }
    }

Comment: Você poderia me dizer como fazer isso, sou novo no C#.
Comment: voce pode por exemplo adicionar o mesmo trecho de codigo que voce user na Action "HttpGet".

    var coordenacaoList = db.VW004_LISTAR_COORDENACAO.ToList();
        ViewBag.CoordenacaoList = new SelectList(coordenacaoList, "ID_COORDENACAO", "TITULO_COORDENACAO");

adicione o codigo acima antes do Return View()
Comment: Não entendi como fazer isso, vou editar minha pergunta e colocar o controller para você da uma olhada.
Comment: Adicione tambem o methodo HttpGet
Comment: Estou fazendo 2 DropDownList
Comment: Não funcionou, cai direto no catch, não apresenta mensagem de erro.
Comment: antes ja estava caindo no try catch porque se nao ele nao retornaria para a mesma pagina, mas mesmo assim agora voce pode ver atraves da variavel ex qual foi o erro


c# fast hash calculation

Question: I'm looking for a c# wrapper to a native MD5 or SHA1 library to improve hash calculation performance.
Previously I switched SharpZipLib to zlib and got more than 2x performance boost. (ok, you've to take care you've the right zlib.so or zlib.dll depending on the OS and hardware, but it pays off).
Will it be worth for MD5 or SHA1 or both .NET and Mono rely on a native implementation already?
(Edited) Also: in case I've to stick to the MD5CryptoServiceProvider, is there a way in which I can calculate a hash of a file while I'm reading it? I mean, send bytes in chunks but still calculate the whole hash?
Comment: @jrista, Collisions occur in any hash algorithm, "cracked" or not.  But in the end you're right: SHA256 is the way to go.
Comment: Keep in mind that MD5 is a cracked hashing algorithm, and isn't considered secure any more. Collisions with SHA1 have also been found, and while not as severe as MD5, they were considered significant breaks. If you need a secure hashing algorithm, you should opt for SHA2 variants (256/512).
Comment: @pablo, are you sure that hashing and not IO access is your bottleneck...
Comment: It can also be IO, you're right, but after my experience with zlib, I was thinking whether switching MD5 implementation would speed things up.
Comment: @jrista, I'm not so concerned about security since what I'm doing is hashing file contents to quickly check if they changed or not. Hashing and reading in a single pass would might help too.
Comment: @pablo, from the description of your problem the bottleneck is IO (or somehow the process of moving the data to the hashing function) try commenting out the hashing function for a tad to confirm its the case.  I doubt any optimisation of the hashing function will help, its the wrong place to be optimising.
Comment: I know that collisions can occur in any hash algorithm. However, in SHA1, the chance of a collision is high enough that the algorithm is considered insecure (hence the reason I said it was considered a 'significant break'). Both MD5 and SHA1 are broadly considered cryptographically broken, and should not be used due to their now low collision resistance. SHA1 will also no longer be supported in .NET 4.0 and future versions, so if you need a hashing algorithm with some longevity, SHA2 variants should be used.
Comment: @jrista there are no chance collisions, not from md5 or sha1, both algorithms are vulnerable to collision attacks, which mean people can theoretically engineer collisions
Comment: @Sam Saffron "there are no chance collisions" yes there are, 1 in 2^128. But it's safer than say, asteroids destroying the earth.
Answer: MD5 and SHA1 rely on native implementaions, nonetheless its possible a C++ solution + introp could be slightly faster, cause you could possibly reduce the number of method calls a bit and optimize the native implementation.
Keep in mind that the Native (SHA1CryptoServiceProvider) can be 3X faster than the managed one(SHA1Managed).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Security.Cryptography;

namespace ConsoleApplication22 {

    class Program {

        static void Profile(string description, int iterations, Action func) {

            // clean up
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            // warm up
            func();

            var watch = Stopwatch.StartNew();
            for (int i = 0; i < iterations; i++) {
                func();
            }
            watch.Stop();
            Console.Write(description);
            Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
        }

        static void Main() {
            SHA1Managed managed = new SHA1Managed();
            SHA1CryptoServiceProvider unmanaged = new SHA1CryptoServiceProvider();

            Random rnd = new Random();

            var buffer = new byte[100000];
            rnd.NextBytes(buffer);

            Profile("managed", 1000, () => {
                managed.ComputeHash(buffer, 0, buffer.Length);
            });

            Profile("unmanaged", 1000, () =>
            {
                unmanaged.ComputeHash(buffer, 0, buffer.Length);
            });

            Console.ReadKey();
        }
    }
}

managed Time Elapsed 891 ms
unmanaged Time Elapsed 336 ms

Also Keep in mind unless my calculation is wrong, the unmanaged implementation is hashing 100MB of data in about 300 milliseconds, this would very rarely be a bottleneck.
Comment: Fortunately I checked I'm using the unmanaged one: MD5CryptoServiceProvider. Loved your profiling example!
Comment: Yerp, see TransformBlock and TransformFinalBlock functions
Comment: An interop solution would require marshalling, however, which could mitigate any other gains that might otherwise be made. Just something to keep in mind.
Comment: my understanding is the SHA1CryptoServiceProvider requires marshalling anyway, its using extern calls
Comment: Sam, you're right, the problem must be somewhere else. One question, though: Is there a way to hash in chunks? I need to read the file and also to hash it, can I do it in only one pass?
Answer: The SHA1CryptoServiceProvider class uses the underlying Windows API implementation. However, SHA1Managed is pretty fast.
EDIT: Yes, it's possible to compute the hash step by step. The TransformBlock and TransformFinalBlock methods do this.
Comment: pretty fast can mean many things ... turns out pretty fast means 3 times slower .... still 30MB per 300ms is plenty fast
Answer: I would just use the BCL's SHA1 and MD5CryptoServiceProvider classes.  The ones that ship with the framework are quite fast.
Comment: Thanks. That's what I'm using right now, I'm just wondering if there's a way to make it faster. I'm hashing entire files.
Answer: Depending on your application of hashing, MD5 might not be applicable.  MD5 is only useful in error correction, it's no longer viable as a check against malicious file alteration.
http://en.wikipedia.org/wiki/Md5#Vulnerability
The short story is, MD5 collisions are easy to generate by changing 16 bytes in a file.

c# fast hash calculation


Choosing from two instances of the same form in Django post-request

Question: I have the following issue best described by example.
First, I send two instances of the same form to a Django template.
View 1:
def view_1
leg_address_form = AddressForm()
fct_address_form = AddressForm()
return render_to_response('my_template.html',
                          {'leg_address_form':leg_address_form,
                           'fct_address_form':fct_address_form},...

After this, when submit button is pressed somewhere in my_template, I have to process the request and I am having trouble accessing the data from the two form instances.
View 2:
def employee_create(request.POST):
    leg_address_form = AddressForm(request.POST) #how could I know which one is it?
    fct_address_form = AddressForm(request.POST) #how could I know which one is it?

Answer: You could use prefix to give each Form its own namespace.
def main_view(request):
    if request.method == 'POST':
        leg_address_form = AddressForm(request.POST, prefix='leg')
        fct_address_form = AddressForm(request.POST, prefix='fct')
        # do something with data
    else:
        leg_address_form = AddressForm(prefix="leg")
        fct_address_form = AddressForm(prefix="fct")
    return render_to_response('my_template.html',
                      {'leg_address_form':leg_address_form,
                       'fct_address_form':fct_address_form},...

Comment: I updated my answer. Here I just use only one view function.


Ajuda - Upload Específico PHP

Question: Galera, Eu precisava de uma ajuda enorme, na verdade uma caminho pra tentar fazer oque eu pretendo.
O problema é esse que eu não tenho nenhuma ideia de como fazer:
Tenho um sistema que geram boletos com o seguinte nome:
020 112.pdf
020 113.pdf
021 163.pdf
021 164.pdf

021 seria = id de um user,
112 seria a quantia de boletos que o user tem até agora.

Eu precisava ter uma área específica pra enviar arquivos .pdf em apenas um input (file multiple),seja em php (Que eu conheço um pouco), ou outra linguagem pra mim estudar melhor.
Ao Selecionar todos esses boletos acima, eu precisava que direcionasse automaticamente para a conta dos usuários.
Exemplo:
020 112.pdf
020 113.pdf

Esses arquivos pdf por exemplo deve ir para o user que começa com "020..." e assim sucessivamente.
Obrigado desde já.
EDIT:
Necessariamente só preciso fazer com que os arquivos fossem pra pasta de acordo com o código começado, como dito no exemplo.
Tenho o seguinte código HTML:

    <meta charset="utf-8"/>
    <title>Upload PDF</title>

    <link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700" rel='stylesheet' />

    <link href="assets/css/style.css" rel="stylesheet" />

    <form id="upload" method="post" action="upload.php" enctype="multipart/form-data">

            Drop Here

            Browse
            <input type="file" name="upl" multiple />

    </form>

script.js
    $(function(){

    var ul = $('#upload ul');

    $('#drop a').click(function(){
        // Simulate a click on the file input button
        // to show the file browser dialog
        $(this).parent().find('input').click();
    });

    // Initialize the jQuery File Upload plugin
    $('#upload').fileupload({

        // This element will accept file drag/drop uploading
        dropZone: $('#drop'),

        // This function is called when a file is added to the queue;
        // either via the browse button, or via drag/drop:
        add: function (e, data) {

            var tpl = $('
<input type="text" value="0" data-width="48" data-height="48"'+
                ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />

');

            // Append the file name and file size
            tpl.find('p').text(data.files[0].name)
                         .append('' + formatFileSize(data.files[0].size) + '');

            // Add the HTML to the UL element
            data.context = tpl.appendTo(ul);

            // Initialize the knob plugin
            tpl.find('input').knob();

            // Listen for clicks on the cancel icon
            tpl.find('span').click(function(){

                if(tpl.hasClass('working')){
                    jqXHR.abort();
                }

                tpl.fadeOut(function(){
                    tpl.remove();
                });

            });

            // Automatically upload the file once it is added to the queue
            var jqXHR = data.submit();
        },

        progress: function(e, data){

            // Calculate the completion percentage of the upload
            var progress = parseInt(data.loaded / data.total * 100, 10);

            // Update the hidden input field and trigger a change
            // so that the jQuery knob plugin knows to update the dial
            data.context.find('input').val(progress).change();

            if(progress == 100){
                data.context.removeClass('working');
            }
        },

        fail:function(e, data){
            // Something has gone wrong!
            data.context.addClass('error');
        }

    });

    // Prevent the default action when a file is dropped on the window
    $(document).on('drop dragover', function (e) {
        e.preventDefault();
    });

    // Helper function that formats the file sizes
    function formatFileSize(bytes) {
        if (typeof bytes !== 'number') {
            return '';
        }

        if (bytes >= 1000000000) {
            return (bytes / 1000000000).toFixed(2) + ' GB';
        }

        if (bytes >= 1000000) {
            return (bytes / 1000000).toFixed(2) + ' MB';
        }

        return (bytes / 1000).toFixed(2) + ' KB';
    }
}
);

UPLOAD editado:
   <?php

// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip','pdf');

if(isset($_FILES['upl']))
{

    $ext = substr($_FILES['upl']['name'],-4); //Obtém a extensão do aquivo.
    $nome = substr("020 112.pdf", 0, -4); //retorna o nome sem extensão
    $dados = explode(" ", $nome); //Divide a string em partes.

    $dados[0]; //Parte "0" da string corresponde ao id do user.
    $dados[1]; //Parte "1" da string corresponde a quantia de boletos que o user tem

    $dir = 'uploads/'.$dados[0].'/'; //Diretório para uploads separando por id

    move_uploaded_file($_FILES['upl']['tmp_name'], $dir.$_FILES['upl']['name']); //Fazer upload do arquivo

}

Comment: Você pode usar o [explode](http://br.php.net/manual/pt_BR/function.explode.php) para capturar os valores `020` e `112`. E para enviar o arquivo... http://php.net/manual/pt_BR/features.file-upload.php
Comment: Você pode usar `$dir.$dados[1].pdf` e substituir `substr("020 112.pdf", 0, -4);` por `substr($_FILES['upl']['name'], 0, -4);`
Comment: Você tentou usar o `explode` (como na resposta abaixo) para separar os valores do nome do arquivo?
Comment: sim, porém, ele até vai pra pasta 020/020 113.pdf, mas vão todos os arquivos pra essa pasta e não distribuiu para as outras criadas. editei o Upload
Comment: Funcionou! Por um detalhe! obrigado!
Answer: Segue uma sugestão, existem inúmeras formas de entender e fazer o que você precisa. A "conta do cliente" pode ser um registro no banco de dados ou uma pasta específica.
O Html pode ser semelhante a esse:

       <title>Basic Upload</title>

       <form action="#" method="POST" enctype="multipart/form-data">
          <input type="file" name="arquivos">
          <input type="submit" value="Enviar">
       </form>

O arquivo PHP que irá receber o POST pode ser semelhante a esse:
if(isset($_FILES['arquivos']))
{

    $ext = substr($_FILES['arquivos']['name'],-4); //Obtém a extensão do aquivo.
    $nome = substr("020 112.pdf", 0, -4); //retorna o nome sem extensão
    $dados = explode(" ", $nome); //Divide a string em partes.

    $dados[0]; //Parte "0" da string corresponde ao id do user.
    $dados[1]; //Parte "1" da string corresponde a quantia de boletos que o user tem

    $dir = 'uploads/'.$dados[0].'/'; //Diretório para uploads separando por id

    move_uploaded_file($_FILES['arquivos']['tmp_name'], $dir.$_FILES['arquivos']['name']); //Fazer upload do arquivo

}

Dessa forma os arquivos deverão ficar separados por pasta, sendo que o nome da pasta é o id do usuário.
Exemplo:

uploads/020/020 112.pdf
uploads/020/020 113.pdf
uploads/021/021 163.pdf
uploads/021/021 164.pdf

Você deverá aprimorar o código, mas a ideia é essa!

Ajuda - Upload Específico PHP


Irreducible polynomial over an algebraically closed field

Question: Suppose $k$ is an algebraically closed field and $p(x,y)\in k[x,y]$ is an irreducible polynomial.

Prove that there are only finite many $a\in k$ such that $p(x,y)+a$ is reducible, i.e. the set $\{a\mid p(x,y)+a $ is reducible over $k, a\in k\}$ is finite.

More generally, suppose $p\in k[x_1,\ldots,x_n]$ is irreducible, is it true that there are only finite many $a\in k$ such that $p+a$ is reducible?
Thanks!
Answer: Yes, there are only finitely many values of $a$ for which $p(x_1,...,x_n)+a$ is reducible.
In order to use the mighty tools of projective algebraic geometry, let us   consider the  homogeneization  $P(x_0,x_1,...,x_n)$ of $p(x_1,...,x_n)$  ($P$ is an irreducible  homogeneous polynomial of degree $d$) and ask whether $P(x_0,x_1,...,x_n)+ax_0^n$ is irreducible with only finitely many exceptions (The factorizability of the homogeneized polynomial  is equivalent to the factorizability of the original polynomial).
The  answer is yes.
Indeed in the projective space  $\mathbb P^{N_d}\: (N_d=\binom {n+d}{d}-1)$ of homogeneous polynomials of degree $d$ in $n+1$ variables , the reducible ones form a union of finitely many irreducible strict subvarieties: the images of the morphisms  $\mathbb P^{N_e} \times \mathbb P^{N_f}\to \mathbb P^{N_d}\; (e+f=d)$ given by the multiplication of a polynomial of degree $e$ by one of degree $f$.
The rest is easy: the projective line in $\mathbb P^{N_d}$ given by the family $P(x_0,x_1,...,x_n)+ax_0^n$ is not included in the mentioned union of subvarieties because the polynomial corresponding to $a=0$ is irreducible.
Hence it cuts that variety for only finitely many values of $a\in k$ and for the other values of $a$ both $P(x_0,x_1,...,x_n)+ax_0^n$ and $p(x_1,...,x_n)+a$ are irreducible.
Comment: Great answer!!!


How to implement recursive self join entity framework?

Question: I have Menu table in database which have self referencing foreign key i.e. ParentID. Below is my Menu class (DB First Approach)
public partial class Menu
{
    public Menu()
    {
        this.Menu1 = new HashSet<Menu>();
        this.Products = new HashSet<Product>();
    }

    public int MenuID { get; set; }
    public string Name { get; set; }
    public Nullable<int> ParentID { get; set; }
    public virtual ICollection<Menu> Menu1 { get; set; }
    public virtual Menu Menu2 { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

I want to implement following things,

I want entire hierarchy using menu id e.g "if I pass 7 then result should be all the child and sub-child of menu id 7"
If I pass 7 then I want all parent and super parent of menu id 7.

I found several article on StackOverflow before posting this question but they were asking to implement Code First Approach. Here are the questions posted on Stackoverflow before Entity Framework Self Join, Most efficient method of self referencing tree using Entity Framework
Comment: Possible duolicate: http://stackoverflow.com/questions/1308158/how-does-entity-framework-work-with-recursive-hierarchies-include-seems-not-t
Comment: A possible solution is through a TVF (Table Valued Function) that uses a TSQL Recursive Query and returns the rows.
Comment: @xanatos : I can not interact with database. I have Static list of Menu class object. That's why i need to do it with EF.
Answer: I am not sure if you realize this but Menu1 is your parent Menu and Menu2 are your children menus. (I would recommending renaming both Menu1 and Menu2 properties to parent and children).
I believe all of the solutions you have linked have a solution you can use to solve your problem.

Code Sample:
void GetParents(Menu current) {
    dbContext.Entry(current).Reference(m => m.Menu2).Load();
    while (current.Menu2 != null) {
        current = current.Menu2;
        dbContext.Entry(current).Reference(m => m.Menu2).Load();
    }
}

void GetChildren(Menu current) {
    if (current == null) {
        return;
    } else {
        dbContext.Entry(current).Collection(m => m.Menu1).Load();
        foreach (var menu in m.Menu1) {
            GetChildren(menu);
        }
    }
}

Something like this should help you get all parents and all children of a Menu instance called current. Note the efficiency is terrible. But that is a different problem. I don't optimize code until my performance tests indicate the bottlenecks in my application.
Fun quote: "Premature optimization is the root of all evil." - Donald Knuth
Comment: Parth i can reach parent and child upto one level by following code 'List childList = db.Menus.Where(m => m.ParentID == menuID).ToList();' . There may be N-Level. How can i do it?
Comment: Added a code sample. It is untested so you will need to change stuff here and there. But that is the general idea. I re-read your class definition and am a bit confused on why you call Nullable ParentId? I would assume they would be your children? However if your model says you can have multiple parents and just one child, then you will have to rename my functions.
Comment: Your answer helped me solve my problem. I want to vote up but my reputation is 1 so i cant do it and i cant find accept answer or mark correct answer button to accept your answer.
Comment: You might see a tick below the vote up/down buttons. If you click on the tick, then it will mark this answer as correct.