Do not trigger my method more than once

Question: models.py
class Contract(TimeStampedModel):
    customer = models.ForeignKey('customers.CustomerProfile')
    template = models.ForeignKey('configurations.ContractTemplate')
    product = models.OneToOneField('products.CustomerProduct')
    signed_at = models.DateTimeField(_('Date signed'), blank=True, null=True)
    cancelled_at = models.DateTimeField(_('Date cancelled'), blank=True,
                                        null=True)
    html_source = models.TextField(_('HTML source'), blank=True, null=True)
    pdf_file = models.OneToOneField('documents.Meta', on_delete=models.SET_NULL,
                                    blank=True, null=True)
    is_signed = models.BooleanField(_('Is signed'), default=False)
    is_cancelled = models.BooleanField(_('Is cancelled'), default=False)
    signature_uuid = models.UUIDField(_('Signature UUID'), primary_key=False,
                                      default=uuid.uuid4, editable=False)
    signature_ip = models.GenericIPAddressField(_('Signature IP'), blank=True,
                                                null=True)

...

    def sign(self, ip):
        from loanwolf.contracts.utils import render_html_contract, store_pdf_contract
        self.html_source = render_html_contract(self.template, self.customer,
                                                self.product)
        store_pdf_contract(self)
        self.signature_ip = ip
        self.signed_at = datetime.datetime.now()
        self.is_signed = True
        self.save()
        if self.request.state.is_signature:
            self.request.sign()
        return True

views.py
class ContractAsHtmlView(DetailView):
    model = Contract
    pk_url_kwarg = 'uuid'

    def get_object(self, queryset=None):
        try:
            return self.model.objects.get(
                signature_uuid=self.kwargs.get('uuid'))
        except self.model.DoesNotExist:
            return None

    def render_to_response(self, context, **response_kwargs):
        if self.request.GET.get('lang'):
            lang = self.request.GET.get('lang')
        else:
            lang = translation.get_language_from_request(self.request)
        if self.object.template.language == lang:
            template = self.object.template
        else:
            try:
                template = ContractTemplate.objects.get(
                    slug=self.object.template.slug, language=lang)
            except ContractTemplate.DoesNotExist:
                template = self.object.template
        html = render_html_contract(
            template, self.object.customer, self.object.product)
        return HttpResponse(html)

    def get_context_data(self, **kwargs):
        import ipdb; ipdb.set_trace()
        context = super(ContractAsHtmlView, self).get_context_data(**kwargs)

        context.update({
            'signature_ip': self.viewing_signature_ip,
        })

    @property
    def viewing_signature_ip(self):
        import ipdb; ipdb.set_trace()
        contract = Contract.objects.get(pk=1)
        if contract.sign == True:
            return contract.signature_ip

In the moment, sign() method returns a Boolean argument, but it can't be triggered more than once. Hence, I can't use that method in my view with if contract.sign == True:. Anyway, sign() needs arguments and it is not a property. Is there another way to call sign() without triggering it another time? Could I use a sort of indicator or signal to do such thing?
In clear, sign() is used somewhere else in the program. I would like to say to view_signature_ip() method  if sign() is true, than return contract.signature_ip.
Comment: do you mean you can't use `{% if contract.sign %}` in your template? After calling sign() on your contract instance you could check the `contract.is_signed` attribute?
Comment: @Odi No, I can't. Your second question is very interesting. Could you develop a little bit more about 'you could check the `contract.is_signed` attrbute'? Could you build a full answer about that? Furthermore, I can't use `{% if contract.sign %}` because `sign` is not a property
Answer: Okay, let's see. You have a bug in your property method:
@property
def viewing_signature_ip(self):
    import ipdb; ipdb.set_trace()
    contract = Contract.objects.get(pk=1)
    if contract.sign == True:
        return contract.signature_ip

You are checking against a method definition, which is always True ;) If you want to check against the result of the method, you have to call it: if contract.sign() == True :-)
If you want to avoid calling sign, you could use the is_signed attribute of the contract instance: if contract.is_signed.
Another thing about the method property: contract = Contract.objects.get(pk=1) is called everytime you access the property, you might want to cache the result of the contract in a view attribute:
    _signature_ip = None

    @property
    def viewing_signature_ip(self):
        import ipdb; ipdb.set_trace()
        if self._signature_ip is not None:
             return self._signature_ip

        contract = Contract.objects.get(pk=1)

        self._signature_ip = contract.signature_ip if contract.is_signed else ''
        return self._signature_ip

Do not trigger my method more than once


Android spinner problem

Question: I've create the android application program..I have done the program that extends list activity. Is spinner works insdie the listview..pls tell some idea..Thanks in advance.
Comment: I cannot understand what you need, could you try rephrasing your question?
Comment: and for next time you need to improve you asking question technique
Comment: @uthra you want to use spinner into listview or spinner with the listview. if spinner into listview that means its like list of spinner like checkbox list.
Comment: please provide your layout xml file here
Comment: Please Provide Some Code & Description About Your Problem.
Comment: i want to use spinner into listview
Comment: I have attached my xml file..http://pastebin.com/raw.php?i=U2Bvmq9r
Comment: i got you problem, just concentration on keyword :: you need to implement custom list-view in which each list-item has spinner are show right? so you need to implement with custom adapter.  i think this will help you http://stackoverflow.com/questions/7411228/android-how-to-use-inbuilt-icons-and-template/7411283#7411283
Comment: @nik Thank you very much.Hereafter i improve to ask question
Answer: i got you problem, just concentration on keyword :: you need to implement custom list-view in which each list-item has spinner are show right? so you need to implement with custom adapter.  i think this will help you How to use inbuilt icons and template?

Android spinner problem


Best way to pass object to child component

Question: It's very interesting to know - is there difference in performance between
<Child data={{...// some props here}}/>
and
render() {
    const data = {...}
    return <Child data={data}/>
}

I read about functions. That it is better to replace inline functions
from:
<button
    onClick={() => {
        ...
    }}
/>

To:
handleClick = () = {...}

...

<button
    onClick={this.handleClick}
/>

And what about passing objects?
Comment: Bad for handlers not for passing data. :) Helpful link: https://medium.freecodecamp.org/why-arrow-functions-and-bind-in-reacts-render-are-problematic-f1c08b060e36
Answer: render() {
    const data = {...}
    return <Child data={data}/>
}

The data should be outside render(), because when some states are change, the render() method will be recall, and the data will be set again and again. So for performance, better declare it outside render()
Answer: If the object is not derived from state or props and always be constant then better declare it outside the render method to avoid assigning the value to data every time the render method is called.
In comparison, for passing an object to a component both options(inline and assigning to a variable) are equivalent in terms of performance.
Answer: If you want to pass all the props to child component from parent then you can do like:
<Child data={...this.props} />

But if you want to pass some props to that child component then you can take out those props in some constant and pass that constant to the child like:
const data = {data1: this.props.data1, data2: this.props.data2};
return <Child data={data}/>


Column Differences for MultiIndex Dataframes

Question: I've got (probably) quite a simple problem that I just cannot wrap my head around right now. I'm collecting the following two series:
from pandas_datareader import wb
countries = [
            'DZA', 'ARM','AZE','BLR','BIH','BRN','KHM','CHN','HRV', 'CZE','EGY',\
             'EST','GEO','HUN','IND','IDN','ISR','JPN','JOR','KAZ','KOR','KGZ','LAO','LVA',\
             'LBN','LTU','MYS','MDA','MNG','MMR','MKD','PHL','POL','ROU', 'RUS','SAU',\
             'SGP','SVK','SVN','TJK','THA','TUR','UKR','UZB','VNM'
]
dat = wb.download(indicator='FR.INR.LEND', country=countries, start=2010, end=2019)
dat.columns = ['lending_rate']
us = wb.download(indicator='FR.INR.LEND', country='US', start=2010, end=2019)
us.columns = ['lending_rate_us']
dat2=pd.concat([dat,us])
dat2

I'd like to take the difference between lending_rate and lending_rate_us but obviously would like to subtract lending_rate_us for the US only from lending_rate in all other countries (ie. avoid what would otherwise lead to NANs everywhere).
So I guess what I'm trying to do is to copy the values for lending_rate_us to all other countries to then take the difference between both columns.
Does anyone have an idea how to do that (or an alternative idea that makes more sense)?
Thanks!
EDIT:
I tried the following, alas without success:
from pandas_datareader import wb
countries = [
            'DZA', 'ARM','AZE','BLR','BIH','BRN','KHM','CHN','HRV', 'CZE','EGY',\
             'EST','GEO','HUN','IND','IDN','ISR','JPN','JOR','KAZ','KOR','KGZ','LAO','LVA',\
             'LBN','LTU','MYS','MDA','MNG','MMR','MKD','PHL','POL','ROU', 'RUS','SAU',\
             'SGP','SVK','SVN','TJK','THA','TUR','UKR','UZB','VNM'
]
dat = wb.download(indicator='FR.INR.LEND', country=countries, start=2010, end=2019)
dat.columns = ['lending_rate']
us = wb.download(indicator='FR.INR.LEND', country='US', start=2010, end=2019)
us.columns = ['lending_rate']

for i in dat.index.get_level_values(0).unique():
    dat["lending_rate_spread"]=dat.loc[i,:]-us.loc["United States",:]
dat

Output:
        lending_rate    lending_rate_spread
country year
Armenia
2019    12.141989   NaN
2018    12.793042   NaN
2017    14.406002   NaN
2016    17.356706   NaN
2015    17.590330   NaN
... ... ... ...
Vietnam
2014    8.665000    NaN
2013    10.374167   NaN
2012    13.471667   NaN
2011    16.953833   NaN
2010    13.135250   NaN
450 rows × 2 columns

But when I just print the result of the loop without creating a new column I get the correct values:
for i in dat.index.get_level_values(0):
    print(dat.loc[i,:]-us.loc["United States",:])

Output:
      lending_rate
year
2019      6.859489
2018      7.888875
2017     10.309335
2016     13.845039
2015     14.330330
2014     13.158665
2013     12.744987
2012     13.980068
2011     14.504474
2010     15.950428
      lending_rate
year
2019     11.998715
2018     12.544167
2017     12.445833
2016     12.863560
2015     14.274167

I don't understand why I would get the correct result but not present it in the correct way?
Comment: What does *subtract `lending_rate_us` for the US only from lending_rate in all other countries* mean?
Comment: Yes, that was a bit confusing perhaps. I'd like to get spreads of all countries relative to the US. `lending_rate_us` is only reported for the US, so it is `NaN` in all other countries. So if I had ```diff=lending_rate-lending_rate_us```, I'd get a column with `NaN` values. So basically, I want to subtract values for one MultiIndex level (US) from all other levels.
Comment: I noticed that the display loop succeeds and the write error occurs when the destination country is not specified. Also, there are some countries where the rate values do not add up to the year data being obtained in US, so you need to adjust the US data according to the number of year data for the country you are writing to.
Answer: In response to your comment, I reviewed the data again. I reworked the data for each country as NA data existed, and found that all of the data was for 10 years.
The method @Paul commented on is possible, so I modified the code.
dat['lending_rate_us'] = us['lending_rate_us']*len(dat['country'].unique())
dat['lending_rate_spread'] = dat['lending_rate'] - us['lending_rate_us']
dat.head()
country     year    lending_rate    lending_rate_us     lending_rate_spread
0   Armenia     2019    12.141989   237.7125    6.859489
1   Armenia     2018    12.793042   220.6875    7.888875
2   Armenia     2017    14.406002   184.3500    10.309335
3   Armenia     2016    17.356706   158.0250    13.845039
4   Armenia     2015    17.590330   146.7000    14.330330

Comment: If my answer helped you, please consider accepting it as the correct answer
Comment: That does seem to work, thanks. Although I do wonder, if there isn't a more efficient solution for this. It seems to be a fairly complex loop for doing something so simple like calculating a spread. Having to set a destination country does make sense though. I wonder if one cannot simply add a column that repeats values from the US for all other countries and then take the difference between columns?


WCF Interop with WSE2.0

Question: I'm attempting, with great difficulty, to have an WCF client communicate with a WSE 2.0. The wse service requires UserName token for authentication and it would appear that this is not possible over an unsecured channel.
I have configured the following custom bindings:
<code><customBinding>
        <binding name="wse2Binding">
          <textMessageEncoding messageVersion="Soap11WSAddressingAugust2004" />
          <security authenticationMode="UserNameOverTransport">
            <secureConversationBootstrap authenticationMode="UserNameOverTransport" />
          </security>
          <httpTransport authenticationScheme="Digest"/>
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="http://ecareweb/eCareMessaging1_1/Notification.asmx"
        binding="customBinding" bindingConfiguration="wse2Binding"
        contract="NotificationSrv.NotificationSoap" name="NotificationSoap1" />
    </client>
</code>
Do you know of a work-around for this problem
Thanks in advance
Comment: You _do_ know that WSE is obsolete, right? Especially 2.0?
Comment: I know. Unfortunately, the WSE services are hosted by a third-party.
Answer: WCF does not allow you by default, but if you have exceptional circumstances you can still do it.
Here is some sample code for using ClearUserNameBinding
Answer: WCF will not let you send username/password over an HTTP connection. If you have control over the service side I would suggest adding an HTTPS endpoint so you can use transport level security.
Comment: I'm aware of this solution, but wondered if there was a work around for having to impose https.

WCF Interop with WSE2.0


Why is the expected gradient of a density not parallel to the expected gradient of the log density?

Question: I'm confused by a seemingly counter-intuitive property of the interaction between distributions, log transforms, expectations and gradients.
Suppose I have some distribution over random variable $x$ parameterized by $\theta$. (Unless I'm mistaken), the MLE for the distribution is the same as the MLE for the log of the distribution.
$$\theta^* = \underset{\theta}{\operatorname{argmax}}  p(x;\theta) = \underset{\theta}{\operatorname{argmax}}  \log p(x;\theta)$$
If $p(x;\theta)$ is differentiable with respect to $\theta$, I believe that the gradient of the distribution with respect to $\theta$ is parallel to the gradient of the log distribution since
$$\nabla_{\theta} \log p(x ; \theta) = \frac{1}{p(x ; \theta)} \nabla_{\theta} p(x ; \theta)$$
This means that performing gradient ascent on $\log p(x;\theta)$ is the same as performing gradient ascent on $p(x; \theta)$.
In contrast, if I consider the expected value of the gradient of the distribution $\langle \nabla_{\theta} p(x;\theta) \rangle_{p(x;\theta)}$ against the expected value of the gradient of the log density $\langle \nabla_{\theta} \log p(x;\theta) \rangle_{p(x;\theta)}$ , the two are perpendicular since the mean of the gradient of the log density is 0:
$$
\begin{align*}
\langle \nabla_{\theta} \log p(x;\theta) \rangle_{p(x;\theta)}
&= \int dx \, p(x;\theta) \nabla_{\theta} \log p(x;\theta)\\
&= \int dx \, p(x;\theta) \frac{1}{p(x;\theta)} \nabla_{\theta} p(x;\theta)\\
&= \int dx \, \nabla_{\theta} p(x;\theta)\\
&= \nabla_{\theta} \int dx \, p(x;\theta)\\
&= \nabla_{\theta} 1\\
&= 0
\end{align*}
$$
This seems contradictory. For any specific sample from the density, the two gradients point in the same direction, but averaged over multiple samples, they don't. Why is the expected gradient of a density not parallel to the expected gradient of the log density?
Answer: There is a minor typo in one of the equations:
$$\nabla_{\theta} \log p(x ; \theta) = \frac{\nabla_{\theta} p(x ; \theta)}{p(x ; \theta)} $$
Nevertheless, I think the confusion is because you are ignoring the effect of the term $p(x;\theta)$.
Consider a simple example, the gradient of the function $x^2 + y^2$ averaged over all the points on the unit circle is zero i.e $2x \hat{i} + 2y\hat{j} $ average over the unit circle is zero vector.
However, the same gradient when weighted by a term, say, $\frac{1}{x}$ is non-zero i.e $2 \hat{i} + 2\frac{y}{x}\hat{j} $ averaged over unit circle has positive component along x-axis.
Notice that in both the cases, the gradients are parallel
Comment: Good catch on the typo! I fixed it.
Answer: Usually when you're doing maximum likelihood estimation what you're really trying to do is maximize the posterior distribution $p(\theta | x)$. That is, you're trying to find the most likely model (or model parameters) given a set of data $x$. By Bayes' theorem, this becomes
$$
p(\theta | x) = \frac{p(x | \theta) p(\theta)}{p(x)}.
$$
We maximize this by taking the derivative with respect to $\theta$. The derivative $\nabla_\theta p(x)$ is zero, and if the prior is sufficiently weak then its derivative is (approximately) zero as well, so we can approximate the maximum posterior by using maximum likelihood estimation.
Now, consider the form of $p(x|\theta)$ when you have multiple data points. If the points are chosen independently from the underlying (unknown!) distribution $p(x)$, then
$$p(\vec{x}|\theta) = p(x_1, x_2, \ldots | \theta) = \prod_i p(x_i|\theta).$$
As you note, $\nabla_\theta f(\theta)$ is parallel to $\nabla_\theta \log f(\theta)$, so we might as well maximize $\log p(\vec{x}|\theta)$ instead. The product becomes a sum,
$$
\log p(\vec{x}|\theta) = \sum_i \log p(x_i | \theta),
$$
and we can divide by the total number of samples and take the continuum limit to get an expectation over all samples,
$$
\log p(\vec{x}|\theta) \rightarrow \langle\log p(x|\theta)\rangle_{p(x)}.
$$
Maximizing this expression will be equivalent to maximizing the posterior distribution with a uniform (or weak) prior. Note that the expectation should be over $p(x)$, not $p(x|\theta)$! The derivative goes to zero when $p(x) = p(x|\theta)$, as you noted, which just shows that you've modeled the distribution perfectly and reached the maximum likelihood.
So why not maximize the expectation of $p(x|\theta$) directly? Because that expectation doesn't correspond to joint a probability distribution! You shouldn't expect that maximizing the sum of a bunch of probabilities would yield the same result as maximizing their product, which is really what you want to do at the end of the day.


Cannot make tftp connection for PIX firewall password reset

Question: I am trying to reset my firewall password so that I can do a factory reset on it.
I bought it used and the rules are more restrictive than I want. It's being used for a small project where we can demonstrate a bad configuration.
I am following the Cisco PIX Password Recovery Guide as the basis for my procedure.
These are the steps that I followed:

Turn off wireless
Go to my LAN network options and click on ipv4 options
Set the ip 192.168.1.49 and DNS 255.255.255.255, click ok
Start a tftp server on the ip 192.168.1.49
Connect the firewall via ETHERNET to my laptop (I also have the console serial connected)
Go into my terminal and type address 192.168.1.75, this is the ip I want for the firewall
Then I type server 192.168.1.49, ip of my comp/server
I use the command ping 192.168.1.75 to test the connection and it says 0/5 successful
I tried using the tftp command to get the file I needed, but it just hung forever

What could I be doing wrong?
I checked out wireshark to see what was happening with the 'tftp' command and it would always say port unreachable. I am using port 69 on my tftp server, if the ping command didn't work the tftp command probably isn't going to work either
The firewall is connected DIRECTLY to laptop via ETHERNET. I tried using interface 0, but it failed.  Interface 1 worked just fine. I don't know if this makes a difference or not.
I am going to try to put a router in between the two to see if it will help me at all
Comment: This could be windows firewall blocking the connections
Comment: While this is about a device that provides security-related functions on a network, I'm not seeing a question that's actually about security here.  Maybe [sf] might be a better place for this.  I've flagged it for migration - please don't cross-post.
Comment: This is more about device configuration, albeit a traditionally security device. This is really a better fit for our sister site for Information Technology Professionals, [SF].
Answer: I've only worked on the ASA series firewalls and this is the procedure I use: http://www.ranjodh.com/cisco/how-to-reset-asa-password/. I believe it will work on the PIX as well.
Either way you can always call the TAC and they will walk you threw it step by step.
Comment: I'm trying to use 192.168.1.* 255.255.255.255, should it be 255.255.255.0 or do I need to use a router and switch?
Answer: Ideally, you would have a switch between your computer and the firewall, but a direct connection should work.
You need to change the IP address of your computer to 192.168.1.* 255.255.255.0.  This could definitely cause the issues you described.  By specifying 255.255.255.255 as the netmask, you told the computer that the entire network consists of only 1 IP address.  Even if it successfully receives tftp traffic from the PIX, your computer won't know how to respond since there are no other devices on your interface's network.
Also, be sure to turn off, or properly configure your desktop firewall.
You would probably get more feedback for this question on http://superuser.com or http://serverfault.com


Date format on client browser

Question: I am getting a date from the server as a javascript string(GMT) or unix timestamp(GMT).
I can convert it to a javascript date object with
var date = new Date(string) or var date = new Date(string)
This gives me the date variable with proper system time-zone's time.
Currently I am displaying this- date.toLocaleString()
Which gives me a nicely formatted date/time according to my system locale and time zone.
I am using this to automatically accomodate for DST if the client browser follows it.
Previously I was required to display this date only in EST, but when the US time started following EDT, I was told to display it in EST. I think this approach would simplify displaying the time/date acoording to user's system time setting.
Is there any disadvantage or possible bug accociated with this approach?
If yes, what would be the best way to display this date in the browser, so that it displays correctly according to the timezone(accomodating DST if any) in which the user(cient browser) is?
Comment: [`toLocaleString` returns a string value that is similar to the following form. The exact format depends on the platform, locale and user's settings.](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleString#Using_toLocaleString)
Comment: when you do new Date() in Javascript you get the current date in his currently set time format. in casa you are sending the date from server it might be in different time format may be with daylight saving as well.
Comment: @AurA As I mentioned, the server time I am receiving is in GMT (+00 offset)
Answer: As pointed out in the comments, the output may be different depending on the users settings. A more reliable and flexibe solution is moment.js, which is a great library.
moment("2013-04-04", "YYYY-MM-DD").format("MMM Do YY"); //"Apr 4th 13"

Comment: In this case I just have to display the date. It is not, and will not be used for any other purpose. It would be ok if it is not consistent across browsers. I think it would be even better if it displays according to system locale or users specified preferences.

Date format on client browser


Expected value formula explanation in probability

Question: Could anyone explain me why we compute expected value as :
$E[X] := \sum\limits_{i} x_i p_i$
I understand the output of the formula but I can't understand why the formula works.
Comment: Closely related and possible duplicate: [need help with understanding expected values](https://math.stackexchange.com/questions/2050808/i-need-help-with-understanding-expected-values?rq=1)
Comment: "*I can't understand why the formula works*"... How do you **define** expected value then, because that is the very definition that I am used to seeing as the definition (*for a discrete case*).
Answer: Explanation of a definition
I would change the question:
Why is this the definition of the expectation:
$$\sum_1^n x_ip_i?\tag 1$$
when the possible outcomes of a random experiment are $\{x_1,x_2,\dots x_n\}$ and the probabilities belonging to the outcomes are $p_1,p_2,...p_n$.
Assume that we don't know anything about probability theory and we have a source of random numbers $\{x_1,x_2,\dots x_n\}$ and we want to calculate the average of the random numbers poured by the source. So, let's denote the random outcomes of the source by $X_1, X_2, \dots X_N$. Here all the $X_i$ can take one of the values from $\{x_1,x_2,\dots x_n\}$ and $N$ has nothing to do with $n$. $N$ is just the number of the outcomes we observed. Preferably $N$ is way larger than $n$. Now, the average is
$$A=\frac1N\sum_1^N X_j.$$
Assume now, that the values $x_1, x_2,\dots x_n$ appeared $m_1,m_2,\dots, m_n$ times during the experiment. $\left(m_1+m_2+\cdots m_n=N\right)$
With this
$$A=\frac1N\sum_1^N X_j=\frac{m_1}Nx_1+\frac{m_2}Nx_2+\cdots\frac{m_n}Nx_n=$$
$$=\overline p_1x_1+\overline p_2x_2+\cdots +\overline p_nx_n=$$$$=\sum_1^nx_i\overline p_i $$
where $\overline p_i$'s are the relative frequencies of the values $x_i$ in our experiment.
Now, if we believe that the $\overline p_i$'s are good approximations of the probabilities then it will be intuitive to define the expectation as in $(1)$ because then we can look at the expectation as an estimate of the average if we calculate that based on a long series of independent outcomes of a long sequence of experiments. (Of course expectation and average have to be sort of synonyms in our eyes.
Then probability theory cleans up all this...


Ports to open for FTP II 7.5 Publish Servicing?

Question: Recently setup an ftp server using FTP 7.5 publishing service... I have tried opening ports 20,21 and that sort of worked but it hang after logging in.... saying Opening binary.....
I disabled the firewall and all works ok... So i tried following this document
http://learn.iis.net/page.aspx/309/configuring-ftp-firewall-settings/
but it fails to work, can anyone tell me what i am missing?
I have specifically done this as per the document above
netsh advfirewall firewall add rule name="FTP for IIS7" service=ftpsvc action=allow protocol=TCP dir=in

netsh advfirewall set global StatefulFtp disable

and set port channel range to 49152-65535..
As i say as per the document it FAILS won't even log in ... as if there is not ftp service there, with my GUESS opening port 20-21 TCP it sort of works but stops at opening binary.....
If i disabled the firewall completely that it works 100% without problems..
I am using Windows 7 (similar firewall setup to Windows 2008 server)
Any ideas really appreciated
thanks
Answer: Seems like a statefull filtering issue, i think you should enable this feature in your firewall.
Answer: Using IIS predefined rules for FTP and only apply
netsh advfirewall set global StatefulFtp enable

worked for me
Answer: Is FTP enabled for the private or public profile?


Estimating distribution characteristics from characteristics of multiple samples

Question: Definition
Suppose that $X \sim D(\mu, \sigma)$, where $D$ is a 1D distribution (generating from $\mathbb{R}$) with mean $\mu$ and stddev $\sigma$.
If I sample $X$ (the random variable) $M\times N$ times, receiving a matrix $A$ (with $M$ rows and $N$ columns), then generate

a vector $V_\mu$ from $A$ by reducing each row of $A$ to a single value by calculating the mean of that row, and

a vector $V_\sigma$ from $A$ by reducing each row of $A$ to a single value by calculating the biased standard deviation of that row from the mean --> single number of $V_\sigma = \sqrt{\frac{1}{N}\sum_{i=0}^{N}(x_i - \overline{x})^2}$,

how do I properly estimate the original $\mu$ and $\sigma$ from $V_\mu$ and $V_\sigma$? It's clear that the estimate of $\mu$ is just the mean of $V_\mu$, but how do I handle the $\sigma$?
Sigma
I've tried experimenting, deciding that, for starters, let's assume that $D = \mathcal{N}$ and $X \sim \mathcal{N}(\mu=3, \sigma=5)$. I generated $A$, computed unbiased $\sigma(A)$ and then reduced $A$ to $V_\sigma$, from which I calculated the mean. This is the result:

Obviously, the result is biased, the estimate undershoots the true $\sigma$ more often than not. If I instead multiply each member of $V_\sigma$ by $\frac{N}{N-1}$ before calculating the mean of $V_\sigma$, I get:

which overshoots the true $\sigma$ more often than not, so I'm really at a loss here. I've also tried multiplying $V_\sigma$ by $\frac{MN}{MN-1}$ instead, but this yields

which is slightly better than the original, but still heavily biased.
EDIT: Thanks to Ryan for pointing out my mistake, of course, I forgot to square root the correction factor. Still, I had no idea that the $c_4$ factor should be taken into account as well. By multiplying the mean of $V_\sigma$ by $\sqrt{\frac{N}{N-1}}$ and also by $1/c_4(M)$, I've obtained:

which is unbiased, but distributed more uniformly (with larger standard deviation).
Mu
The mean estimate is good, as expected:

Question
After everything that I've shown, what I wonder is this:

Given $D = \mathcal{N}$, what are these distributions I'm observing? They look normal, but aren't they t? EDIT I know now that the distribution for mean estimate, if we subtract the true $\mu$, is a $t$ distribution with $N-1$ degrees of freedom.

SOLVED COMPLETELY Given $D = \mathcal{N}$, how do I correct the $\sigma$ estimate from $V_\sigma$? EDIT: answered by Ryan, see Sigma section.

Given $D = \mathcal{N}$, after I correct the $\sigma$ estimate, is it okay to claim that $D$ is probably $\mathcal{N}(\mu, \sigma)$? Certainly, the larger $M$ and $N$ get, the more confident I can be while claiming such a fact, right? What is the proper statistical procedure I should execute after I get my estimate of $\mu$ and $\sigma$? For example, according to my experiment, I can see that the $\mu$ estimate falls into $[2, 4]$ about 95% of the time. EDIT: I know now that if I generate the interval as $\overline{x} \pm 1.96 \cdot \sigma \cdot \sqrt{N}$, the interval will contain $\mu$ 95% of the time. But what about $\sigma$? And when I finally settle on some interval estimates of $\mu$ and $\sigma$, can something about $P(X > c), X \sim \mathcal{N}(...)$ be said?

Can this problem be solved for general $D$, that is, obtain $V_\mu$ and $V_\sigma$ from a bunch of samples ($M\times N$ to be specific) and conclude something about the true $\mu$ and $\sigma$?
Answer: Welcome to CV!
(1) Sampling Distribution of Sample Statistics
Given $D = \mathcal{N}$, what are these distributions I'm observing? They look normal, but aren't they t?
a) Sample mean $\bar{X}$
$\frac{\bar{x}-\mu}{S/\sqrt{n}}\sim t_{n-1}$ - t distribution with $n-1$ degrees of freedom.
b) Sample variance $S^2$
$\frac{(n-1)}{\sigma^2}S^2 \sim\chi^2_{n-1}$ chi-squared distribution with $n-1$ degrees of freedom (see Sampling Distribution of Sample Variance)
c) Sample standard deviation $S$
$\sqrt{\frac{(n-1)}{\sigma^2}}S \sim\chi_{n-1}$ - chi distribution with $n-1$ degrees of freedom. This follows from the fact that if $X\sim \chi(n)$ then $X^2\sim \chi^2(n)$ (see Wikipedia: Chi Distribution)
(2) Unbiased Estimate of Population $\sigma$
Given $D = \mathcal{N}$, how do I correct the $\sigma$ estimate from $V_\sigma$?
The sample variance with Bessel's correction ($\tfrac{n}{n-1}$) provides an unbiased estimate for the population variance. Two reasons that statement doesn't help you.

You are applying Bessel's correction $\frac{n}{n-1}$ to the sample standard deviation. In fact, you would want to multiply the sample standard deviation by $\sqrt{\frac{n}{n-1}}$ to apply the correction.
Even then, you will not get an unbiased estimate of the sample standard deviation. The corrected variance is unbiased, but the square root of that value is not an unbiased estimate of population standard deviation. See Wikipedia and related question. In the case where $D = \mathcal{N}$, there is a correction factor ($c_4(n)$) you can apply. It is discussed in the wikipedia article linked above. For the case where $n=10$, the correction looks like $c_4(10)= \left(\frac{128}{105}\sqrt{\frac{2}{\pi}}\right)\approx 0.9726592741$.

In general, an unbiased estimate for the population standard deviation where $D = \mathcal{N}$ is given by
$$\hat{\sigma}=\frac{1}{c_4(n)}\sqrt{\frac{\sum_{i=1}^N(x_i-\bar{x})^2}{N-1}}$$
Here is a quick plot to show the difference in the estimated standard deviation using the two corrections on samples from a normal distribution as well as Python code to reproduce the plot.

from math import gamma
import seaborn as sns
import pandas as pd

SIGMA = 5
MU = 3
m = 10000
# calculate correction
def c4(n):
    return np.sqrt(2/(n-1)) * gamma(n/2) / gamma((n-1)/2)

# calculate statistics for various N
results_dict = {x:[] for x in ['N','correction','s']}
for N in range(3, 25):
    A = np.random.normal(loc=MU, scale=SIGMA, size=[m,N])
    df_i = pd.DataFrame()
    results_dict['N'] += [N]*m*3
    results_dict['correction'] += ['None']*m+['Bessel']*m+['Bessel + c4']*m
    results_dict['s'] += list(np.std(A, axis=1))
    results_dict['s'] += list(np.std(A, axis=1)* ((N/(N-1))**0.5) )
    results_dict['s'] += list(np.std(A, axis=1)* ((N/(N-1))**0.5) / c4(N))

# create dataframe
results_df = pd.DataFrame(results_dict)

# plot results
plt.figure(figsize=(8,6))
sns.pointplot(
    data=results_df,
    x='N',
    y='s',
    hue='correction',
    ci=None
)
plt.title("Comparison of statistics for estimating $\sigma$")
plt.axhline(5, c='k', linestyle='--', label= "$\sigma$")
plt.show()

(3) Confidence Intervals - Normal
Given $D = \mathcal{N}$, after I correct the $\sigma$ estimate, is it okay to claim that $D$ is probably $\mathcal{N}(\mu, \sigma)$? Certainly, the larger $M$ and $N$ get, the more confident I can be while claiming such a fact, right? What is the proper statistical procedure I should execute after I get my estimate of $\mu$ and $\sigma$? For example, according to my experiment, I can see that the $\mu$ estimate falls into $[2, 4]$ about 95% of the time.
You of course can't say that $D$ is probably exactly $\mathcal{N}(\bar{X}, S)$ but you can construct confidence intervals for $\mu$ and $\sigma$.
As an aside, the maximum likelihood estimator for the variance is actually the uncorrected version $s^2=\frac{1}{N}\sum_{i=1}^N(X_i-\bar{X})^2$ (see MLE Biased). This is regardless of the fact that the uncorrected estimate tends to underestimate the true value. And if $S^2$ is the MLE estimate for $\sigma^2$ then $\sqrt{S^2}=S$ is the MLE estimate for $\sqrt{\sigma^2}=\sigma$ (see Maximum Likelihood Estimation) We can also see, using our simulation, that the average squared difference between our estimate $S^2$ and the population variance $\sigma^2$ is lowest for the uncorrected estimate.

# Variance
results_df['s2'] = results_df['s']**2
# Variance error
results_df['s2_mse'] = (results_df['s2']-SIGMA**2)**2

plt.figure(figsize=(8,6))
sns.pointplot(
    data=results_df,
    x='N',
    y='s2_mse',
    hue='correction',
    ci=None
)
plt.ylabel("$(S^2-\sigma^2)^2$")
plt.title("Squared Error of statistics for estimating $\sigma^2$")
plt.axhline(5, c='k', linestyle='--', label= "$\sigma$")
plt.show()

You can construct the following confidence intervals for your sample statistics.
a) Population mean $\bar{X}$
A $(1-\alpha)%$ confidence interval for the population mean is
$$\left(
\bar{X}-\frac{S}{\sqrt{n}}t_{n-1,\alpha/2}
\leq
\mu
\leq
\bar{X}+\frac{S}{\sqrt{n}}t_{n-1,\alpha/2}
\right)$$
see: Confidence Intervals with σ unknown
b) Population variance $\sigma^2$
A $(1-\alpha)%$ confidence interval for the population variance is
$$\left(\frac{(n-1)s^2}{\chi^2_{\alpha/2,n-1}}
\leq
\sigma^2
\leq
\frac{(n-1)s^2}{\chi^2_{1-\alpha/2,n-1}}
\right)$$
(see Confidence Intervals for Variances)
c) Population standard deviation $\sigma$
A $(1-\alpha)%$ confidence interval for the population standard deviation is
$$\left(\sqrt{\frac{(n-1)s^2}{\chi^2_{\alpha/2,n-1}}}
\leq
\sigma^2
\leq
\sqrt{\frac{(n-1)s^2}{\chi^2_{1-\alpha/2,n-1}}}
\right)$$
See Confidence Intervals for Variances again or this related question
(4) General Case
Can this problem be solved for general $D$, that is, obtain $V_\mu$ and $V_\sigma$ from a bunch of samples ($M\times N$ to be specific) and conclude something about the true $\mu$ and $\sigma$?
@Ben's answer seems most relevant to this question. A similar procedure you may be able to apply in the general case and avoid any analytical computation is to utilize the bootstrap. You can certainly use the bootstrap procedure to estimate the distribution of the sample mean, but I am not sure how well it applies to estimating sample variance. I'm not finding a lot of specific discussion on this question, but this thesis seems to discuss the issue in depth. Evaluation of Using the Bootstrap Procedure to Estimate the Population Variance
Comment: Wow, that's so cool! Thank you very much Ryan, I'm checking the articles and updating my code.
Answer: Your notation for this problem is problematic, so I am going to use a different notation for the same thing.  I will denote the vector of subsample means as $\bar{\mathbf{x}} = (\bar{x}_1, ..., \bar{x}_M)$ and $\mathbf{s} = (s_1,...,s_M)$.  I also note that each subsample is of size $N$, so each of the elements of these vectors uses $N$ data points.

Since the values in your initial $M \times N$ matrix are IID values with mean $\mu$ and standard deviation $\sigma$, the best thing to do here is just to pool the $M$ subgroups into a single sample of size $MN$ and use this to estimate the mean and standard deviation parameters.  If you are willing to use the original data in your matrix, this problem is fairly simple --- you just compute the overall sample mean and sample standard deviation and use standard estimation methods for the parameters.  However, if you particularly want to start from the vectors $\bar{\mathbf{x}}$ and $\mathbf{s}$ for the subgroups, you can use mathematical rules for pooling subgroup moments to get the overall sample mean and sample standard deviation without using the underlying data values (see below for how to do this in R).
In the case where your initial data is IID normal data, the sample mean follows a normal distribution and the sample standard deviation follows a scaled chi distribution.  This is true both for the subgroup sample moments and the overall pooled sample moments.  In the more general case where you don't assume normality of the underlying values (but you assume finite kurtosis), the central limit theorem applies and you get similar distributions, though the latter may be adjusted for kurtosis (see e.g., here).
There are well-known confidence interval formulae for the true mean and standard deviation parameters given the sample mean and sample standard deviation (and maybe also the sample kurtosis).  You can find derivation of the confidence intervals for the mean and variance, plus some related information on moments, in O'Neill (2014).  (Note that this particular paper gives a confidence interval for the variance/standard deviation that takes account of the kurtosis of the population, either through a known kurtosis parameter or the sample kurtosis of the data; other sources give a simpler formula that implicitly assumes mesokurtosis of the underlying data.)

Computing pooled sample moments from subgroup moments: Computing the sample moments for pooled datasets composed of subsamples has been automated in the sample.decomp function in the utilities package (see package documentation).  This function can compute pooled sample moments from subgroup moments up to fourth order (i.e., up to sample kurtosis).  Here we give an example where we use the function to compute the sample moments of the pooled sample for $M=6$ subgroups each composed of $N=200$ standard normal data points.  As you can see from the code below, we input the sample sizes, sample means and sample standard deviations into the function, and then compute the moments of the pooled sample.
#Show sample statistics for the subgroups
library(utilities)
N      <- c(200, 200, 200, 200, 200, 200)
MEAN   <- c(0.0556434, 0.0153109, 0.0722623, 0.1211588, 0.0152080, 0.0801092)
SD     <- c(0.9977933, 0.9315480, 1.0310567, 1.0109557, 0.9731961, 0.9554002)

#Compute sample decomposition
sample.decomp(n = N, sample.mean = MEAN, sample.sd = SD, include.sd = TRUE)

              n sample.mean sample.sd sample.var
1           200  0.05564340 0.9977933  0.9955915
2           200  0.01531090 0.9315480  0.8677817
3           200  0.07226230 1.0310567  1.0630779
4           200  0.12115880 1.0109557  1.0220314
5           200  0.01520800 0.9731961  0.9471106
6           200  0.08010920 0.9554002  0.9127895
--pooled-- 1200  0.05994877 0.9825550  0.9654142


Disparar função apenas quando os dados do form estiverem todos preenchidos

Question: Criei um form do tipo radio, que ao preenchido as alternativas, ao clicar no botão de submit, ele envia os dados do form via AJAX para a página PHP aplicar a lógica de quantas questões foram acertadas. O botão ao clicado gera uma div por popup com o retorno da lógica do PHP, exibindo quantos acertos foram realizados. Porém ao clicar no botão mesmo sem preencher todos os radios, ele gera a div vazia na tela. Os campos todos estão com required.

DESCUBRA

SE VOCÊ TEM DTM

<form action="" method="post" id="questionario">

Sente dificuldade para abrir a boca?

        <input type="radio" name="questao1" id="questao1-1" value="Sim" required> Sim
        <input type="radio" name="questao1" id="questao1-2" value="Não" required> Não

Sente dificuldade para movimentar a mandíbula para os lados?

        <input type="radio" name="questao2" id="questao2-1" value="Sim" required> Sim
        <input type="radio" name="questao2" id="questao2-2" value="Não" required> Não

<button type="submit" value="Enviar" style="background:#690d2e; color:white; font-weight: 600" class="btn" onsubmit="document.getElementById('modal-wrapper1').style.display='block'">GERAR RESULTADO</button>
</form>

Comment: sua pergunta não está bem claro quanto ao problema, mas quer enviar só com os campos preenchidos, seria interessante validar o form antes, por exemplo usando a [função valid() do jquery](https://jqueryvalidation.org/valid/)
Comment: Uma opção é desabilitar o botão do submit com `disabled` e só habilitar depois de preencher os radio buttons. Resolveria assim?
Answer: Tem coisas a melhorar no seu código.
Primeiro é que você não precisa colocar required em todos os radios. Basta colocar em apenas 1 dos que tiverem o mesmo name, por exemplo:
<input type="radio" name="questao1" id="questao1-1" value="Sim" required> Sim
<input type="radio" name="questao1" id="questao1-2" value="Não"> Não

Veja que foi colocado apenas no radio "Sim". Isso irá obrigar a marcar uma das duas opções, pois ambas possuem o mesmo name.
Também não precisa colocar onsubmit no botão de submit. Você já tem um event handler .submit() e pode mostrar a div lá dentro.
E em vez de usar window.onclick= function(event){ para esconder a modal, você pode simplesmente usar o método .one("click", function...) para isso. Esse método habilita o clique na div apenas uma vez, ou seja, quando o AJAX entrar no success a modal está habilitada para receber um clique e se esconder:
success: function( data )
{
   $("#div1").html(data);
   $("#modal-wrapper1").one("click", function(){
      $(this).hide();
   });
}

Também não utilize
 entre as divs para dar espaçamento. É incorreto. Você pode usar padding ou margin para isso no seu CSS.
O código completo ficará assim:
jQuery(document).ready(function(){
   jQuery('#questionario').submit(function(){
      $("#modal-wrapper1").show(); // mostra a modal
      var dados = jQuery( this ).serialize();

      jQuery.ajax({
         type: "POST",
         url: "teste.php",
         data: dados,
         success: function( data )
         {
            $("#div1").html(data);
            $("#modal-wrapper1").one("click", function(){
               $(this).hide(); // esconde a modal ao ser clicada
            });
         }
      });
      return false;
   });
});

HTML:

DESCUBRA

SE VOCÊ TEM DTM

      <form action="" method="post" id="questionario">

Sente dificuldade para abrir a boca?

               <input type="radio" name="questao1" id="questao1-1" value="Sim" required> Sim
               <input type="radio" name="questao1" id="questao1-2" value="Não"> Não

Sente dificuldade para movimentar a mandíbula para os lados?

               <input type="radio" name="questao2" id="questao2-1" value="Sim" required> Sim
               <input type="radio" name="questao2" id="questao2-2" value="Não"> Não

         <button type="submit" value="Enviar" style="background:#690d2e; color:white; font-weight: 600" class="btn">GERAR RESULTADO</button>
      </form>


Query to a List of dictionaries, return the specific dictionary?

Question: I pushed a db as simple as, using python, pymongo and mnogodb, the db is mae of many files like the sample below:
<code>  def pushdata():
        for filename in os.listdir(directory):
                with open( directory + filename , 'r') as f:
                    datastore = json.load(f)
                    m = data.insert_one(datastore)
</code>
My jsons loook like that
<code>  {
            "info": {
                "S1": {
                    "SS": "1221"
                },
                "S2": {
                    "SDS011": "5121"
                },
                "OP": "157.138",
                "LK": "32121",
                "MN": "122.077"
            },
            "readings": [
                {
                    "SS1": "7.80",
                    "SS2": "1.80",
                    "timestamp": "1530857160"
                },
                {
                    "SS1": "9.67",
                    "SS2": "2.53",
                    "timestamp": "1530857520"
                },
            ]
        }
</code>
how can i query the data? When i try
<code>  print(data.find_one({'$and':[{ "readings.SS1": "7.80"},
                {"readings.SS2": "1.80"}]}))
</code>
in python
<code> print(data.find_one( "readings.SS1": "7.80"}))
</code>
in mongodb
I always get the whole Database file  not the specific dictionary from the list? Why does it happen? I want query response like that:
<code>   {
                "SS1": "7.80",
                "SS2": "1.80",
                "timestamp": "1530857160"
            }
</code>

also for the info dictionary, how to make a query where let say 'OP'=157.138 and 15500000< timestamp < 15000000 , response:
<code>  {
        "SS1": "7.80",
        "SS2": "1.80",
        "timestamp": "15100000"
    }
    {
        "SS1": "7.80",
        "SS2": "1.80",
        "timestamp": "15300000"
    }
    {
        "SS1": "7.80",
        "SS2": "1.80",
        "timestamp": "15500000"

   }
</code>
Answer: You can use an aggregation like below:
<code>db.collection.aggregate([
  {$unwind: "$readings"},
  {$match: {"readings.SS1": "7.80"}},
  {$replaceRoot: {newRoot: "$readings"}}])
</code>
Which returns:
<code>[
  {
    "SS1": "7.80",
    "SS2": "1.80",
    "timestamp": "1530857160"
  }
]
</code>


What is the floppy drive data cable called?

Question: I'm talking about the 3.5" floppy drive. I did some research but could not come up with the proper name. What I know is that it uses a ribbon cable with a 34-pin variant of the 40-pin IDE, but it's not called an IDE? The term IDE seems to always refer to the 40-pin so I'm a bit confused.
If I posted this in the wrong site, please refer me to the correct one.
Comment: Everyone I know always called them "floppy drive cables" to distinguish them from the wider hard drive cables.
Comment: @people-who-closed-my-queestion: How is my question not related to servers? Also, if you're closing, would you kindly refer me to the site I'm suppose to use?
Answer: it looks like but actually not an IDE cable. it is described in detail here: http://www.interfacebus.com/PC_Floppy_Drive_PinOut.html
I still have one if you really need it :-)
thanks to Chris McKeown for pointing out my mistake.
Comment: Forgive me if I've missed something, but that link is referring to an IDC (insulation displacement connnector) cable, rather than an IDE cable specifically. Although an IDE cable is also an IDC cable, IDE refers to the fact that the drive controller hardware is on the drive itself rather than on the host system, not how the cable is physically constructed.
Comment: um, i think you are right. i have seen the floppy cables referred to as EIDE cable so assumed that they are IDE, which I thought is just an interface specification. this link makes the distinction clearer: http://www.kitchentablecomputers.com/drcables1.php
Comment: Thanks, john. However, not even that article says that it is an IDE but I'm gonna go with Chris' definition of the word IDE and simply call it a 34-pin IDE instead of simply IDE.
Comment: yeah, Chris was right. I fixed the answer based on his feedback. I just always thought it was IDE :-)
Comment: I'll accept your answer, wish I could up-vote though but don't have enough rep on this stack exchange site.
Comment: @Err - It's probably incorrect to refer to the cable as a 34-pin IDE. Floppy drives do not have their controller hardware onboard and therefore can't be referred to as IDE devices. Probably more correct to refer to it as a 34-pin IDC cable (or an IDC34 as some sites seem to refer to them)


Dynamically configuring subdomains based on folder structure using Apache's VirtualHost

Question: What I want to do is have dynamically created virtualhosts based on a username and subfolder, for example if I were to create the following folder:
/home/USER/www/PROJECT_FOLDER

The following domain will be mapped to the previous folder as its webroot
http://PROJECT_FOLDER.USER.domain.com

Aside from creating a script that checks for new folders, creating the matching VirtualHost in the Apache configuration, and restarting HTTPD, is there a config-friendly method of accomplishing this?
-- EDIT --
Thank you @kashani for suggesting mod_vhost_alias. It worked perfectly.
Answer: You might want to look into mod_vhost_alias. http://httpd.apache.org/docs/2.2/mod/mod_vhost_alias.html
The config in your case should look like this, though I haven't tested it.
VirtualDocumentRoot /home/%2/www/%1

and for logging
LogFormat "%V %h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"" dynamic_vhosts
CustomLog logs/access_log dynamic_vhosts

That'll put the vhost the request came into at the front of each log entry. You can adjust the rest of the setting to match what you need. If %V doesn't work, try %v. I don't believe there is a way to split out into separate log files at least with the standard Apache mod_log.
Comment: Thanks @kashani! After working with mod_vhost_alias for a while, that seemed to do the trick! My only concern now is if the project_folder directory has capital letters in it the apache usually translates http://EXAMPLE.username.domain.com as "example.username.domain.com" when in fact the directory may be "/home/username/www/EXAMPLE"
Comment: I can't think of a way to solve that one, but glad to hear mod_vhost_alias worked out for you.
Comment: One more semi-related question. Is there any way to also have virtual mapping of error and access logs using mod_vhost_alias?
Comment: put the logging in the answer for better formating.
Comment: @Workman, mod_speling might help with the case sensitivity of the folders. But I've never used it in conjunction with mod_vhost_alias: http://httpd.apache.org/docs/2.2/mod/mod_speling.html
Answer: With "ServerAlias *.example.com" and the Virtual User Hosts RewriteRule example, I believe you can easily setup apache to do what you wish
http://httpd.apache.org/docs/2.2/rewrite/rewrite_guide.html#uservhosts
Comment: Can you do this with local hostnames as well?

Such as PROJECT_FOLDER.USER.dev (where 'dev' is the name of the machine)?


Solving a linear system of equations use row operations

Question: Can somebody help me find the simplest way to use elementary operations of multiplying one row by another and scalar multiplication of a row to find the solution to the system of equations?
$$2x_1+4x_2-x_3=7$$ $$x_1+x_2-x_3=0$$ $$3x_1-2x_2+3x_3=8$$
Every time I solve this it feels like it could have been done simpler... Thanks!

My attempt:
I first exchanged row 1 and row 2  to get:
$$x_1+x_2-x_3=0$$ $$2x_1+4x_2-x_3=7$$ $$3x_1-2x_2+3x_3=8$$
Then I did $-2R_1+R_2 \rightarrow R_2$ and $-3R_1+R_3 \rightarrow R_3$ to get:
$$x_1+x_2-x_3=0$$ $$0x_1+2x_2+x_3=7$$ $$0x_1-5x_2+6x_3=8$$
But now I can't use row 2 to eliminate the $x_2$ in row 3 without introducing fractions. I realize i could use back substitution, but I want to use row operations. Was there a different way I could have carried out the row operations to make this nicer? Thank you!
Comment: It is all right if your equation coefficients are fractions.
Answer: What you can do is multiply rows by nonzero constants. For instance $5R_2 \to R_2$ and $2R_3 \to R_3$. Then you can cancel the $x_2$ term in the last equation without getting a fraction in the coefficients. Of course, if there are fractions in the right-hand side, we cannot avoid those.


How to avoid duplicate scale-in with step scaling policy?

Question: With EC2 auto scaling, when using a step scaling policy (as opposed to a simple scaling policy) that scales in due to an alarm that is based on an AWS/EC2 metric (e.g. CPUUtilization <= 30%) with detailed CloudWatch monitoring disabled, when my auto scaling group scales in, it scales in two instances in short succession, without waiting for the metric to update. How can I prevent the auto scaling group from scaling in too fast for the metric to update?

Edit: here was last night's scaling history. At 5:15, 5:17, 5:19, 5:21 UTC, auto scaling scaled in due to low CPU Utilization, even though CPU Utilization only has data points at 5:10, 5:15, 5:20, and the scaling event should have ceased after the 5:15 datapoint. There appears to be no way to adjust the cooldown duration of step scaling policy scale ins (step scaling policies ignore the Default Cooldown (=600s) and only scale out policies have estimated instance warmup).
Answer: I had exactly the same problem. What i ended up doing was changing my scale down policy to SimpleScaling reducing by one instance at a time and setting a 10m cooldown. I've also changed my scale down alarm condition to trigger when there are 10 periods of 60 seconds below my threshold of 35% CPU. ( I have detailed cloudwatch metrics enabled ) The idea being that as soon as a scale down occurs then the alarm will turn off faster than if there was fewer periods and a longer evaluation time.
I've still got StepScaling to go up so I scale up fast, but with SimpleScaling and a cooldown to scale in I scale down much more slowly.
Answer: You'll want to adjust your autoscaling cooldown settings. By default, it's five minutes, but you can customize it in the console or via the API/CLI with PutScalingPolicy.
Comment: Isn't the cooldown period only for simple scaling policies? The documentation states, "Cooldown periods are not supported for step scaling policies or scheduled scaling."
Comment: @yonran Step scaling policies appear to have a cooldown setting as well. See https://media.amazonwebservices.com/blog/2015/as_create_stepped_group_5.png
Comment: Only scale out step scaling policies support estimated warm-up time. Scale in step scaling policies don't. I have added screen shots from last night that show gradual scale outs but rapid scale ins.
Comment: I believe there is only a "warm-up" setting for step-scaling when you add more instances, but no cooldown during removal.


Alexandru posted 2 duplicate questions

Question: I don't know how to edit them because they each have answers. I think How is monetary policy sustainable, or even fair, in the current economy? should be shortened?
Alexandru's question at How is monetary policy sustainable, or even fair, in the current economy?, numbered

1 = How is monetary policy fair in the current economy?.
2 =  Who regulates the balancing of the books for commercial banks and how is this done? Is it public information?.
Answer: I don't quite understand your question here. The two questions are not duplicates, though the asker draws from the same material, and even if they were, one of the questions are closed, so you would only need to deal with the second one.
If you are asking how to edit the first one so it can be re-opened, honestly I would say don't. Both of these questions are 5 years old, and the first one is a litany of many many questions that could each be a separate question. Trying to edit the first question to be re-openable would require really substantially changing the question from the original author's intent, so I'd say it's up to that user specifically to edit the question if they desire (I do not think they want to).
Comment: Alexandru asked the same question in three posts.

Alexandru posted 2 duplicate questions


Import Excel data to Python for generating a heatmap

Question: I would need some help! By now i used this short code to design a map with folium:
pyton_folium_test.txt
The next step for me is to learn how to import positions like this from an excel file, but here i got stuck the last two days. I tried to do the import with pandas, xlrd and also OPENPYXL, but i dont fit to the end. Am i right here to find help for it? can someone help me with that?
Excel below will be an example file to import and the screenshot is how the result should look like.
Eingabe_Python.xlsx

<code>#Allgemeine Weltkarte
import pandas as pd
import geopandas
import matplotlib.pyplot as plt

##GPS-Daten und Werte
#Hüttensand-Quellen
q = pd.DataFrame(
    {'City': ['Voestalpine Donawitz'],
     'Amount': [150000],
     'Latitude': [47.37831193777984],
     'Longitude': [15.066798524137285]})

gq = geopandas.GeoDataFrame(
    q, geometry=geopandas.points_from_xy(q.Longitude, q.Latitude))

print(gq.head())

#Hüttensand-Bedarf
b = pd.DataFrame(
    {'City': ['Retznei-Zementwerk', 'Peggau-Zementwerk'],
     'Amount': [ 98741, 78908],
     'Latitude': [ 46.74156539750959, 47.22606763599665],
     'Longitude': [ 15.574118966270278, 15.346740145512106]})

gb = geopandas.GeoDataFrame(
    b, geometry=geopandas.points_from_xy(b.Longitude, b.Latitude))

print(gb.head())

#Plot Österreich Karte mit Punkten
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))

ax = world[world.name == 'Germany'].plot(
    color='white', edgecolor='black')

gq.plot(ax=ax, color='red', legend=True, legend_kwds={'label':'City'})
gb.plot(ax=ax, color='blue')

plt.show()

#Heatmap
import folium
from folium.plugins import HeatMap

max_amount = float(gb['Amount'].max() and gq['Amount'].max())
print('der maximale Wert ist:',max_amount)

hmap = folium.Map(location=[47.070714, 15.439504], zoom_start=8,control_scale=True )

hm_quellen = HeatMap( data=gq[['Latitude', 'Longitude','Amount']],
                   min_opacity=0.3,
                   max_val=max_amount,
                   gradient = {.3: 'yellow', .6: 'orange', 1: 'red'},
                   radius=20, blur=10,
                   max_zoom=5,

                 )

hmap.add_child(hm_quellen)

hm_bedarf = HeatMap( data=gb[['Latitude', 'Longitude','Amount']],
                   min_opacity=0.3,
                   max_val=max_amount,
                   gradient = {.3: 'turquoise', .6: 'blue',  1: 'grey'},
                   radius=20, blur=15,
                   max_zoom=1,
                 )

hmap.add_child(hm_bedarf)

#Markierungen
# Quellen
folium.Marker([47.37831193777984, 15.066798524137285],
              popup=folium.Popup('integrierte Hüttenwerk - Donawitz',show=True)).add_to(hmap)

# Bedarf
folium.Marker([46.74156539750959, 15.574118966270278],
              popup=folium.Popup('Zementwerk - Retznei',show=True)).add_to(hmap)

folium.Marker([47.22606763599665, 15.346740145512106],
              popup=folium.Popup('Zementwerk - Peggau',show=True)).add_to(hmap)

#karte speichern
import os
hmap.save(os.path.join(r'C:\Users\stefa\Desktop\Bachelorarbeit\Daten_Python', 'zement_heatmap.html'))
</code>
Comment: is there someone who can help a beginner like me?
Comment: Do you have any control over the format of the Excel file? If each town/region (?) eg Quelle, Bedarf were on a separate worksheet and the headers were just Name,Latitude etc then this would make life a lot easier. Then pandas has a very handy read_excel function which will return a dictionary of data frames: https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html It might be worth doing some pre-processing on the Excel data before importing.
Comment: Hi, yeah  by now i have full control of the excel, just tell me how it should best look like for easy working with it (i am much better in organising excel than in programming). You mean every town on a seperate sheet in the excel? if this will prepare it best, i would try it
Answer: A possible full solution. I have split out the data acquisition as a separate task from the data display. Since each one of the 'groups' (Quelle, Bedarf etc) has a different colour scheme, I've added a dictionary to hold this information (this could come from a separate configuration file).
Since I don't have GeoPandas (the installation is not simple on Windows), I have commented those lines out: they should work, but I cannot test.
<code>import pandas as pd
#import geopandas
#import matplotlib.pyplot as plt
import folium
from folium.plugins import HeatMap

def LoadData(filename):
    #Read in 1st sheet of Excel file
    dfLocations = pd.read_excel(filename)

    GroupData = {}
    fields = []
    max_amount = 0.0

    #Run through the column headers
    #to extract all the unique field names and groups
    for hdr in dfLocations.columns:
        parts = hdr.split('_')
        if( len(parts) ) > 1: #column names not in Field_Group format
            if( parts[0] not in fields ):
                fields.append(parts[0])
            GroupData[parts[1]]=None

    #Now parse the data, group by group
    for r in GroupData:
        df = dfLocations[[ fld + '_' + r for fld in fields]].dropna().set_axis(fields, axis=1, inplace=False)
        df.rename(columns={'Name':'City'},inplace=True)
        max_amount = max(max_amount,df.Amount.max())
        GroupData[r] = df

    return GroupData,max_amount

dictGroups,max_amount = LoadData('ImportFile.xlsx')

#Set up colour schemes for plot, markers and heatmaps
#NB: need one line for every different group
colourScheme = [{'loc': 'red','heatmap': {.3: 'yellow', .6: 'orange', 1: 'red'},'radius':20,'blur':10 },
                {'loc': 'blue','heatmap': {.3: 'turquoise', .6: 'blue',  1: 'grey'},'radius':20,'blur':15}]

if len(colourScheme) < len(dictGroups):
    raise ValueError('Insufficient Colour Scheme entries for the number of Groups')

#world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
#ax = world[world.name == 'Germany'].plot(color='white', edgecolor='black')

hmap = folium.Map(location=[47.070714, 15.439504], zoom_start=8,control_scale=True )

nGroup = 0
for r in dictGroups:
    dfLocations = dictGroups[r]
    scheme = colourScheme[nGroup]

    #gdf = geopandas.GeoDataFrame(dfLocations, geometry=geopandas.points_from_xy(dfLocations.Longitude, dfLocations.Latitude))
    #gdf.plot(ax=ax,color=scheme['loc'],legend=True,legend_kwds={'label':'City'})

    hmap.add_child(HeatMap( data=dfLocations[['Latitude', 'Longitude','Amount']],
                            min_opacity=0.3,
                            max_val=max_amount,
                            gradient = scheme['heatmap'],
                            radius=scheme['radius'], blur=scheme['blur'],
                            max_zoom=5 ) )

    for idx,location in dfLocations.iterrows():
        folium.Marker([location.Latitude,location.Longitude],
                      popup = folium.Popup(location.City,show=True)).add_to(hmap)
    nGroup += 1

#plt.show()
hmap.save('zement_heatmap.html')
</code>
Comment: @bose No worries. SO is not a coding service though: perhaps take some time to understand how the code works and you may not need more help!
Comment: wow this looks really helpfull, thanks! if i have my code so far, how can i easily use this result to fit it into code somehow like i did previously to plot my map like the example?
Comment: @bose I don't have the geopandas package so can't test that part. Take some time to look through the code I've posted, and understand how it works. That will give you the insight on how to use the imported DataFrame.
Comment: @bose I've posted a fuller answer
Comment: oh thank u a lot, this looks so great, you helped me a lot. i will try it and if i still have problems i will contact you again but thankyou very much ba now
Comment: wow thank you very much, it worked perfectly!! so by now this is all i need, if i get some more stuff i need to display i will maybe ask you again for help, if itis okay? @DS_London
ps: sorry btw for my maybe not so good english
Comment: yeah i know, i try my best for future issues, i would not have come here if i did not see myself lost after few days of trying to solve it myself :O


can't allocate region malloc

Question: I am getting this error causing my app to crash:
<code>..Splash-it(1369,0x5783000) malloc: *** mmap(size=516096) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
</code>
I have no idea why the error is caused. Is it a memory problem error? How can I prevent it?
What do they mean by "set a breakpoint in malloc_error_break to debug"?
Thanks for any answers.
Comment: How much memory your application uses? On which device? Did you receive memory warning before this?
Comment: the new ipad, and no i didn't receive any memory worning
Comment: Take a look at http://stackoverflow.com/questions/8477236/malloc-error-cant-allocate-region-failed-with-error-code-12-any-idea-how-to for some ideas.
Answer: In my case i was getting this because imgCount is not getting value as my condition fails.
And the non void function is returning the value of imgCount.
<code>- (NSInteger)collectionView:(PSUICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger imgCount;
    if(collectionView == self.imageCollection) {
        imgCount=self.imageCount;
    }
    return imgCount;
}
</code>
So i resolved it by assigning the value to imgcount.
It works for me.
Comment: This answer helped me by realizing i was just referencing a array for the count instead of array.count , thank you!!!
Answer: Chances are that you are trying to allocate too much memory at once. I tried to malloc crazy big amounts of memory, and I got this error.
Answer: Not sure but this is waht happened in my case & I resolved by removing breakpoint.
I was loading data from server & adding them to tableview & hiding or showing footer. At times my footer view was not appearing as I wanted so I inserted the breakpoints to check out whats going wrong. But then after some time doing the same activity my app got above error.
I tried this 2-3 times without breakpoint & it did not crash but, whenever I added breakpoint the error occured.
This may not be in your case but I guess if you are doing some large operations on main thread & if you have inserted breakpoints, you can atleast try this once.
Comment: By removing thebreakpoints you mean removing all by the-selecting the breackpoint button on the top bar? Is it ok if I leave them in the code itself?
Comment: I mean try to run your code by disabling breakpoint from you Xcode toolbar. See if it works.
Comment: I had them disabled even before, sorry

can't allocate region malloc


Ruby Benchmarking a line that runs multiple times

Question: Suppose I have a script that's timing out, and I want to see where it's spending most of its time.  I know I can benchmark any given line of code, but my understanding is that if I do:
Benchmark.measure { test = "a"*1_000_000 }
That it will measure the time it takes every time that line is reached.  But I want to know which parts of my program are causing the slowdown overall, being called multiple times.  Is there an easy way to group lines together across the course of the program for Benchmarking?
Update: Realizing now the proper term here is profiling rather than benchmarking.
Comment: [This](https://stackoverflow.com/questions/4092641/profiling-ruby-code) may be of interest. You may wish to add the tag "profiling".
Comment: @CarySwoveland not sure what Tesla has to do with it, but thank you!
Comment: Do you have the script available to post?  Is it many lines of code? Does it make any external API calls?
Comment: @lacostenycoder No API calls, it's a binary heap implementation
Answer: There are many gems that might help depending on your application but you could try some of these:
https://github.com/flyerhzm/bullet
https://github.com/SamSaffron/memory_profiler
https://github.com/MiniProfiler/rack-mini-profiler
https://github.com/tmm1/stackprof
https://github.com/oozou/ruby-prof-flamegraph
Another crude approach might be to add a Logger and log before and after any line which you suspect might be time consuming.
Let's use ruby-prof-flamegraph example:
Install the gem:
gem install ruby-prof-flamegraph

And the example implementation:
#example.rb

require 'ruby-prof'
require 'ruby-prof-flamegraph'

rubyprof_dir = Gem::Specification.find_by_name('ruby-prof').gem_dir
require "#{rubyprof_dir}/test/prime"

# Profile the code
result = RubyProf.profile do
  run_primes(200)
end

# Print a graph profile to text
printer = RubyProf::FlameGraphPrinter.new(result)
printer.print(STDOUT, {})

To generate the image:
bundle exec ruby example.rb | \
    ~/GitHub/FlameGraph/flamegraph.pl --countname=ms --width=728 > example.svg


Can the installation of a silent system in a grand piano interfere with its performance?

Question: I am thinking of installing a silent sytem on my piano. I have read and talked with some people about it.
Some people have warned me that the installation of such a system can interfere with the weight of the keys, making it harder to play soft.
Can the installation of a silent system interfere with current performance?
Does it make a difference if the silent system comes from factory or not?
Comment: I've never played on one of these but looking at the technology it seems likely that the feel of the piano would change. Ideally you would be able to find a showroom near you where there is a modified demo piano and you can see for yourself. If you have a product in mind I would reach out to their sales or support and ask where you can try it out.
Comment: @ToddWilcox I don't understand because the system is optical. It doenst interfere with the mechanics, or am I missing something?
Answer: Your mileage may vary, of course, but for what it's worth, here are my impressions:
We have a couple of Yamaha silent pianos at our home (ordinary stringed pianos with a MIDI interface: one grand and one upright), as well as a digital keyboard with an ordinary piano action.  It might be a little harder to play soft, but the difference is pretty small, as far as I can tell, compared to the difference between different piano brands.
However, they were installed before we bought them, so my comparison is with the same model without the silent system (at the same store), but not the same actual piano.
Comment: Is the silent base on optical sensors?


DNSCache memory leak on Windows Server 2003

Question: After running for a month or so the svchost.exe that contains the DHCP as well as DNSCache services is showing a Mem Usage of above 400M in task manager. My network interfaces are all static IPs and not running a DHCP server so I'm guessing the usage is from the DNSCache.
Is there any reason that the memory usage for this process should be so high? I still have over a gig of free memory but I don't want to be worrying that if I need a lot of RAM at short notice (which does happen on these servers), that I'll run out. Maybe svchost is smart enough to give memory back under pressure but should I count on that?
From ipconfig /displaydns the cache itself only has around 64 entries so it can't possibly need all that RAM can it?
Edit: I wanted to add a note that while the below answer is useful, it did not fix my problem. My problem is specific to either the DNSCache (dns client) or DHCP (dhcp client) services. The below hotfix is for DNS Server memory leak.
Answer: From: http://msmvps.com/blogs/acefekay/archive/2009/09/03/the-dns-cache-poisoning-vulnerability-microsoft-kb953230-patch-and-ports-reservation-explained.aspx
You will want the hot fix for the hotfix :) http://support.microsoft.com/kb/975830/en-us

DNS Process Memory Leakage After Installing Hotfix 941672 for Windows 2003
If your DNS server is experiencing a large amount of memory being consumed by the DNS process to the point it hangs the DNS service and it stops responding, it may be associated to hotfix 941672. If 941672 was installed on the DNS server,
there is a known memory leak issue in the DNS process associated with this hotfix. The issue has been fixed by installing hotfix patch 975830.

Please read more about it in the following link, where you can also request the hotfix.

The memory usage of the Dns.exe process keeps increasing after you install hotfix 941672 on a computer that is running Windows Server 2003 SP2 and that has the DNS server role installed
Article ID: 975830 - Last Review: October 27, 2009 - Revision: 1.0
http://support.microsoft.com/kb/975830/en-us

DNS Memory Consumption Related Discussion:
http://social.technet.microsoft.com/Forums/en-US/windowsserver2008r2general/thread/bcf3ac92-3485-4a2d-9386-55f2dcbc78f8

If you feel that you need more information to determine if a DNS process leak is occuring, you can enable debug logging, and use the following link in conjunction with the symptoms explained in KB975830 to further analyze the issue. Read the following link for more info.

DNS: Monitoring Server
http://technet.microsoft.com/en-us/library/cc783975(WS.10).aspx
Comment: Looks like this is probably it. I won't be able to really test before bounty is over since takes so long for memory usage to grow. So unless something else comes up I'll accept this answer soon.


Variables in template files

Question: In my .tpl.php template files, I have several links and names of external websites. I would like to print these as variables, which are defined in template.php. That way, if I have to change a link, I can just change it in template.php and have them updated in all my tpl.php files.
How can I do this?
 Steps I have tried
In this tutorial, it says you can define your variables in themename_preprocess_page(&$variables). You can then call them with <?php print render($page['your_variable_name']); ?>
However, when I try this, I  just get a message stating Notice: Undefined variable: page in include(). The variable also doesn't print.
Also, if I use this method, can I use my variable in all tpl.php files or just the page.tpl.php file?
Comment: http://drupal.stackexchange.com/questions/18545/define-variables-for-template-files have a look at this will solve your problem
Comment: @DEVARAJJOHNSON That link works for node.tpl.php and page.tpl.php but not block.tpl.php
Answer: If you create a variable in themename_preprocess_page(&$variables), it should could be accessed using the variable name itself. Example
function themename_preprocess_page(&$variables) {
  $variables['my_new_variable'] = "String value";
  $variables['my_new_variable_array'] = array(); // Some renderable array.
}

And then in your template you could simply print the first variable directly
<?php print $my_new_variable; ?>

And render the renderable array using the render() function:
<?php print render($my_new_variable_array); ?>

Note: The array keys become the name of the variable, so please make sure to use a unique name to the keys.
Comment: It works for **all** theme functions @big_smile, it's the fundamental mechanism Drupal provides to add/edit variables in a template file. It works for page.tpl.php and block.tpl.php. The proof is the existence of functions like [`template_preprocess_block()`](https://api.drupal.org/api/drupal/modules!block!block.module/function/template_preprocess_block/7), which core uses to do the same thing
Comment: Yep, that's `hook_preprocess()`. It's fired for every theme preprocess (including page and block)
Comment: This only seems to work in page.tpl.php file. It doesn't work in other tpl.php files (e.g. node.tpl.php).
Comment: It also doesn't work for block.tpl.php
Comment: @Clive Does that mean I need to have separate functions (e.g.  themename_preprocess_page, themename_preprocess_block, themename_preprocess_node). Isn't possible to have one function that provides the variables for all templates?

Variables in template files


Ajuda com configuração do DbContext com o EntityFramework usando boas práticas

Question: Tenho minha aplicação divida em camadas com Class Library e a minha camada com o Entity Framework, onde configurei o DbContext, é a Repository.
Minha classe herdada de DbContext:
public class Context : DbContext
{
    private static string connectionString = "Data Source=(local); Initial Catalog=CRM; Integrated Security=True;";
    public Context() : base(connectionString)
    {
        // Set the auto versioning
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Migrations.Configuration>());
        // Gets or sets the database initialization strategy.
        Database.SetInitializer<Context>(new Repository.DatabaseAdditionalConfigurations<Context>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Pluralizing
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        // Non delete cascade
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        // Configure Pessoa
        modelBuilder.Configurations.Add<Domain.Pessoa>(new Domain.PessoaTypeConfiguration());

        base.OnModelCreating(modelBuilder);
    }

    #region DbSet´s ...
}

Vejam que a primeira linha do constructor é para a auto migração da base de dados usando o Migrations: Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Migrations.Configuration>());.
Esse é um bom momento do ciclo de vida da classe para essa linha estar? Ou ela deveria ficar fora, em outro contexto?
E também criei a classe UniqueKeyAttribute para configurar os campos que são unique em minha base de dados:
using System;

namespace Domain.Attributes
{
    ///
    ///A unique attribute
    ///
    public class UniqueKeyAttribute : Attribute { }
}

E para que esse atributo seja traduzido no banco de dados eu adicionei a seguinte classe, que infelizmente não me lembro a fonte:
public class DatabaseAdditionalConfigurations<T> : IDatabaseInitializer<T> where T : DbContext
{
    public void InitializeDatabase(T context)
    {
        var created = false;

        if (context.Database.Exists())
            created = true;
        else
            context.Database.CreateIfNotExists();

        if (!created)
            CreateUniqueKeys(context);
    }

    public void CreateUniqueKeys(T context)
    {
        //Fetch all the father class's public properties
        var masterProperties = typeof(DbContext).GetProperties().Select(x => x.Name).ToList();

        //Percorre cada DBSet<> do DbContext
        foreach (var item in typeof(T).GetProperties().Where(p => masterProperties.IndexOf(p.Name) < 0).Select(x => x))
        {
            //busca o tipo de "T"
            Type entityType = item.PropertyType.GetGenericArguments()[0];
            // Cria as chaves únicas
            var fields = from f in entityType.GetProperties()
                         where f.GetCustomAttributes(typeof(Domain.Attributes.UniqueKeyAttribute), true).Count() > 0
                         select f.Name;

            var uniqueKeys = "";
            foreach (string s in fields)
            {
                if (string.IsNullOrEmpty(uniqueKeys) || string.IsNullOrWhiteSpace(uniqueKeys))
                    uniqueKeys = s;
                else
                    uniqueKeys += ", " + s;
            }
            if (!string.IsNullOrEmpty(uniqueKeys) && !string.IsNullOrWhiteSpace(uniqueKeys))
                context.Database.ExecuteSqlCommand("alter table " + entityType.Name + " add unique(" + uniqueKeys + ")");
        }
    }
}

Bom, primeiro eu tenho um problema. Agora que adicionei o controle com Migrations eu não sei em que momento eu posso colocar a configuração Database.SetInitializer<Repository.Context>(new Repository.DatabaseAdditionalConfigurations<Repository.Context>()); para que o método CreateUniqueKeys possa criar as chaves únicas no banco. Como eu poderia tratar isso? Seria no método Seed da classe Configuration do Migrations?
Outra questão é que minha base foi criada automaticamente somente quando AutomaticMigrationsEnabled = true; do constructor da classe Configuration do Migrations estava setado como true. Precisa disso mesmo, ou estou fazendo algo de errado? Ir por esse caminho é uma boa prática?
Lembrando aqui sobre a pergunta do local ideal para: Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Migrations.Configuration>());.
Answer: ConnectionString na Declaração do Contexto
Não é uma boa prática. Ao publicar seu site em uma base diferente (como no Azure, por exemplo), o sistema já não funcionaria adequadamente. O ideal é você configurar seu contexto da seguinte forma:
public Context() : base("name=SeuSistema")

E no Web.Config da raiz, tenha essa configuração:
<configuration>
    <connectionStrings>
        <add name="SeuSistema" connectionString=""Data Source=(local); Initial Catalog=CRM; Integrated Security=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Remover Pluralização de Tabelas
Isto não é exatamente uma boa prática. Apenas evita que o Framework pluralize suas tabelas, que podem ficar estranhas se você escrever o sistema em português (por exemplo, um Model chamado Contato teria um controller chamado ContatoesController).
A maneira fácil e simples de resolver o problema de pluralização em banco de dados é usando [Table].
Remover Cascade Delete
Isto também não é exatamente uma boa prática. É claro que o cascade on delete é uma opção perigosa, mas não usar esta opção pode criar inconsistências estranhas. O ideal é não permitir a exclusão de registros quem possuam muitos dados dependentes.
SetInitializer
O comando apenas indica que todas as Migrations pendentes precisam ser executadas na inicialização do sistema (não requer o uso do comando Update-Database). Não exatamente é uma boa prática porque pode executar erroneamente Migrations automáticas, o que pode gerar resultados imprevisíveis em caso de alteração frequente dos modelos. Esta configuração não é necessária.
O fonte Migrations\Configuration.cs já é executado quando for executado o comando Update-Database e na publicação do seu sistema utilizando o método Web Deploy. O método Seed() já realiza inserções e modificações de dados mínimos da base e não é necessário implementar um IDatabaseInitializer inteiro para inicializações, a não ser que você precise de um comportamento muitíssimo específico que a inicialização normal não faz, o que acho muito difícil.
CreateUniqueKeys
O MVC é projetado para uso de Surrogate Keys, ou seja, chaves primárias que já são únicas. A ideia de outras chaves únicas serve bem apenas se for do interesse do programador identificar duas colunas como chaves, sendo uma independente da outra. Para isso, basta usar decorar todos os atributos desejados com [Key].
Por exemplo, se tenho um modelo chamado Fabricante e não desejo que dois fabricantes tenham o mesmo nome. Nome não exatamente é a chave. Neste caso, uso [Index(IsUnique=true)].
Entretanto, ainda assim a criação de uma constraint unique vai contra a ideia do Entity Framework, que o banco de dados deve ser agnóstico e nem todos os bancos de dados suportam unique. Dentro da abordagem do MVC, ainda usando o exemplo de Fabricante, o ideal é conferir se não existe um registro que possua o mesmo nome do registro a ser inserido/atualizado.
Automatic Migrations
Como já dito acima, o mecanismo de Automatic Migrations pode ser útil apenas se não é necessário um controle rígido do estado do banco de dados (por exemplo, se o escopo ainda não foi muito bem definido, se há poucos programadores trabalhando no projeto, e se o projeto está bem no começo). Em estágio de desenvolvimento, isto pode ser muito útil.
Entretanto, não é recomendável usar essa configuração se seu sistema já possui uma instância de produção. Neste caso, é melhor usar Migrations manuais, geradas pelos usuários.


Why tapping the bat on the pitch is not considered illegal?

Question: Why does tapping the bat on the pitch (including the danger zone) not considered as illegal but a bowler running over the danger zone is given a warning?
I assume that even if a batsman is "gardening" the pitch   around the bowler's foot marks (on a spinning track), it will not be considered as illegal.
Answer: Tapping the pitch using bat is common practice, as it has been done for so long. I guess in olden days the game was tilted towards the bowlers so much. No helmet or good protection from personal harm. All batsmen could do was tap the pitch, which does not make much of a difference anyways.


How to get query with temp table to work in PHP?

Question: I'm simply trying this query in PHP for the temp table, but it's not working in PHP.
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
    DROP TABLE ##t1
select 'rec1' as col1 into ##t1;
select * from ##t1

PHP code:
$database = new SQL_DB;
$database->query(
  "
  IF OBJECT_ID('tempdb..##t1') IS NOT NULL
    DROP TABLE ##t1

  SELECT 'rec1' as col1 into ##t1;
  SELECT * FROM ##t1;
  "
);
$rows = $database->resultset();

SQL_DB class (simplified):
public function __construct(){
    //Set DSN
    $dsn = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->dbname;
    //Set options
    /*$options = array(
        PDO::ATTR_EMULATE_PREPARES => true,
        PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8
    );*/
    $options = array(
      PDO::SQLSRV_ATTR_QUERY_TIMEOUT => $this->TIMEOUT,
      PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_EMULATE_PREPARES => false
    );
    //Create a new PDO instance
    try {
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        // $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    } catch (PDOException $e) {
        $this->error = $e->getMessage();
    }
}

//Prepare statement
public function query($query) {
    $this->stmt = $this->dbh->prepare($query);
}

//Return result Set
public function resultset($in = "") {
  try{
    if ($in == ""){
      $this->stmt->execute();
    }
    else{
      $this->stmt->execute($in);
    }
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
  }
  catch (PDOException $e) {
      $this->error = $e->getMessage();
  }
}

It works just fine in Microsost SQL Server Management Studio and all other queries I've worked with in PHP work just fine so it's not any of the connection problem.
It definitely has something to do with the temp table and '#'.
What am I missing?
Update:
It works just fine if I split the query into 2 parts:
$database = new SQL_DB;
$database->query(
  "
  IF OBJECT_ID('tempdb..##t1') IS NOT NULL
      DROP TABLE ##t1
  SELECT 'rec1' as col1 into ##t1;
"
);
$database->resultset();
$database->query(
  "
  SELECT * from ##t1;
"
);
$rows = $database->resultset();

Comment: How do you execute this query in PHP?
Comment: Please show us the real code, not pseudo code. a [Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve)
Comment: @Edos That code is highly relevant for the question to be answered. Show that in your question.
Comment: with PHP PDO execute
Comment: Yeah sorry, I updated the questions
Comment: Do you get any error or something?
Comment: Nope, simply empty $rows when checked
Answer: Turns out the problem isn't the temp table but how PDO works for multiple result sets.
The fix is simply changing the way the result is fetched (in this case fetching the last result set):
public function lastresultset($in = "") {
  try{
    if ($in == ""){
      $this->stmt->execute();
    }
    else{
      $this->stmt->execute($in);
    }
    $result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    while($this->stmt->nextRowset()){
      $result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    };
    return $result;
  }
  catch (PDOException $e) {
      $this->error = $e->getMessage();
  }
}


Up button exits app?

Question: I'm not really sure why this is happening, however I have my Main activity, and then use an Intent to call a child activity.  On this activity I have an up button, however it just exits the app for some reason.  I've been staring at this for a while and maybe it just needs a fresh pair of eyes.
If anyone can explain why this is happening, I'd be grateful
MainActivity.java
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CardView cardView = (CardView) findViewById(R.id.card_view);
        cardView.setOnClickListener(new CardView.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Orange.class);
                startActivity(intent);
                finish();
            }
        });
    }
}

Orange.java
    public class Orange extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.orange);
        getActionBar().setDisplayHomeAsUpEnabled(true);
}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

In my AndroidMainfest.xml I have
<activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Comment: Do you have any error log...
Comment: You are finishing Activity when you are starting new Activity. remove `finish();`
Answer: In your MainActivity on button click you do:
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, Orange.class);
        startActivity(intent);
        finish();
    }

You start Orange activity and finish MainActivity. When you exit from Orange, there's nowhere to return, thus the application is closed
Comment: but Orange activity is never being displayed as he describes on his post
Comment: @Alexander Zhak : I think You're right.OP needs to remove that `finish()` line.
Answer: I am not sure but may be its because of finish(); As finish destroys the activity after moving into another activity ,so you cannot go back to previous activity. Try removing finish (); hope this helps :)
Answer: Try adding this...
MainActivity.this.startActivity(intent);

Answer: are you declaring the Orange activity in your manifest?
pleas display your whole android manifest file.
you should have something like:
<activity android:name=".Orange"
    android:label="@string/app_name" >
</activity>

in addition to:
<activity
    android:name=".MainActivity"
...

or else it will crash when you try to start the orange activity.
EDIT:
after re-reading this post I think @Alexander Zhak is correct with his answer, that line (finish();) is closing the first activity so there is nothing to return to so it closes the app.

Up button exits app?