Updating a Variable doesn't seem to have any effect

Question: I am running a DAG which attempts to update a Secret. The Secret is stored in the GCP Secret Manager. Code looks like this:
    Variable.set(key=secret_name, value=mapping_list)

I get this warning message:

[2024-02-23 19:45:42.627489+00:00] {variable.py:245} WARNING - The variable my_var is defined in the CloudSecretManagerBackend secrets backend, which takes precedence over reading from the database. The value in the database will be updated, but to read it you have to delete the conflicting variable from CloudSecretManagerBackend

How can I ensure that the new value I set gets propagated to the backend?

Ok, so I here's what happened: the first time I ran my code, it tried to call Variable.set. The DAG ended successfully, no messages, no warnings, but also: NO NEW Secret in the Secrets backend. So I thought that maybe Airflow couldn't create, for some reason, so I created the Secret manually.
Then when I reran the code, I started getting messages like above. Today I noticed that in the Airflow UI, in the "Variables" page, under Admin, there was a new variable, with the correct name and value. That explains the messages about the conflict! There was the same key in the Airflow database as the Secrets backend!
I deleted the variable in the Airflow database, reran my DAG, and I STILL get the same warning as above, but now I also get an error that causes the DAG to fail when I call Variable.set:

Variable {key} does not exist in the Database and cannot be updated.

So now I really don't know why I'm getting this error: the variable should be cleared from the database and only exist in the backend.
Answer: You are experiencing a case of key collision as explained in the search path doc of Secret Backend.
Before Airflow updates a Variable value it checks for conflicts (see source code), My recommendation is to avoid cases where the same Variable key is stored both in Airflow DB and in Secret backend. It doesn't make much sense to maintain the two versions of the same key as it raises question of what is the source of truth for the data stored with this key?
Either manage the key as Airflow Variable or as key in Cloud Secret Manager but not in both.
The simple solution is to remove one of them then the error will not be shown any more.
EDIT:
To clarify, Variable.set() will always create the variable in Airflow metasotre. It will not write to secret backend. This is a design choice of Airflow. The reasoning behind it is that secret stores normally don't allow to write keys for users. You need special permissions for writing (Admin etc...)
You encounter the error because you used Variable.set(key="my_Var", ...) Airflow checks if the value exist in the secret store (because read access is allowed) and warns you that same key already exist, thus when you will do Variable.get("my_Var") the value from secret store will be returned and the Airflow Variable will be ignored.
I raised https://github.com/apache/airflow/pull/37814 to improve the Airflow docs around the Variable.set() when working with secret backend.
Comment: Well now I'm confused.... I only use `Variable.get` and `Variable.set` - it's how I access other values in the Secret backend, though this is the first time I've tried to update one. I guess I thought I was _only_ storing values in the the secrets backend. Is there a way to ensure that `Variable.get` and `.set` _only_ go to the secrets backend?
Comment: @FrustratedWithFormsDesigner please see edit to my answer. `Variable.set()` will not write to secret store.
Comment: Oh, I didn't realise that _not_ writing to the backend was by design. I don't really feel like creating my own writable backend, so I guess I'll have to either stick with a variable that's only in the Airflow database, or come up with something else...
Comment: @FrustratedWithFormsDesigner Normally secret stores are not being used with a lot of writes from automated pipelines that run frequently. It's very OK to combine Secret store usage with Airflow variables (but not on the same key).  If you feel this design choice is too harsh feel free to raise discussion with your use case and ideas in the Airflow dev mailing list. We are happy to hear feedback. Rather than implementing your own maybe if your idea to support right is accepted you can implement it directly in the open source.
Comment: Option for a workaround in your case is instead of doing `Variable.set()` you can invoke an operator that updates the key in your secret store. I am not aware that such operator exist in the Google provider but it should be rather simple to write one and use it as a task in your DAG.
Comment: I could use a bash or python operator to call Google's Secret Manager API directly, if I can't make do with just a variable in the database.
Comment: That will work.


Add views past date filter dropdown

Question: Tried if someone has already faced or tried for this but I could not find any forum discussion around this.
Within Drupal views I am trying to add date filter based on a CCK date field. I am trying to add date filter within views like:

Past 7 days
Past one month
Past 3 months
Past 6 months
Past one year

I don't see any modules to achieve this neither any discussion around this
Answer: The Date module has a submodule called Date Views that allows Views integration with Date fields.
Once enabled, you should be able to add an Exposed, Grouped filter on your date field. For each grouped filter, you can add your Label (e.g. "Past 7 days"), Operator (is between), & Value which you can set to Relative dates that match your label (e.g. From: "-7 day" / To: "now").
Comment: I do have Date Views module enabled. But I don't have an views operator as "is between" in Drupal 7.
Comment: I have also tried installing the module: views_between_dates_filter but again no luck.
Comment: Is your field data stored as a UNIX timestamp?
Comment: @AnAnD try adding [Authored On](http://i.stack.imgur.com/VA2uq.jpg) you should get an `is between` option there.
Comment: @No Sssweat, As I am using a CCK filed which is indexed in Apache Solr I  have to use only that field to filter the nodes based on date. I can't use any other date field

Add views past date filter dropdown


Compass is creating the same sprite map multiple times

Question: This is resulting in an insane compile time: ~20 seconds. Notice that it creates the global-s9e3ed7fd2e.png image 5 times, as opposed to just once for mobile & once for desktop.
I only see @import "sprites/global/*.png"; being called twice, hence my confusion.
Here's the config file: jsfiddle
Comment: It looks like you are using Grunt so you might want to show your gruntfile.js as it could be causing the problem.
Comment: Heads up, this is part of a gigantic repo which I am still trying to navigate fluidly.

So, I can see about 10 different gruntfile.js files in this repo, all within the node_modules folder.

Would the grunthelpers.js file be of more use?
Comment: Wait, just realized that you want the config file. Added to original post in jsfiddle.
Answer: Try setting force:false on your compass config options, there was a previous issue that caused sprites to be regenerated.
Compilation with Compass and sprites is slow regardless. I had a similar problem: Grunt with Compass and Watch compiles slow
Comment: Yeah, turns out the issue was simply the fact that we were generating so many sprite sheets. Bundled some, removed others, and the compile time dropped drastically.


Remover elementos repetidos usando duas listas

Question: Como faria para remover sem usar collections e while, apenas com for. Queria uma estrutura de busca elemento a elemento, pois já sei remover dessa forma. Então quero usar no mínimo dois for encadeados.
for i in range(len(convidados)):
    pessoas.remove(convidados[i])

Tenho uma boa parte do código, funcionando. Na lista convidados, os elementos serão inseridos com input(), porém deixei assim para fins de praticidade.
pessoa= ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe","Karen","Matheus","Tulio"]
for i in range(len(pessoa)):
   # achei = 0
    #if 0  len(convidados) or i > len(pessoa):
        #pessoa.index(pessoa[i]):
            i -= 1
        elif pessoa[i] == convidados[j]:

            pessoa.remove(convidados[j])
            #j = achei
            #i=achei

Answer: Olá,
Você pode criar uma nova lista que irá conter os elementos não repetidos:
arraySemRepeticao = [] # Lista que terá os elementos não repetidos
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]
pessoa = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]

todos = convidados + pessoa    # Concatena as duas listas

for i in range(len(todos)):    # Irá percorrer a lista que contém elementos repetidos
    if not todos[i] in arraySemRepeticao:    # Irá verificar se elemento não existe, e se não existir, ele entra nesse if
        arraySemRepeticao.append(todos[i])    # Adiciona no fim da lista o elemento que não existe ainda

print(arraySemRepeticao)

Se essa não for a solução que busca, você ainda pode se basear em uma nova solução com a mesma lógica dessa: eu crio um array novo somente com os elementos que ainda não existem, ou seja, se existir, ele não adiciona.
Fiz uma método que funcionaria com infinitas listas e que não cria uma nova lista:
def flat(*list):
    newList = []

    for i in range(len(list)):
        for j in range(len(list[i])):
            newList.append(list[i][j])

    return newList

def removeDuplicates(*list):
    flattedList = flat(*list)
    newList = []

    for i in range(len(flattedList)):
        if not flattedList[i] in newList:
            newList.append(flattedList[i])

    return newList

print(removeDuplicates([1, 2, 3], [3, 2, 1], [4, 2, 1])) # [1, 2, 3, 4]

pessoa = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

print(removeDuplicates(pessoa, convidados)) # ['Matheus', 'Maria', 'Felipe', 'Tulio', 'Karen']

Para remover todos elementos de pessoa que estão em convidados, faça o seguinte código:
pessoa = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

for i in range(len(pessoa)):
    if pessoa[i] in convidados:
        pessoa[i] = None

pessoa = [x for x in pessoa if x is not None] # Remove todos os None
print(pessoa)

Comment: Sim é uma solução, uma das formas que tbm não quis usar é uma nova lista.
Comment: Editei e postei uma nova solução, veja se te atende...
Comment: Deve ser removido da lista pessoa as pessoas que foram convidadas, deve ser resultada as duas listas, mostrando a lista pessoa sem os convidados escolhidos. Meu código consegue remover mas não tem  uma condição de parada.
Comment: Entendi, editei novamente com uma nova solução, veja se te atende :)
Comment: Entendo é que eu gostaria muito de seguir a mesma estrutura mantendo o código, eu até consegui remover quando há mais de 1 pessoa, porém eu gostaria de que algo fizesse o índice voltar a 0, dessa forma eu consigo remover quem sobrou.
Answer: Aqui você diz que quer remover da lista de pessoas todas as que foram convidadas. Então uma forma bem simples (assumindo que não há pessoas repetidas) é:
pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

for convidado in convidados:
    try:
        pessoas.remove(convidado)
    except ValueError: # convidado não está na lista de pessoas
        pass

print(pessoas) # ['Maria']

Tomei o cuidado de capturar o ValueError, pois caso o convidado não exista na lista de pessoas, esta exceção é lançada. No caso, estou ignorando o erro e indo para o próximo convidado (também mudei o nome da lista para pessoas - no plural - já que se trata de uma lista com várias pessoas; pode parecer um detalhe besta, mas dar nomes melhores ajuda na hora de programar).

O problema é que pessoas.remove(convidado) só remove a primeira ocorrência do convidado, então o código acima só funciona se a lista de pessoas não tiver nomes repetidos. Por exemplo, se ela fosse:
pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen", "Felipe"]

Somente o primeiro "Felipe" seria removido, e o resultado seria ['Maria', 'Felipe'].
Outro detalhe é que este código modifica a lista de pessoas. Se você não quer isso, uma alternativa é criar outra lista:
pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen", "Felipe", "Fulano", "Ciclano"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

pessoas_nao_convidadas = [ p for p in pessoas if p not in convidados ]
print(pessoas_nao_convidadas) # ['Maria', 'Fulano', 'Ciclano']

Neste caso, além de criar outra lista, eu também eliminei as repetições, verificando se a pessoa não está na lista de convidados com not in.

Se manter a ordem das pessoas não for importante, você também pode usar set, que é uma estrutura que não permite elementos repetidos. Assim, basta tranformar as listas em set's, subtrair um do outro e converter o resultado em uma lista:
pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen", "Felipe", "Fulano", "Ciclano"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

# retorna uma lista com 'Maria', 'Fulano' e 'Ciclano', mas não necessariamente nesta ordem
pessoas_nao_convidadas =  list(set(pessoas) - set(convidados))

Então quero usar no mínimo dois for encadeados

Para que? Não precisa, as soluções acima são bem mais simples, o seu código estava complicando à toa.
Tudo bem que a solução com not in deve fazer uma busca linear na lista, então é um "loop implícito" dentro de um for, mas a questão é que você não precisa usar dois for explícitos encadeados.
Answer: Olá, eu por conta do tempo desenvolvi uma forma bem complicada de conseguir que com dois for's seja possível, eu propus dessa forma para fins de lógica, e alcançar o resultado sem mudar muito a estrutura, gostei bastante da solução de hktsubo principalmente, chega muito próximo do que eu queria. Aqui está o que eu pude fazer sem fugir da estrutura dos fors:
pessoa= ["Matheus", "Maria", "Felipe", "Tulio", "Karen","belinhaAlmeida"]
convidados = ["Matheus", "Maria", "Tulio", "Karen"]
cont = 0
for i in range(len(pessoa)):

   # achei = 0
    #if 0  len(convidados) or i > len(pessoa)-1:
            i -= 1
       # elif i > pessoa.index(pessoa[j]):
        #    i -= 1
        if len(pessoa) == 1:
            break
                #cont -= 1
        if cont > len(pessoa)-1:
                cont -= 1
        elif pessoa[cont] == convidados[j]:

            pessoa.remove(convidados[j])
            cont = 0
            #j = achei
            #i=achei
    cont += 1
print(pessoa)

Remove qualquer pessoa acredito eu.


OpenVPN won't assign static IPs

Question: I have OpenVPN setup and running correctly. The problem is I want to assign static IPs to certain users on my VPN, so they always get the exact same IP every time.
My setup is for PAM authentication, this is working fine:
client-cert-not-required
plugin /usr/lib/openvpn/openvpn-plugin-auth-pam.so login

My username is joel and also it is working fine as I can login to the VPN from any PC using this username. Here is my server.conf file for IP static config:
client-config-dir /etc/openvpn/ccd

CCD Directory and the User file are both owned by nobody as my process runs as them:

Contents of the user file:

Even with all of this I still do not have a static IP when I connect as user joel. I get different IPs everytime, from .6 to .10, but never .4.
Comment: What are you using for your topology?  Is this tun or tap?  Do you have old Windows clients connecting to this system?  Does your config have `username-as-common-name` set?
Answer: First, do you have a client-connect script in place?  If so, any IP directives from that take precedence.
Secondly, according to the OpenVPN documentation, the client-config-dir only uses the client's X.509 common name to determine which file to use.  You can validate if the joel file is not matching by creating a DEFAULT file.  It appears that you are not using client certificates at all, which may preclude the use of the client-config-dir option.
Comment: Thanks for that! It was just what I needed, I didn't know that I had to tell OpenVPN to set the Common Name to username, I thought it already did. Using `username-as-common-name` on server side did it.
Answer: Using username/password authentication disables any Common Name use by OpenVPN. So it doesn't set the client Common name when logging in.
The solution is to set the following flag in the server.conf file and restart the OpenVPN server:
username-as-common-name

This tells OpenVPN to set the username to the client's Common Name when connecting. Since the file is named after Common Name this is required or OpenVPN doesn't know which file to check.

OpenVPN won't assign static IPs


Combine parameters from URL with props object in Vue router config

Question: Here is my router config.
const router = new VueRouter({
  routes: [
   {
      path: '/user/:id',
      components: User,
      props: {
        sidebar: true
      }
    }
  ]
})

I can't access to all props (e.g sidebar and id), only sidebar in this config.
Any ideas ?
Answer: If I understand you correctly, you want to set the prop sidebar to true (static) and the prop id to the :id URL parameter (dynamic).
You'll have to use a function which takes the route as a parameter and returns the prop values you want to set on the component:
props: route => ({
  id: route.params.id,
  sidebar: true,
})

Have a look at Function Mode in the vue-router docs for more information.
Comment: Is this still possible if you have multiple components and need to pass different sets of props to different named components?
Answer: You can access route path and params like this:
this.$route.path or
this.$route.params.id

from within your function, computed props or your template
Comment: Is there any other way ? From [Vue's doc](https://router.vuejs.org/en/essentials/passing-props.html), it seems to be not the best way to do it.
Comment: Do you want to pass ` props: {
        sidebar: true
      }` to `User` component?
Comment: i do, i need it in my User component.
Comment: can you check https://jsfiddle.net/ow85z2n8/1/ ? I can get the id in the template


How can i get n digits from right side in sql

Question: in sql-server how can I get N digits from right side
example 123456-->3456

Answer: Use RIGHT()
select right(123456, 4)

SQLFiddle demo
Comment: This would fail for SQL Server compact and would also involve `cast` ?
Answer: 123456 % 10000 -- 3456

try using modulo or
select right(123456,4)

DEMO
Answer: DECLARE @TEST VARCHAR(1000)
SET @TEST = '123456'

SELECT RIGHT(@TEST,4)


Make label translatable in Global: Custom Text field

Question: I'm using Drupal 7 and I have a Global: Custom Text in my view

Label

[title]

[category]

When I try to translate the 'Label' from
`Configuration » Regional and language » Translate interface`

I get an error 'The submitted string contains disallowed HTML'.
That is because the label is wrapped in a div. I could add the div in include/locale.inc in the function
`locale_string_is_safe($string)`

but I don't think is a good idea to edit the Drupal core.
Do you have any better solution?
Answer: Use hook_views_pre_view and set your global header programmatically.
E.g.
$view->set_item_option($view->current_display, 'header', 'area_text_custom', 'content', $header);

Answer: You can create a template for the field, i.e.
views-view-field--your-view-name--nothing.tpl.php
in which, instead of the default code:
print $output;

you add the following code:
$yourstr = t('Your Cool Label');
$out = str_replace('Your Cool Label', $yourstr, $output);
print $out;

In this way you'll find "Your Cool Label" under the translatable strings interface (admin/config/regional/translate/translate).
Just remember to "Rescan template files" under Theme -> Information of your view, then save.


Share one back office (database) over three drupal websites

Question: I'm wondering if there is a way to have one back office for three drupal websites with different domaine names, so I can share users over the three websites, I think I'm gonna have one database for all my drupal websites, but I'm not sure how I can achieve this using drupal.
Comment: You need to use domain module for the above case.
Answer: Teeyo,
You can do this with the domains module that can be found here:
https://www.drupal.org/project/domain
The installation instructions can be found here:
https://www.drupal.org/node/477372
Don't forget to edit your settings.php file ;-)
I used the module myself a couple of times, so if you need any assistance, just let me know :-)
Comment: Thank you @guardian, yup it's great module, I started using it, now I'm exploring it, (trying to add the domain blocks module so I can control the display of my modules) ... I'll contact you when if I need anything ;)


The project failed to build after enable-migrations

Question: side info: I'm following the MVC 4 course on pluralsight
Problem:
I have an ASP.NET MVC4 internet application. Everything goes like thebook tells me but
after enable-migrations into the package-manager console i get en error:The project 'somesite.web' failed to build.
I deas?
Answer: Try to build the project somesite.web by yourself and check the detail error.


Integral of $ \int \frac{x}{\sqrt{4x^2 + 8x + 5}} dx$

Question: How to solve:
$$\int \frac{x}{\sqrt{4x^2 + 8x + 5}} dx$$
This question is from a list and it's in the category of problems that involving $\sqrt{x^2\pm a^2}$ and $\sqrt{a^2\pm x^2}$ (triangle rules).
I tried some methods, but I didn't get anywhere. Where this type of problem fits?
Comment: Where it fits: The thing inside the square root is $(2x+2)^2+1$.  Let $u=2x+2$. Then $dt=\frac{du}{2}$ and $x=\frac{u-2}{2}$. So we are integrating $\frac{1}{4}\frac{u-2}{\sqrt{u^2+1}}$.  Completing the square is a useful tool.
Comment: @AndréNicolas Now I can see.. I was look for something like $\sqrt{u^2\pm a^2}$ as you found
Answer: First note that
$$ \frac{d}{dx} (4x^2+8x+5) = 8(x+1), $$
so add and subtract $1$ in the numerator:
$$ \int \frac{x}{\sqrt{4x^2 + 8x + 5}} \, dx = \int \frac{x+1}{\sqrt{4x^2 + 8x + 5}} \, dx - \int \frac{1}{\sqrt{4x^2 + 8x + 5}} \, dx $$
The first integral is then in the form $(f)^{-1/2}f'$, which is easy to integrate.
For the other, complete the square on the denominator:
$$ 4x^2+8x+5 = 4(x+1)^2 + 1 $$
This transforms the integral into one of the form
$$ \int \frac{dy}{\sqrt{a^2y^2+1}}, $$
(with here $y=x+1$, $a=2$) which you can then turn into one of the forms you know how to do.


AccessKey no Jquery

Question: Em uma página tenho diversos botões com seus respectivos accesskey (tecla de atalho para o mesmo), como faço para quando esse botão for chamado pela tecla executar a ação click do mesmo no Jquery. Exemplo: tenho o botão Enviar, com atalho pela tecla A, quando pressiono a tecla A (accesskey do mesmo) chamo a função de click do botão no Jquery.
Comment: Se puder, comente o codigo que está utilizando.
Answer: Não sei exatamente como estás a adicionar esses aucultadores de eventos. Se adicionares isso na pergunta fica mais claro a tua tua implementação.
Alguns exemplos de como podes fazer isso:
Se estiveres a adicionar localmente
se o que usas é algo do género: $('.button').on('click, keyup', function(){ então podes juntar uma verificação do tipo de evento assim:
$('.button').on('click, keyup', function(e){
    if (e.key == 13){
        // correr a lógica do código para a tecla Enter, e depois
        $(this).click();
    }
    // etc

ou alternativamente if (e.type != 'click') $(this).click();, mas se já tens uma lógica para detetar a tecla isso implica que é um evento de teclas.
Se tens um auscultador global
Se tens algo do género $(document).on('keyup', function(){ que vai verificar qual a tecla então deves ter um objeto que guarde a relação entre botões e teclas... por exemplo:
Botão 1
e depois podes colocar isso em cache no inicio do carregamento da página:
var btnsTeclas = {};
$('button[data-tecla]').each(function(){
    var tecla = $(this).data('tecla');
    btnsTeclas[tecla] = this;
});

e quando souberes qual é a tecla basta fazeres:
var teclaPressionada = event.key; // ou outra lógica que tenhas para saber a tecla pressionada
$(btnsTeclas[teclaPressionada]).click();

AccessKey no Jquery


Can a space $X$ be homeomorphic to its twofold product with itself, $X \times X$?

Question: Let $X$ be  a  topological  space  of  infinite  cardinality. Is  it  possible  for  any  $X$  to  be  homeomorphic  to  $X\times X$  $?$
For example, $\mathbb R$  is  not  homeomorphic  to  $\mathbb R^{2}$, and $S^{1}$  is not  homeomorphic  to  $S^{1} \times S^{1}$ . What  other  topological  spaces  might we consider$?$ What  properties  of  a  space  may  ensure  or  contradict  this  possibility$?$  From  the  little  topology  I  have  learnt  yet,  I  have  not  seen  this  happening.
Comment: $X = Y^{\mathbb{N}}$
Comment: Other common nontrivial examples include $\mathbb Q$ and the Cantor set.
Comment: @Travis: There is a general theorem of Sierpinski: a countable space with no isolated points is homeomorphic to $\Bbb Q$. But I believe you can write down an explicit homeomorphism with continued fraction trickery. I believe this is done somewhere on this site.
Comment: @MikeMiller Thanks, that's quite a nice result. A little searching yields this well-sourced answer: http://math.stackexchange.com/a/56536/155629 . Sierpinski's original paper (in French) is http://matwbn.icm.edu.pl/ksiazki/fm/fm1/fm113.pdf .
Comment: (@MikeMiller FWIW, that post also includes metrizability among the hypotheses of Sierpinski's Theorem.)
Comment: See also:
[Homeomorphism between Space and Product](http://math.stackexchange.com/questions/677574/homeomorphism-between-space-and-product),
[Homeomorphism between topological space and product space](http://math.stackexchange.com/questions/722412/homeomorphism-between-topological-space-and-product-space),
Comment: @MikeMiller What is the argument for $\Bbb Q$, say? At a glance this seems nonobvious, assuming that $\Bbb Q$ is given the subspace topology induced by its inclusion into $\Bbb R$.
Comment: @Travis: Ah, fair point. You need some decent hypothesis since it's obviously false if you allow non-Hausdorff spaces. Thanks for the correction.
Answer: Yes, consider $X := \Bbb Z$ endowed with the discrete topology.
For any topological manifold $M$, $\dim (M \times M) = \dim M + \dim M = 2 \dim M$. Since the dimension of a nonempty topological manifold is well-defined, there is no positive-dimensional topological manifold $M$ for which $M \cong M \times M$, which in particular excludes $R$ and $S^1$ as observed. This implies that the example $X = \Bbb Z$ is the only example that is a (second countable) topological manifold.
Comment: @Augustin: The definition of dimension of a topological manifold is the unique integer $n$ such that $M$ is locally homeomorphic to $\Bbb R^n$. That this is well-defined comes down to that $n$ being unique: that is, that $\Bbb R^n \cong \Bbb R^m$ implies $ n=m$.
Comment: Here, well defined means that homeomorphic topological manifolds have the same dimension?
Answer: At this level of generality you can make $X=X \times X$ happen quite easily. Take a discrete space of any infinite cardinality, for instance. Or topologize $X=A^B$ by whatever means and compare $X \times X = A^{B \sqcup B}$; under various mild assumptions on $B$ those spaces would be homeomorphic.
Answer: Many Banach spaces are linearly homeomorphic to their Cartesian squares. For instance all classical spaces including $c_0$, $\ell_\infty$, $C(K)$ for $K$ compact metric, $L_p(\mu)$ for $p\in [1,\infty]$ etc.


Pandas bar plot ignores the xlim parameter

Question: I would like to only make a plot with only the year between 1990 and 2000.
import random
import pandas as pd

df = pd.DataFrame({'year':range(1950,2020),
                   'value':[random.randint(100, 1000) for x in range(70)]})
df.plot(kind = 'bar', x = 'year', y ='value', xlim = (1990,2000))

Whatever I set the value of xlim to: (1990,2000) or [1990,2000] or 1990, it still displays the full range of the year from 1950 to 2019.
I know that one solution is to first select only the rows of year 1990 to 2000, then make the plot, like this:
df.query('1990 <= year <= 2000').plot(kind = 'bar', x = 'year', y ='value')

But what is the problem for the above code?
Comment: @JohanC Oh I see, I think I've got your idea. because when I try using other kind of plot such as `line` or `area`, the `xlim` works. Anyway that means the `xlim` is not applicable for `bar` graph. Thank you.
Comment: @JohanC Can you post your comment again as the answer? I would like to mark your reply as the answer. Thanks.
Comment: Please try to use correct upper case letters, e.g. in the beginning of your title, sentences or the word "I". This would be gentle to your readers.
Answer: A bar plot is categorical. Internally, the bars are numbered 0,1,2,.... Pandas' bar plot doesn't seem to look at the xlim= argument, but you can call plt.xlim(40, 50) after creating the plot.
The following code looks up the categorical position of the values to set the x limits. 0.5 is added to avoid bars cut into two.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import random

df = pd.DataFrame({'year': range(1950, 2020),
                   'value': [random.randint(100, 1000) for x in range(70)]})
ax = df.plot(kind='bar', x='year', y='value', rot=0)
ax.set_xlim(np.where(df['year'] == 1990)[0] - 0.5, np.where(df['year'] == 2000)[0] + 0.5)
plt.show()


Relation between F test and T test. Are they mutually exclusive?

Question: I am studying Statistics for data science since few months..
1)I am learning that, when we have to compare multiple samples (>2) then a T test would be tedious and instead we go for ANOVA and conduct a 'F Test'.
2)Above understanding kind of creates a 'mutually exclusive requirement between F test and T test."
3)I have also learned that, the T test ( be it : 1 sample/paired/2 sample ) basically tests for differences in means whereas 'F test' tests for differences in Variances.
4)Now, suppose two samples groups are having nearly equal means but highly different variances,  then, both tests would give different answers right?
T test would say 'they are not different'.
But 'F test' would say 'they are different'.
Or even for a reverse case. (hugely different means, but nearly same variances)..
5)So based on what, (the mean? or the variance?) we are finally going to decide their true difference?
6)So Question is:  How are they related? If original objective was to find out two or more samples are different or no,
then how 'looking for means'(i.e. choosing the T test) for smaller no of sample groups, gets changed to 'looking for variances' when no of sample groups are >2? (When the fact is :the variance and mean are basically independent characteristics of a sample group)
7)Should Not these both metrics be checked for finding whether truly the two samples are different or Not ?
( I have mentioned serial numbers to points that I have stated. Kindly point out if any of them is a basically wrong understanding. Would appreciate if answers are given for each point)
Comment: Well, making a "test" is finding the answer to a question. The first thing you need to know is what the actual question is!
Comment: What do you exactly mean by "comparing samples"? Are you talking about comparing whether the mean of the population they come is the same/different? Or are you talking about checking whether their distribution is the same/different?
Comment: I am not sure !!  Because thats what I want to know.!  Should  we not look for both for deciding "those two sample groups are different or not"  in all aspects ? I could not find any tutorial which highlighted this view..  Most of the tutorials explain like "...for comparing more than two groups, go for F test.. .. ". That time the view point changes from "looking at mean" to "looking at variances !!"..   Hence I am not clear on this!
Comment: As a new student of stat, i dont know what to look out for !..  most of tutorials say.. " T test  OR F test".. none of the tutorial said " check for both T AND F !! ( my opinion : Shouldn't we look from both angles ? (i.e. the  means as well as the variances)?
Comment: The below link kind of goes there: I have referred it already. But not exactly it answers my question ):  https://stats.stackexchange.com/questions/78150/is-it-possible-to-combine-the-f-test-and-t-test-to-test-for-differences-in-both
Answer: The terms t-test and F-Test are ambiguous, because any test where the test statistic has a t-distribution (under the null hypothesis) is called t-test and any test where the test statistic has an F-distribution is called F-test. There is more than one instance of these.
This is relevant to your question because there is an F-test that compares the variances of two samples, but this is not the F-test used in standard ANOVA-analysis. In fact the ANOVA F-test compares between-group and within-group variability, and between-group variability is in fact measured by squaring and summing up differences between group means, so in this setup both t- and F-tests are about comparing group means. In fact, if you have only two groups/factor levels, the F-test statistic is the square of the t-test statistic, and the F-test is equivalent to the two-sided t-test.
For more than two groups the issue with t-tests is that the t-test can only compare two groups at one time, meaning that you will need several t-tests to compare all groups, involving issues with multiple testing (i.e., if you test several hypotheses at 5% level, the probability to find at least one wrong significance assuming that the null hypotheses are all true can be substantially higher than 5%).
Additionally, you are right that one may be interested in exploring both differences between means and differences between variances, and groups with same mean may still have different variances. You may indeed check them both, though this again involves multiple testing; there's no free lunch. In many applications of ANOVA it is either fairly reasonable to assume equal variances, or only mean differences are of substantial interest (e.g., only wondering whether one group performs "better" than another), therefore differences in variances are often not explicitly investigated (I will abstain from a statement about whether this would be "good" or "correct"; or rather my answer would be "it depends"...).
Comment: Thanks  for the explanation
Comment: The way I have phrased this to my colleagues (and perhaps on here) is that the ANOVA F-test cleverly uses variances to make a statement about the means, though I do believe the name is misleading. +1
Answer: If you are comparing more than two groups and are interested in comparing their means then it is usual to do ANOVA as you say which tests the hypothesis that all group means are equal. Doing multiple $t$-tests is not quite equivalent because each test only tets if the means in those two groups are equal. Your point 1)
The use of the $F$ test to compare variances is used because what you compare in ANOVA is the variance between the group means versus the variance within groups. (Your point 3)
The remainder of your questions are hard to answer because, see my points above, I think you have some mis-conceptions about just what is going on.
Answer: It is simple and depends upon your problem statement. If you want the comparsion based on an average you can use a t-test and if you want the comparision that how the data variate within the data then you will use the F-test.
Answer: Consider this formula
<code>Ho: group1 and group2 has the same average
(e.g. do they have the same average height)
t = (mean-k)/(s/sqrt(n)), basic assumption. variance is known.

Ho: Different level of fertilizer (NPK) has no significant effect on plants.
F = n(mean-k)^2 / s^2, w/c is simply t^2

</code>

from Practicality point of view this could be true correct.

2.If you have a control and treated group form the same population then they will be the same. But say if you have boys vs girls, location1 vs location2, they could be different.

Correct.
Possibly
Depending on your objective. If you simply want to know if the group have different characteristics (like average) then t-test. If you want to know if certain applied factors (like different levels of cigarette's nicotine) have significant effects then use F-test.
The formula is related but the application differs depending on your goal.
No. since it doesn't makes any sense since t and F test have different goal or problem they're solving.


Inspect an Exception object like a normal object in Firefox dev tools

Question: I'm trying to debug an issue where I have an exception being thrown and caught. When I log it to the console, Firefox displays it completely differently from a normal object:

I can force it to display like a normal object by doing JSON.parse(JSON.stringify(e)), but is there a less clunky way?
Answer: When you set a breakpoint within the catch block, you can see the exception's properties using the Scopes panel in the sidebar of the Debugger panel.
In that panel, all objects of the current stack frame are shown under the Block scope.

In addition to that, I have now also created an enhancement request asking to add a way to display an exception's properties within the console.
PS: To log errors, you can use console.error() instead of console.log().


Is the "missing Unicode character" box a Unicode character itself, and if so, which one?

Question: When browsing the web in Windows XP, Windows is often unable to render more esoteric unicode characters. When this occurs, it replaces the characters with a small box.
If you're running Windows XP, the following should render as this box, for example: ︙
Is this box a Unicode character itself?
If so, I was thinking that I could put it in my web pages, and see if other Unicode characters I was attempting to use were the same width as it, in order to check whether the other characters were supported or not.
Comment: At least in my computer/browser, the displayed character is not always the same... It's a box with the hexadecimal code point inside.
Comment: @Álvaro: aha! Yes, I've seen that too. Hm.
Comment: possible duplicate of [Detect browser character support in javascript?](http://stackoverflow.com/questions/4635683/detect-browser-character-support-in-javascript)
Answer: It is a Unicode code point. It may represent a single character or be one of the combining points (multiple code points forming a character)
Comment: To detect whether a font supports the character? Apparently yes: http://stackoverflow.com/questions/4635683/detect-browser-character-support-in-javascript
Comment: Alrighty. Does that mean I can actually use it in a web page?
Comment: WINNER, that's the stuff. Bravo!

Is the “missing Unicode character” box a Unicode character itself, and if so, which one?


Recommend an enjoyable / introductory book on Statistics

Question:
Possible Duplicate:
A resource on concepts underlying statistics, not the techniques used in applied stats

I am interested in learning more about Statistics and when I ran a Google / Amazon search that brought up way too many options.
I am hoping to get a recommendation of a statistic book that is beginner's oriented and fun to read / learn.
Comment: I feel like this question should just be closed. We have collected several recommendations on various related threads, see e.g. this query: [books +introduction +statistics](http://bit.ly/RzRvnI).
Comment: How much probability/math do you already know, Daniel?
Comment: I've always thought there ought to be book discussing all of the paradoxes, counterintuitive results and plain weird findings from the field statistics. For example: - Simpson's Paradox - Stein's Paradox - St. Petersburg Paradox - Ecological fallacy - Prosecutor's fallacy - Cauchy distribution (mean and variance are undefined!) Don't know if such a book exists, however.
Comment: It's been a while since I actively studied math, the furthest I got to was Cal, Linear Algebra.
Comment: One thing I would do is first studying a lot of probability for a while. There are many good probability books. Ross (A First Course in Probability) is well written. You won't learn much without solving $\textbf{a lot}$ of the problems.
Comment: One of my personal favorites is [How to Lie With Statistics](https://www.amazon.com/How-Lie-Statistics-Darrell-Huff/dp/0393310728/ref=sr_1_1?s=books&ie=UTF8&qid=1485189961&sr=1-1&keywords=how+to+lie+with+statistics).  It provides a great overview of the subject, practical examples, and focuses on what is going on with different statistics beyond the math involved.
Answer: Here are two nice books that I enjoyed

Statistics: A Very Short Introduction This is just about 130 pages of text, that introduces the subject for a general reader. Part of the Very Short Introductions series from OUP.
Cartoon Guide to Statistics A book that handles the subject with lot of illustrations. Suitable for reader from all walks of life.

Update: A similar query at Quora
Answer: Slightly OT, but The Lady Tasting Tea is a really fun book about the history of statistics and some of the people who practised it. There's some actual stats in their too, and some of it is really useful in terms of learning stats, e.g. what are parametric statistics?
Oh yeah, and Red State Blue State, by Andrew Gelman, about voter behaviour in the US, is another great one for catching your interest and learning stuff (e.g. the ecological fallacy) along the way. Awesome graphs too. Mmm... graphs (as Homer Simpson never said)
Answer: I suggest the Statistics 101 course at Udacity.
This is not technically a book, but I have found it to be a more useful way to learn statistics, when you are learning on your own.  It is definitely more fun than a book.
It is free, and it starts with the assumption of no previous knowledge of statistics.
Answer: There is a statistics one course  starting up tomorrow at coursera. I guess it's much like the one at udacity, though I haven't followed that one.
It will be with small assignments throughout the course. 75,000 have already signed up.
It's not a book, but it takes you directly back to the classroom again :-)
Here's the link: https://www.coursera.org/course/stats1
Answer: I really enjoyed Intuitive Biostatistics.  It covers lots of material, is easy to read, and has very good explanations.  At the end of each topic is a question and answer section for the common (and not so common) problems/concerns for the discussed statistical procedures.  Of course all the examples deal with biology but is still applicable to any field.
Answer: I got on well with Statistics for Terrified Biologists, though this may be a little focused on biology if you're looking for a more in depth introduction. It covers the absolute basics, which are often overlooked - the importance of standard deviation, and what things really mean.


What is the purpose of placing a HashSet inside of a HashMap?

Question: For example:
private HashMap<Integer, HashSet> variableName;
I understand that HashMap implements Map and doesn't allow duplicate keys and HashSet implements Set and doesn't allow for duplicate values, but what is the purpose of placing a HashSet inside of a HashMap? Do they not achieve similar tasks by themselves (though in different ways and with different performance)? What functionality does doing this provide that a HashMap by itself couldn't?
Comment: Same reason you would put **anything** in a `HashMap`, you want to associate a key (here an `Integer` value) with something (in this case a `Set` of other things).
Answer: You do this when you want to map a key to more than one thing.  A Map can only map a key to a single thing, but that single thing can be a Set which holds multiple things.


What is the walk out song World Cup 2018?

Question: During the FIFA World Cup this year (2018), you can hear a song being played throughout the stadium as the players walk out of the tunnel onto the field. What song is this?
Answer: I believe it's The White Stripes - 'Seven Nation Army'.
Comment: And as far as I remember, it's been played before matches of FIFA World Cup and UEFA Cup for at least ten years already.


Certbot unauthorized and connection errors

Question: I have a spring boot application on Google Cloud, CentOS 7. I wish to install SSL certificate via Let's Encrypt and Certbot. When I use certbot --apache -d mydomain.zone command I receive an error:

My domain is registered on Namecheap. My A records on Google Cloud:

Also I provided google cloud nameservers in Namecheap like in this tutorial: https://www.wpmentor.com/setup-domain-google-cloud-platform/

Can you tell me where the issue is? I also wonder is there an issue with my java code in app. For example sometimes while accessing index page, error_page is called. When I have a method in my controller:
@RequestMapping(value = "/error_page", method = RequestMethod.GET)
public String homeError(Model model)
{
  return "/error_page";
}

I have a different certvbot error:

but when I comment/erase my controller method for error page I receive this error:

Can it be it's an application bug? Or issue with apache?
I tried to turn off Tomcat. Now I receive this error:

Note: My Apache forwards to 8080, I don't know will it make any issue?
iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port  8080

Answer: Let's Encrypt is attempting to verify your ownership of the server by spinning up a temporary web server and having the Let's Encrypt servers try to contact it.
You will need to:

Disable any currently running web servers

Make sure port 80 is accessible from the internet

You already took care of step 1 by stopping Apache, now you need to fix your iptables rule.
Looks like you're forwarding traffic from port 80 to port 8080, this is most likely why you're getting the Connection refused error, since the temporary web server's traffic is getting black-holed to port 8080. Disable/fix that rule and the verification should succeed.
Comment: It works! I have a few questions: 1. I will return my redirect to 8080, because Apache is on 80 and Apache Tomcat is on 8080 and I don't wish 8080 to be visible in the URL. Will this be an issue when the certificate needs to be renewed?
2. My https part is colored in red and it says it's not secure. Is this normal with Let's encrypt or I need to do additional configurations in Apache files?
Comment: @LosmiNCL It won't be a problem as long as you can temporarily make port 80 reachable from the internet like you just did.
Comment: @LosmiNCL If https is red then something is wrong with your web server config. Most likely Apache Tomcat isn't pointed to the files generated by certbot.
Comment: It's not red if I type https://mydomain, it's red only when it's https://ip_address so It's probably ok
Comment: @LosmiNCL yup you're all set


Spivak calculus 7. ch 22: Convergence of a continued fraction sequence

Question: This exercise is has a "small" modification, but I haven't been able to solve it yet and I wanted some advice! thanks!
For any positive integers $a$ and $b$ consider the sequence
$$
a_{1}=a, \quad\text{and}\quad a_{n}=\frac{b}{2 a+a_{n-1}}\quad \text{for} \; n \geq 2
$$
Show that the sequence converges to the value of
$$
\sqrt{a^{2}+b}-a
$$
And use the first item to show that a development in continued fractions of $$ \sqrt{a^{2}+b}$$ is
$$\sqrt{a^{2}+b}=a+\frac{b}{2 a+\frac{b}{2 a+\frac{b}{2 a+\cdots}}} $$

Context from Comments
I've been trying, but I don't understand what $\left | a(n)-a(m) \right |\leq kd_{e}(n-m)=k\sqrt{n^{2}-m^{2}}$ has to do with $\sqrt{a^2+b}-a$. Then, without loss of generality, and considering that $a$ and $b$ are positive integers, so $a^{2}+b<a^{2}+b^{2}\Rightarrow \sqrt{a^{2}+b}-a<\sqrt{a^{2}+b^{2}}= d_{e}(a,b)$ in order to find a relationship between $\left |a(a)-a(b)  \right |$ and $kd_{e}(a,b)$
Comment: @Andre785858 Can you please insert this attempt into the question post, because this fulfills the context criterion for questions, and is important for future visitors/ answerers? Thank you for providing it.
Comment: @EricTowers I've been trying, but I don't understand what $\left | a(n)-a(m) \right |\leq kd_{e}(n-m)=k\sqrt{n^{2}-m^{2}}$ has to do with $\sqrt{a^2+b}-a$. Then, without loss of generality, and considering that $a$ and $b$ are positive integers, so $a^{2}+b<a^{2}+b^{2}\Rightarrow \sqrt{a^{2}+b}-a<\sqrt{a^{2}+b^{2}}= d_{e}(a,b)$ in order to find a relationship between $\left |a(a)-a(b)  \right |$ and $kd_{e}(a,b)$
Comment: Are you able to show the $a_n = \cdots$ map is contractive on some interval containing $\sqrt{a^2+b}-a$, the largest such interval, and that $\sqrt{a^2+b}-a$ is a fixed point of that map?
Answer: In the following I am assuming that $x \ge 0$.
Let $f(x) = {b \over 2a+x}$, $g(x) = f(f(x))$. Note that $g'(x) = {b^2 \over (2ax +b+4 a^2)^2}$ and $|g'(x)| \le {b^2 \over (b+4 a^2)^2} < 1$. In particular, $g$ is a contraction and hence has a unique fixed point $x^*$. It follows that $x^*$ is the unique fixed point of $f$ as well.
Hence the sequence $a_n$ converges to some $a^*$ and we must have $a^* = f(a^*)$.
Solving shows that $a^* = \sqrt{a^2+b} -a$.
Comment: I have moved the context from the comments into the question. However, the context was there (in comments) prior to this answer being posted.
Comment: Why the downvote?
Comment: Why the delete?
Comment: Unfortunately, Spivak doesn't get to contraction mapping until Exercise 23, several pages later.
Comment: @TedShifrin Bummer, I initially had a long winded proof that showed the increasing part of the sequence converged but was happy to discover the above instead :-(.
Comment: @copper.hat I'd like to see the way you proof it long form
Answer: HINT: In the spirit of the previous part of the exercise, Spivak intends for you to consider separately the subsequences of even terms and odd terms. One is increasing, the other decreasing, and you can check that their limits agree.


How to change input/textarea value with custom keyboard event and keyCode?

Question: I would like to populate a textarea by triggering keyboard events, such as keydown (I'm doing this for a test case).
I have added a snippet (below) to show the code I'm using to create and trigger the event. The event fires, but the textarea never receives the value of keyCode which is the letter A.
What do I need to do to see the letter in the textarea? I'm currently running the snippet in the Chrome console but it should also work in IE9.

var t = document.getElementById('foo');

// Event creation
var event = document.createEvent('HTMLEvents');
event.initEvent('keydown', true, true);
event.keyCode = 65;
event.which = 65;

// Listener for demo purpose
t.addEventListener('keydown', function (e) {
  document.getElementById('fired').value = e.type + ' fired';
});

// Event trigger
t.dispatchEvent(event);
<textarea id="foo"></textarea>

<input id="fired" value="">
Answer: Why does not the value change after triggering keydown?
In short: you can't change the value of input/texarea with dispatching KeyboardEvent programmatically.
How actually do chars come into input? On MDN you can find the description of Keyboardevent sequence (assuming that preventDefault is not called):

A keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true.
If the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down.
A keyup event is fired once the key is released. This completes the process.

So, keydown leads to input event by default. But that is true only for trusted events:

Most untrusted events will not trigger default actions, with the exception of the click event... All other untrusted events behave as if the preventDefault() method had been called on that event.

Basically trusted events are those initiated by a user and untrusted events are initiated with a script. In most browsers, each event has an attribute isTrusted indicating if the event is trusted or not.
And how to test KeyboardEvents on inputs then?
Well, first of all, think if you really need a KeyboardEvent handler. Maybe you can do everything in InputEvent handler. That means that you can just set the value of the input in your tests and then trigger InputEvent.
If you still need KeyboardEvent handler than it depends on what is going on in it. E.g. if you call preventDefault in certain conditions then you can check if it was called or not in a test using a spy. Here is an example with sinon as a spy and chai as assertion library.
const myEvent = new KeyboardEvent('keydown', { key: 'a' })
sinon.spy(myEvent, 'preventDefault')
document.getElementById('foo').dispatchEvent(myEvent)
expect(myEvent.preventDefault.calledOnce).to.equal(true)

Answer: Javascript sending key codes to a <textarea> element
I had a look around and this seems more relevant than my non-relevant answer before. Sorry about that. I know this is jquery, but the premise is the same.
adding this in the event would work
document.getElementById('foo').innerHTML += String.fromCharCode(e.keyCode);

here it is in pure javascript jsfiddle
Comment: I think that OP is asking about why the char is not appearing in the `` not in the ``.
Comment: ah in that case, i feel silly and will be back with an edit to correct
Answer: The keydown event is fired when a key is pressed down but it's not the responsible for write the data in the DOM elements.
The thing is; If the user writes on the <textarea> first the character is added to elements value and then the keyDownevent is triggered. However in your case you're directly triggering the event so the first step which is adding the character to the value for <textarea> is not happening.
You have two options, do it in the browser way write the value and then dispatch the event
t.value = t.value + String.fromCharCode(e.keyCode);
t.addEventListener('keydown', function (e) {
  document.getElementById('fired').value = e.type + ' fired';
});

Or also you can write the value of the <textarea> on the keyDown event:
// Listener for demo purpose
t.addEventListener('keydown', function (e) {
  t.value = t.value + String.fromCharCode(e.keyCode);
  document.getElementById('fired').value = e.type + ' fired';
});

however if you want to use this second approach for user interaction it's a nonsense because in the case that the users inputs the data, the data will be write it twice (one for the user input and the another one in the event).
Hope this helps,
Comment: Thank you! You are right about the flow of events and my lack of understanding this was the problem. Like you say, the keyboard event is fired **after** the user interaction, when the value is already set. The event.keyCode is simply a piece of information.
Comment: @TJ nice to help you `:)`.


System.NullReferenceException: Object reference not set to an instance of an object. bootstrap dropdownlist

Question: Model
public class Employee
    {
        public int EmployeeID { get; set; }
        public string Title { get; set; }
        [Required(ErrorMessage = "Please enter first name.")]
        [StringLength(500)]
        public string FirstName { get; set; }
        public string MI { get; set; }
        [Required(ErrorMessage = "Please enter last name.")]
        [StringLength(500)]
        public string LastName { get; set; }
        public string Gender { get; set; }

        [Required(ErrorMessage = "Please select date of birth.")]
        public Nullable<System.DateTime> DateOfBirth { get; set; }

        [Required(ErrorMessage = "Please enter email.")]
        [StringLength(500)]
        [EmailAddress]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter street.")]

        [StringLength(500)]
        public string Street { get; set; }

        [Required(ErrorMessage = "Please enter state.")]
        [StringLength(50)]
        public string State { get; set; }

        [Required(ErrorMessage = "Please enter city.")]
        [StringLength(50)]
        public string City { get; set; }

        [Required(ErrorMessage = "Please enter country.")]
        [StringLength(50)]
        public string Country { get; set; }

        [Required(ErrorMessage = "Please enter post code.")]
        [StringLength(6)]
        public string PostCode { get; set; }

        [Required(ErrorMessage = "Please enter home phone.")]
        public string HomePhone { get; set; }

        [Required(ErrorMessage = "Please enter mobile phone.")]

        public string MobilePhone { get; set; }

    }

Controller Method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        db.Employees.Add(employee);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(employee);
}

View
@model EmployeeManagementSystem.Models.Employee

@{
    ViewBag.Title = "Create";
}

Create

        @using (Html.Bootstrap().Begin(new Form().Id("CreateEmployee").Type(FormType.Inline)))
        {

            @Html.AntiForgeryToken()

                <fieldset>

                        <legend>Employee Info</legend>

                        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.FirstName).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.LastName).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                        @Html.Bootstrap().ControlGroup().DropDownListFor(m => m.Gender, ViewBag.GenderList as SelectList).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                        @Html.Bootstrap().ControlGroup().Class("input-append date").TextBoxFor(x => x.DateOfBirth).Size(InputSize.BlockLevel).AppendIcon(Icons.calendar).ShowValidationMessage(true, HelpTextStyle.Block)
                        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Email).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)

                        <legend>Contact Details</legend>

                        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Street).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)

                            @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.City).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                            @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.State).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                            @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.HomePhone).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block).HtmlAttributes(new Dictionary<string, Object> { { "data-mask", "(99999)(999999)" } })

                            @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.PostCode).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                            @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Country).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
                            @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.MobilePhone).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block).HtmlAttributes(new Dictionary<string, Object> { { "data-mask", "+99 (9999)(999999)" } })

                </fieldset>

                @Html.Bootstrap().SubmitButton().Style(ButtonStyle.Primary)
                @Html.Bootstrap().ActionLinkButton("Cancel", "Index").Style(ButtonStyle.Default)

        }

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/BootstrapFormHelpersJS")
    @Styles.Render("~/Content/BootstrapFormHelpersCSS")
}

Comment: every time I have seen this it is because a list wasn't initialized. Look in the get method and make sure all lists are initialized.
Comment: Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints.
Answer: Hi this is get method of my controller.
[HttpGet]
        public ActionResult Create()
        {
            List<string> genders = new List<string>();
            genders.Add("--Select--");
            genders.Add("Male");
            genders.Add("Female");
            genders.Add("Not Defind");
            ViewBag.GenderList = new SelectList(genders, "--Select--");
            return View();
        }

Comment: I think should have been edited into the question, not posted as an answer.


use of mvc in project

Question: i am a student(8th semester I.T.).i want to know the use of MVC(model view controller)in project...please explain..thanks
Comment: Don't you think your question is a bit overly broad?  Wouldn't it be more help for you to read a tutorial or two and then ask a *specific* question or questions about points you don't understand?
Comment: not really.we have this topic in our syllabus
Comment: What does that mean and how does it relate to my concern that your question is overly broad and fails to demonstrate any initial effort on your part?
Answer: MVC is an architectural pattern which can be used to organize the logic within an application.  Unsurprisingly, it separates the logic into Models (business logic, the bulk of the knowledge in the code), Views (UI display and logic) and Controllers (sort of an eventing model for the UI to interact with the business logic).
This is by no means the only pattern one can use.  But it's a commonly used one and fairly simple to understand.  Whether or not to use it is an architectural decision on a case-by-case (or project-by-project) basis.
Comment: thank u very much david...what i want to know is use of mvc in real life projects
Comment: @garima: The MVC pattern is used in real life projects, yes.  (As opposed to theoretical projects?)  It's not clear what you're asking, really.  Can you be more specific?
Answer: this should get you started:
Java SE Application Design With MVC
Answer: MVC(Model | View | Controller) is a compound design pattern made of several design patterns. If you need to learn this pattern easily learn about the Observer pattern and Strategy pattern which MVC is made of. Models and Views use Observer pattern, there views are observers of models. When ever there is a change in the view, view trigger the controller to update the model. Then controller updates the model and then as View is the observer of the model model updates the view.

use of mvc in project


Twitter Bootstrap: Why do hidden elements affect layout?

Question: I have a three-column fluid layout using Twitter Bootstrap's fluid grid layout system. The three columns are made up of span4 divs. I am also using a jQuery UI script that swaps one element for another within that grid system meaning that, for brief periods of time, I actually have a hidden fourth element in my row. I would have thought that this wouldn't be a problem because the hidden elements are, well, hidden ("display:none").
Here's a jsfiddle: http://jsfiddle.net/dhilowitz/cfZwv/6/
My question is this:
Why are the elements in the row not displaying as a row? If I take that hidden element out, everything works beautifully. Put it back in and my row breaks and displays as two rows.
HTML

Item 1A

Lorem ipsum dolor sit amet, consectetur

Item 1B
This is a node that should be treated exactly like the other ones.

Item #2

Lorem ipsum dolor sit amet, consectetur

Item #3

Lorem ipsum dolor sit amet, consectetur

Answer: Because of this rule in bootstrap:
.row-fluid [class*="span"]:first-child {
    margin-left: 0;
}

The hidden element is still the :first-child.
Comment: Oh, that's interesting. It seems it's actually not so much that the first (hidden) element is the `:first-child` but that the second element (the first *visible* element) is *not* the `:first-child`. If I apply `margin-left: 0` to that second element everything works. Now, if I could only update/override that CSS selector to apply that style to the `:first-visible-child` I'd be golden.
Comment: Here's the quick JavaScript fix: http://jsfiddle.net/dhilowitz/MvcdN/. Since these hidden elements are going to be created dynamically, I can add this class and then remove it as needed.
Comment: you could try `.row-fluid [class*="span"].hide:first-child + [class*="span"]`, though that's a hell of a selector...


maximum modulus principle

Question:
maximum modulus principle:
If a function $f$ is analytic and not constant in a given domain $D$, then $|f(z)|$ has no maximum value in $D$. That is, there is no point $z_0$ in the domain such that $|f(z)|≤|f(z_0)|$ for all points $z$ in it.

«

Corollary:
Suppose that a function $f$ is continuous on a closed bounded region $R$ and that it is analytic and not constant in the interior of $R$. Then the maximum value of $|f(z)|$ in $R$, which is always reached, occurs somewhere on the boundary of $R$ and never in the interior.

Now let $f$ be an analytic function and $z_0\in D$. Let $C_1=\{z: |z|=r_1\}$ be a circle that passes through $z_0$ and assume $|f(z)|\leq|f(z_0)|$ for all $z\in D_1=\{z: |z|\leq r_1\}$.
Let  $C_2=\{z: |z|=r_2\}$ be a circle that passes through $z_0$ and assume $|f(z)|\leq|f(z_0)|$ for all $z\in D_2=\{z: |z|\leq r_2\}$.
Constructing these disks which cover the domain $D$, we have that for any $z\in D_1\bigcup\cdots\bigcup D_k$, we have $|f(z)|\leq|f(z_0)|$, so $z_0$ is a point in domain $D$ that the maximum of $|f|$ in $D$  occur there. this is contradiction to maximum modulus principle.
you may see the picture here:
http://www.freeimagehosting.net/32879
I think somewhere in this constructing is wrong, but I don't know where.
Could anyone help to find the mistake.
thanks.
Comment: Can you copy/paste the question in order to see the question when we type comments?
Comment: I copied the source over. Feel free to edit, though, asd.
Comment: It kind of seems like you're just assuming that $|f(z_0)|$ is as much of a maximum as you need it to be at every step of the construction. Can you do this for a particular $f$ and $D$? Otherwise it's hard to call it a construction.
Comment: @Dylan Moreland. thanks for copying.
Answer: There is no reason why your $z_0$ should be the maximum of $f$ along the boundary of any circle you construct. The maximum modulus principle just says the maximum of $f$ on a disc occurs at the boundary. If $z_0$ is a point on the boundary of a disc $B$, there may be $z_1$ on the boundary of $B$ such that $f(z_1) > f(z_0)$. If that is true then, of course, you may and will find $z_2$ in the interior of $B$ with $f(z_2) > f(z_0)$ but with $f(z_1) > f(z_2)$. There is no way to construct an inductive contradiction as you suggest.
Comment: uhmm -- the maximum modulus principle? Your circles simply cannot constructed the way you are proposing it.
Comment: Exactly! My question is why $z_0$ can not be a maximum of $|f|$ in the $D_i$'s. Is there any lemma or theorem that discard this case.

maximum modulus principle


Make ProFtpd ignore a blank command

Question: Is there a way to make ProFtpd ignore a blank command?
Now it says "500 Invalid command: try being more creative"
This confuses a client ftp program.  The client (which I can't change) issues blank
commands occasionally - it shouldn't... but it does.  Thanks.
Answer: There is no option for that purpose. Apart from editing the sourcecode and compiling ProFTPd yourself there is no way. I wouldn't recommend this option though, because you have to maintain these changes for security updates.
Comment: Thanks.  I was hoping there was some creative way to do it.  eg use filters to turn the blank command into NOOP then ignore that command or something.

Make ProFtpd ignore a blank command


Product of a linear and a monotonically decreasing function

Question: I have the following function $f(x)>0$:
$$f(x)=g(x)(1-k(x))$$
$$\text{with } g(x)>0, 0<k(x)≤1 \text{ and } x \in \Bbb R^+.$$
I know that $g(x)$ is a linear and $k(x)$ a decreasing function with the following properties:
$$g'>0 \text{ and } g''=0$$
$$k'>0 \text{ and } k''>0 \text{ or } k''<0 $$
My question is: Is it possible to prove that $f(x)$ has either no maximum or only one maximum (which is global)?

For this problem it seems quite intuitive to me there has to be only 1 maximum because $g(x)$ is increasing at a constant rate while $(1-k(x))$ is decreasing. Based on the fact that $(1-h(x))$ must be zero at some value for $x$, $f(x)$ can not increase forever and after it reaches a maximum it has to decrease; it is also possible that $f(x)$ is decreasing all the time.
Therefore I came up with another way of thinking about this problem. Based on the values for $g(x)$ and $k(x)$, $f(x)$ is either decreasing or is strictly concave over $x$. Therefore $f(x)$ is strictly-quasi-concave.
This means that the following statement must be true:
$$g(\lambda x_1 +(1-\lambda)x_2 )(1-k(\lambda x_1 +(1-\lambda)x_2 ))>\min(g(x_1)(1-k(x_1)); g(x_2)(1-k(x_2))$$
for $x_1<x_2$. We know that $g(x_1)<g(\lambda x_1+(1-\lambda)x_2)<g(x_2)$ because $g$ is constantly increasing with $x$. The same argument is also true $(1-k(x_1))<(1-k(\lambda x_1 +(1-\lambda)x_2 )<(1-k(x_2))$ because $(1-k(x))$ is monotonically decreasing with $x$. Therefore the product of $g(\lambda x_1 +(1-\lambda)x_2 )(1-k(\lambda x_1 +(1-\lambda)x_2 ))$ must be between $g(x_1)(1-k(x_1))$ and $g(x_2)(1-k(x_2)$. This means that the above statement must be true.
Comment: Also, if $k'>0$ how come $k$ is decreasing?
Comment: Do you mean $(k'>0)∧((k''>0)∨(k''<0))$ or $((k'>0)∧(k''>0))∨(k''<0)$? Also, if the question has been *significantly* altered, in your case the conditions are changed, it would be better post it as a new question.
Answer: It holds
$$f''(x) = -2g'(x)k'(x) - g(x)k''(x) < 0.$$
Hence $f$ is concave and allows only one maximum.
Comment: Yes, it is strictly concave since $f''(x) < 0$. You do not need to argue with the first derivative since the second derivative already implies that $f$ is strictly concave.
Comment: Thank you for your answer. Do you mean strictly concave? Because this would only allow one maximum. Regarding the proof: is it sufficient to say that the first derivative is unclear because $f'(x)=g'(x)-g'(x)k(x)-g(x)k(x)$ is either increasing or decreasing based on the values for $g(x)$ and $k(x)$ but that the second derivative is clearly negative and therefore $f(x)$ is either decreasing or strictly concave?
Comment: Unfortunately I made a mistake in one of my assumptions. I'm very sorry. I edited my post above. In short: I can no longer assume that $k''(x)>0$
Answer: I am suggesting the following example:
$$k(x) = (1+x)^{-\frac{1}{2}}.$$
Then, $0<k(x)≤1 \text{ and } x \in \Bbb R^+.$ Moreover $$k'(x) = -\frac{1}{2}(1+x)^{-\frac{3}{2}} < 0.$$
Finally,  $$k''(x) = \frac{3}{4}(1+x)^{-\frac{5}{2}} > 0.$$
Take for $g(x) = 1+x$. Then,
$$f(x) = (1+x) (1-(1+x)^{-\frac{1}{2}}) = (1+x)-(1+x)^{\frac{1}{2}},$$
which does not have a global maximum.
Comment: You are totally right. What if I change my statement and argue that the above function as either no maximum or only one maximum?


How can I set an EC2 network interface to stop auto-assigning a public IP address?

Question: I launched the majority of my EC2 instances with network interfaces that automatically assign public IP addresses. Now that I no longer want them to have public addresses, is there any way to disable this setting without having to create new interfaces?
Answer: If you launch your EC2 inside a VPC, you can disable auto-assigning public IP address to subnet.
If you launch classic EC2, you can't do it.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#differences
Comment: The problem is that when launching a machine, you can override the subnet setting. The question is, how can this override be removed?
Comment: The documentation mentions that the ENI remembers the subnet setting from when it was create - editing it afterwards won't modify the interface setting. https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#eni-basics


Pegar elemento aleatório de uma List

Question: Tenho uma List<int> numeros
É possível retornar um elemento aleatório dessa lista?
Answer: Você pode fazer da seguinte forma em .net:
var lista = new List<int>{3,5,1,8,4,9};
var rnd = new Random();
var valorAleatorio = lista[rnd.Next(lista.Count)];

Answer: Para uma ter isso em .NET faça:
IList<int> listaNumeros = new List<int>() { 95, 4, 9, 52, 40, 800, 90, 11, 2, 9, 4, 92, 8, 91, 120, 111 };
Random rand = new Random(DateTime.Now.Millisecond);
int resultado = listaNumeros[rand.Next(listaNumeros.Count)]

Exemplo: Demo
Referências:

Construtor Random
Construtor Random (Int32)
Macoratti.net - C# - Gerando números aleatórios
Comment: E' preferivel chamar o construtor de `Random` sem argumentos. O constructor sem argumentos usa `Environment.TickCount` (2^31 valores possiveis) como seed, que tem uma entropia muito maior do que `DateTime.Now.Millisecond` (1000 valores possiveis).
Comment: E' melhor usar o comportamento default. Alem disso, a grandeza do numero e' irrelevante - nao existe degradacao de performance. Muito pelo contrario, existe uma (ligeira) degradacao de performance em usar `DateTime.Now.Millisecond` pois implica fazer parse da data do sistema, interpretar a zona horario, e interpretar os milisegundos da hora actual. `Environment.TickCount` e' uma chamada directa ao kernel e  e', portanto, mais eficiente e garante um resultado mais aleatorio.
Answer: Um acrescento às demais respostas, na forma de um extension method:
private static Random _randGen = new Random();
public static T GetRandomElement<T>(this IList<T> source)
{
    return source[_randGen.Next(0, source.Count)];
}

Answer: Sim. Veja o exemplo a seguir:
    List<Integer> numeros = new ArrayList<Integer>();
    numeros.add(1);
    numeros.add(2);
    numeros.add(3);
    numeros.add(4);
    numeros.add(5);
    numeros.add(6);
    numeros.add(7);

    Random gerador = new Random();
    int index = gerador.nextInt(numeros.size());

    System.out.println(numeros.get(index));

Comment: C#. Botei na tag, porém esqueci de por no escopo da pergunta. Obrigado!
Comment: Puts! Só agora percebi as tags c# e .net. Mas mesmo sendo em java ele pode usar a mesma lógica.

Pegar elemento aleatório de uma List


Optimizing Apache Subversion Configuration - Remove duplicate config blocks

Question: I have a repeating authentication block for each of my repositories and was wondering, if there is a way to reuse the block and optimize our setup.
This setup enables us to browse to code.domain.com to view all the repositories and browse the source code (as all repositories are open for read).
Here is my current configuration:
<VirtualHost *:80>
    DocumentRoot /u01/subversion/repositories
    ServerName code.domain.com
    ServerAdmin firstname.lastname@example.com

    <Location />
        Options Indexes MultiViews FollowSymLinks IncludesNoExec
        Order allow,deny
        Allow from all
    </Location>

    <Location /repoA>
        DAV svn
        SVNPath /u01/subversion/repositories/repoA
        SVNIndexXSLT "/share/svnxslt/svnindex.xsl"

        AuthzSVNAccessFile /u01/subversion/svnrepos.acl
        AuthName "Source Code Repository / Repertoire de code"

        AuthBasicProvider ldap
        AuthType Basic
        AuthzLDAPAuthoritative off
        AuthLDAPURL "ldap://domain.com?sAMAccountName" NONE
        AuthLDAPBindDN "bindDN"
        AuthLDAPBindPassword bindPwd
        Satisfy Any
        Require valid-user
    </Location>

    # duplicated Location for repoB, repoC, etc...

</VirtualHost>

I found this (and implemented it), however, I get the following error:
[Fri Jul 26 14:41:37 2013] [error] [client x.x.x.x] (25)Inappropriate ioctl for device: The URI does not contain the name of a repository.  [403, #190001]
Configuration file:
<VirtualHost *:80>
    DocumentRoot /u01/subversion/repositories
    ServerName code.domain.com
    ServerAdmin email@example.com

    <Location />

        Options Indexes MultiViews FollowSymLinks IncludesNoExec
        Order allow,deny
        Allow from all

          DAV svn
          SVNParentPath /u01/subversion/repositories
          AuthBasicProvider ldap
          AuthzLDAPAuthoritative Off
          AuthLDAPURL "ldap://domain.com?sAMAccountName" NONE
          AuthLDAPBindDN "bindDN"
          AuthLDAPBindPassword "bindPwd"
          AuthType Basic
          AuthName "Use your sAMAccountName to connect. If you're unsure, write to contact@...com."
    </Location>

    <Location /repoA>
      SVNPath /u01/subversion/respositories/repoA
      Satisfy Any
      require valid-user
    </Location>

    # Other Locations for each repoB, repoC, etc...
</VirtualHost>

Worst case, I keep the redundant configuration I guess.
Update #1
Almost there... can't browse the root of the domain however - get a 401 error...
<VirtualHost *:80>
    ServerName code.domain.com
    ServerAdmin email@example.com

    DocumentRoot /u01/subversion/repositories/
    <Directory /u01/subversion/repositories/>
        Options Indexes MultiViews FollowSymLinks IncludesNoExec
        Order allow,deny
        allow from all
    </Directory>

    <Location />
        AuthBasicProvider ldap
        AuthType Basic
        AuthzLDAPAuthoritative off
        AuthName "SVN Repository. Authorization required."
        AuthLDAPBindDN "bindDN"
        AuthLDAPBindPassword "bindPwd"
        AuthLDAPURL "ldap://domain.com?sAMAccountName" NONE
        AuthzSVNAccessFile /u01/subversion/svnrepos.acl
        SVNParentPath /u01/subversion/repositories

        Satisfy Any
        Require valid-user
    </Location>

    <Location /repoA>
        DAV svn
        SVNPath /u01/subversion/repositories/repoA
         SVNIndexXSLT /share/svnxslt/svnindex.xsl
    </Location>

    # Other Locations

</VirtualHost>

Update #2
I'm getting this error now when browsing the root only:
Directory index forbidden by Options directive: /u01/subversion/repositories/
However, I see that Indexes is present in the Option declaration in the Directory directive...
Update #3 (Lazy Badger proposed solution)
When I access the root, I see .xsl and .css files and not the repositories. However, /svn/ will list the repo, but the end goal is to have /svn/ be the root of the site instead.
<VirtualHost *:80>
    ...

    # /u01/subversion-docs is where .xsl and .css reside
    DocumentRoot "/u01/subversion-docs"

    <Directory />
      Options Indexes MultiViews FollowSymLinks IncludesNoExec
      AllowOverride None
      Order allow,deny
      Allow from all

      RewriteEngine on
      RewriteCond %{REQUEST_URI} ^/svn$
      RewriteRule ^(.*/svn)$ %1/ [R=301,L]
    </Directory>

    <Location /svn/>
      DAV svn

      SVNListParentPath on
      SVNParentPath /u01/subversion/repositories
      SVNIndexXSLT "/svnindex.xsl"

      ...

      Satisfy Any
      require valid-user

    </Location>

</VirtualHost>

Comment: How much of the content is duplicated between the blocks.  While a dynamic config may be slicker, some include statements could help.
Comment: @jeffatrackaid all of it really. Copy and paste the location block and change the paths.
Answer: I'm using the following config in production environment
<VirtualHost *:80>
    ServerAdmin email@example.com
    ServerName svn.example.net

    DocumentRoot /vhosts/svn.example.net/
    <Directory /vhosts/svn.example.net/>
        Options -Indexes
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    <Location />
        AuthBasicProvider ldap
        AuthType Basic
        AuthzLDAPAuthoritative on
        AuthName "SVN Repository. Authorization required."
        AuthLDAPGroupAttribute memberUid
        AuthLDAPGroupAttributeIsDN off
        AuthLDAPBindDN uid=w3-ldap_reader,ou=system,ou=users,dc=example,dc=net
        AuthLDAPBindPassword 7654321
        AuthLDAPURL ldap://127.0.0.1/dc=example,dc=net?uid?sub
        Require ldap-group cn=svn,ou=groups,dc=example,dc=net
    </Location>

    <Location /Soft>
        DAV svn
        SVNPath /svn/soft
        AuthzSVNAccessFile /etc/svn/svn-soft.conf
        SVNReposName "Software repository."
        SVNIndexXSLT "/svnindex.xsl"
    </Location>

    <Location /Education>
        DAV svn
        SVNPath /svn/education
        AuthzSVNAccessFile /etc/svn/svn-edu.conf
        SVNReposName "Education repository."
        SVNIndexXSLT "/svnindex.xsl"
    </Location>

    <Location /Vacation>
        DAV svn
        SVNPath /svn/vacation
        AuthzSVNAccessFile /etc/svn/svn-vacation.conf
        SVNReposName "Vacation repository."
        SVNIndexXSLT "/svnindex.xsl"
    </Location>

    <Location /NDA>
        DAV svn
        SVNPath /svn/NDA
        AuthzSVNAccessFile /etc/svn/svn-nda.conf
        SVNReposName "NDA repository."
        SVNIndexXSLT "/svnindex.xsl"
    </Location>
</VirtualHost>

Comment: This is much better than mine for sure ....  or combine the two ideas an dputh each location it its own conf file.  I like modularity as it makes it easier to clone configs and fewer errors.
Comment: @alex-hha I'm really close... I can see the individual repositories fine, however, root gives me 401... I've added Satisfy Any and require valid-user....
Comment: I am not a webdav guru but your root probably needs a SVNPath, SVNREposName and xslt.
Comment: @alex-hha I'm not longer seeing a 401... however, I'm not getting a listing of repositories either... see update #2
Comment: I have 3 files in the virt doc root - index.html, svnindex.css  and svnindex.xsl. The index.html I have created by myself. It contain just у welcome message.
Answer: I'm sorry, but you must to read and remember some ABCs before going deeper

Single <Location> can handle any amount of Subversion repositories (if they are childs of common directory)
Single AuthzSVNAccessFile can handle any amount of repositories and paths inside these repositories
Directives, defined in <Location> container, are inherited in subpaths of location, if not explicitly redefined

If you business-task is really

Have a collection of repositories with common LPAD-authentication and
  XSLT-based templating of HTML-pages with path-based authorization

Let's transform my ugly draft (VisualSVN Server default config used, less important parts skipped) into functional solution for your case
...
ServerRoot SOME/PATH/TO/SERVER
...
DocumentRoot "htdocs"
...
<Directory />
  Options FollowSymLinks
  AllowOverride None

  RewriteEngine on
  RewriteCond %{REQUEST_URI} ^/svn$
  RewriteRule ^(.*/svn)$ %1/ [R=301,L]
</Directory>
...
<Location /svn/>
  DAV svn

  SVNListParentPath on
  SVNParentPath /PATH/TO/PARENT/OF/REPO/DIR
  SVNIndexXSLT "/svnindex.xsl"
...
  AuthName
  AuthType Basic
  AuthBasicProvider file
  AuthUserFile "...htpasswd"
  AuthzSVNAccessFile "...authz"

  Satisfy Any
  require valid-user

...
</Location>
...

Notes

ServerRoot defined in order to use relative paths later
DocumentRoot doesn't correlate with DAV-location later and it's ordinary (not WebDAV) part of site, which contain template for SVNIndexXSLT directive
WebDAV location moved out of root of site in order to have "normal" part of site for ordinary http

First change: basic auth replaced by LDAP-powered
<Location /svn/>
  DAV svn

  SVNListParentPath on
  SVNParentPath /PATH/TO/PARENT/OF/REPO/DIR
  SVNIndexXSLT "/svnindex.xsl"
...
  AuthBasicProvider ldap
  AuthType Basic
  AuthzLDAPAuthoritative off
  AuthName "SVN Repository. Authorization required."
  AuthLDAPBindDN "bindDN"
  AuthLDAPBindPassword "bindPwd"
  AuthLDAPURL "ldap://domain.com?sAMAccountName" NONE
  AuthzSVNAccessFile "...authz"
  Satisfy Any
  require valid-user
...
</Location>

Second change: SVNParentPath
<Location /svn/>
  DAV svn

  SVNListParentPath on
  SVNParentPath /u01/subversion/repositories/
  SVNIndexXSLT "/svnindex.xsl"

Third change: ServerRoot+DocumentRoot
Define these roots somehow, don't forget to place svnindex.xsl and all other needed files to DocumentRoot
Fourth change
Add ACLs to AuthzSVNAccessFile, write paths inside collection of repo as [REPO:/PATH/IN/REPO]
Comment: I couldn't use a serverRoot, but I specified a documentRoot with my .css and .xsl. Now, if I navigate to the root, I see the .css and .xsl... However, this should show all my repositories instead...
Comment: @TekiusFanatikus - check `SVNIndexXSLT` directive
Answer: You may want to use Includes.  Still some redundancy but would allow most of your configuration to be set in one file.
Really depends on your goals and how often you maintain these files.
See:  http://httpd.apache.org/docs/current/mod/core.html#include
One technique I've used is to use a directory to hold all of the locations.  Include this directory in your main apache configuration.
Include /etc/httpd/conf/svn.d/*.conf

Then in svn.d/*.conf I create one file per instance.  Say, repoa.conf.
In repoa.conf, I include another file that has the standard stanzas for all repos.
To add a new repo, I just copy repoa.conf to repob.conf, update paths, restart.
Not pretty but quick and easy.


Dealing with very tall textboxes and pagination in SSRS 2005

Question: I have a report in SQL Server Reporting Services 2005.  It makes use of a page header and footer and has no subreports.  The body portion contains a few smaller elements and then a simple single column table.  The table has a single header row and a single detail row.  The header is just a label, basically.  The detail row is a single textbox with a simple Fields!FieldName.Value as its output.
The problem is that FieldName, in this case, is a highly variable length string.  It can be a sentence up to 8000 characters (usually no more than 2 pages worth).  The text can contain line/paragraph breaks (returns) but no other special formatting.  Everything is fine so long as the content fits on one page.  Once the text exceeds a single page (8.5x11), the text is very nastily cut off abruptly.  Since this is a pagination problem, it is only visible when exporting to PDF or when viewing the report in Print Layout.
It seems as though there is a maximum size the row can grow to on the first page and then it chops it off and starts it up on the second.  But this cutoff is not carefully managed in relation to the text.  It can occur right in the middle of a line, causing it to show the top halves of the letters on the first page and the bottom halves at the top of the second page.
Obviously, this is unacceptable, as it looks very unprofessional and can impair the readability of the line that was so messily split.  I also can never be sure it'll split badly, as sometimes it more or less ends the page evenly, though usually I can still see the hanging tails of certain letters on the next page (g and p for instance).
The secondary problem is that I'd really like the table row header to repeat on each page.  Setting the obvious property, "RepeatOnNewPage" has no effect.  I suspect this is because it's still trying to show the single really vertically tall row.  It seems like it's okay repeating headers and splitting pages nicely between detail rows.  But because this is basically just a big block of text, and thus just one really tall row, it doesn't split it nicely.
What can I do or use to solve this problem?  I can live without the repeating header so long as it just doesn't cut off text in the middle of a line.
Answer: Unfortunately, page break fine tuning is one of the biggest weak points of SSRS.
I can only suggest that you break up the long text into multiple rows before SSRS ever gets it. You'd want to parse the text to look for word breaks. The result will be odd looking breaks in the output since you won't know where the break will come on a line in the printed report. However, it'd be much more readable than cutting text in half.
If the text is comprised of reasonably sized paragraphs, you could parse it out that way instead.
You might even go so far as to measure the text using SQLCLR and the System.Drawing.Graphics.MeasureString method to fine tune the output but I wouldn't recommend that route for the feint of heart.
Answer: In SSRS 2008 R2 and Visual Studio 2008:
Click (not-right click) a textbox and go to the properties window (lower right side of VS) -> KeepTogether = false.
The text will cleanly cut between a line and continue on the next page.
Just thought to add here as searching for this doesn't return many results.
Answer: In the end, the cut-off-text problem was due to non-standard padding on the textbox in question.
For whatever reason, having padding any greater than the defaults (2pt all around) seemed to cause its pagination to go sour.  I imagine it is due to the algorithm not taking padding into consideration when deciding where to break the paragraph.  With default padding, the line always ends cleanly and nicely on each page.
As a workaround (since I liked the extra white space the padding gave to the layout), I used a rectangle to achieve the border and made the textbox inside it smaller than the rectangle by about an eighth of an inch.  This gave the box some inner padding while still apparently allowing the pagination to correctly determine when to break up lines.
Still, a lot of unnecessary headache.
Answer: I have done what JC has suggested in the past where I've broken down the text into paragraphs and each paragraph would in effect be its own row. Works pretty well given the limitations of SSRS.
One thing to be careful about is that you would need to make sure that your paragraphs sort properly. In most cases it would display them in the correct order, but adding in a column with sortID to give some sorting hints to the table would probably be a good idea.


Views Data Export Module not including the custom added rows in a view

Question: I have created a view for commerce orders where format is tabular and they are grouped by email of order owner. So basically each group of record shows how many orders are placed by a given email id.I need to have a extra row in each grouped results which is basically summary of order(showing cumulative order total) so I used views_summarize module and got it done. Now I need to have export views as csv or xls functionality so I put views_data_export module but it seems the row added by views_summarize is not included by csv or xls generated by views_data_export.
I also tried including the row using hook_views_pre_render(), and I am seeing the row is getting added in the views page under preview but when I export the views in csv again the row does not appear.
Here is code
function mymodulename_views_pre_render(&$view) // don't forget to replace my_module with your modules name
{
  if($view->name == "paid_partner") {
    if($view->current_display = "paid_partner_csv" || $view->current_display = "paid_partner_xls") {
      foreach($view->result as $submission) {
        $order_total_summary += $submission->field_data_commerce_order_total_commerce_order_total_amount;
        $quantity_total_summary += $submission->commerce_line_item_field_data_commerce_line_items_quantity;
        $currency = $submission->commerce_order_total_amount_currency_code;
      }
    $price_display = commerce_currency_format($order_total_summary, $currency);
    // insert a 'total' row
    $row = new stdClass();
    $row->order_id = "Order Summary";
    $row->users_commerce_order_mail = "Order Total Summary";
    $row->commerce_line_item_field_data_commerce_line_items_quantity = $quantity_total_summary;
    $row->field_commerce_order_total[0]['rendered'] = array(
      '#markup' => $price_display,
      '#access' => TRUE,
    );
    $view->result[] = $row;
    }
  }
}

What can I do to include the summary row with each grouped record in exported csv or xls.
Answer: Views Data Export does not render your results in a traditional way, so render hooks are not executed. But you should be able to alter results using hook_views_post_execute:

This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

Emphasis mine - that's what you should to to alter content not only for display purposes, but in generic, usage-independent way.
Comment: @arpitr glad it helped :)


Is an SEM the correct choice in this case?

Question: I want to do some research about how having one specific disease affects the well-being of people. Therefore, I have disease as my independent variable and well-being as the dependent one. In between, there are many mediating and moderating variables such as depression and self-esteem that are neagtively affected by the disease and which influence the people's well-being. Those mediating and moderating variables intercorrelate as well. There already is a lot of reserach on how having the disease affects e.g. depression and self-esteem and different research on how depression and self-esteem affects the well-being so that I could draw a theoretial model from that. However, it is still unclear how those mediating and moderating variables interact and how big their individual influence on the well-being is.
To change that, I'd  like do an Structural Equation Model so that I can graphically show in the end how all variables interact and how big their individual influences are. All in all, I'd have about 9 mediating and moderating variables like depression, anxiety, ADHD, living situation and so on.
My questions now are the following:
1) Can I use a SEM in this case or do I have to many interacting mediating variables?
2) Would you suggest using any other statistics instead?
3) Would it be correct to first build two independendant SEMs for the disease and non-diesease group and then to combine those two in a next step?
Any comments or help is very much appreciated; thank you in advance!
Comment: I guess one of the biggest problems might be my sample size: I only have 200-300 participants in the disease group. With that it might be impossible to have that many paths?
Answer: Structural equation modeling is useful for problems where one must analyze two things:

Structural model: identifies potential causal relationships between endogenous and exogenous variables, and
Measurement model: identifies relationships between latent variables (hypothetical constructs) and their indicators (operationalized measurements)

More detail is required to provide a more specific answer to your question, but in any analysis, Occam's Razor is relevant. Use the least complicated form of analysis that allows you to establish a null hypothesis and the conditions under which it would be rejected.
Regarding your sample size question, it is advisable to conduct a statistical power analysis to determine the minimum sample size required to effectively discern an effect of a particular magnitude. See Sample Size Requirements for Structural Equation Models: An Evaluation of Power, Bias, and Solution Propriety for additional background on this topic.