What is the rationale behind using the t-distribution?

Question: (Probably a very naive question.) According to this tutorial,

Student's t-test deals with the problems associated with inference based on "small" samples: the calculated mean and standard deviation may by chance deviate from the "real" mean and standard deviation (i.e., what you'd measure if you had many more data items: a "large" sample).

So then why is the t-distribution and the t-test ideal for such a purpose?
Put differently, the t-test estimates the probability of the null hypothesis that two normal distributions have the same mean. So if we know that two sampled distributions are (reasonably) normal then why not just compute their means and compare?
Comment: "then why not just compute their means and compare?" ... How are you gonna *compare* if you only got the difference in the means? What is your scale that defines a big or small difference? Right, you also need to use the samples to compute (estimates of) the deviation. To "know" that the distributions are reasonably normal is not sufficient for the calculations you had in mind.
Answer: Martijin comment is essential. Before understanding the t-test, you should understand the z-test: why and how and to adjust the scale for the difference.
Then, what motivates the t-test (from the z-test) arises from the uncertainty in estimating the standard deviation. For the intuition this text is very good about t-test and z-test.
Answer: You use a t-test, as opposed to a z-test, when the population SD is unknown so you use the sample SD instead. The larger the sample, the more tenable this is, and why the t distribution approaches the normal distribution as the sample size increases.
Answer: I'm guessing from your question wording that you believe the t distribution is chosen as if from a set of tools for the purposes of describing small samples.  However, in this case, it's derived.  That is, under the right assumptions, the t distribution arises mathematically, so there aren't any other choices.  It's the unique solution to the problem of describing sample statistics under those assumptions.
If you want to see the derivation, look at the Wikipedia article about halfway down under "Characterization > Deriviation".
With that in mind, the question of whether or not to use it comes down to whether you think the assumptions are true for a particular case.  Also, since the t converges to a normal, with "big enough" sample sizes, some people do exactly as you suggested.  Again, it hinges on the interpretation and conclusion the statistician makes about the assumptions.  (How small is "small", how "normal" do you believe your data are, etc.)
Comment: T test is the only one??
Answer: An experiment, a sample from a population, will be subject to variation. However, this variation is not simple and it may be due to 1) uncontrolled and/or 2) controlled variables.
In many practical cases we wish to find out:

not only the presence of a difference, if there is a certain target size exceeded in some measured value (e.g. a difference between two groups, or a variation of a single group from a theoretic value)
but also the quality of the difference, whether we can ascribe the difference in the measured value  to the controlled variables.

The t-score, combines those two, and is an indicator of the size of some measured value in relation to the random (uncontrolled) variation in this value.
To get an idea of the random (uncontrolled) variation, the trick is to have some measurements in which the controlled variables do not change.

I hope that provides some intuition. The more deeper question 'why is the t-test ideal' is more difficult.
The t-test is ideal, given that assumptions are true. And in practice it works very well for a wider range of situations. However, at what point to use some other test, and what test, such questions are hard.
From another perspective of ideal: The t-test is 'just' a hypothesis test and may not always be considered a very good practice (p-value hacking, neglecting the true research questions which are replaced by tests, etcetera). Certainly, it does not provide the entire picture and downgrades the multidimensional data to a single one-dimensional value and a final yes/no question.
Answer: Since the title of your question is regarding the "Rationale behind using the T-Distribution", I will (attempt) to answer in broad terms and only go into specifics if necessary.
The overall answer is that the T-Distribution gives a higher probability to extreme events, given a small sample size. The reasoning behind this is intuitive in that, as you can imagine, if you have relatively small sample from a population, there is a higher probability that an extreme event from the population did not "make it" into your sample. On the other hand, if you have a relatively large sample from the same population, the probability that an extreme event did not "make it" into your sample is lower, since your sample is capturing more of that population.
Visually, the T-distribution looks like a Normal Distribution with a slightly lower "peak" and slightly "fatter" tails. In this picture, the Normal Distribution is the blue density and the T-Distribution is the red.
The term "small" is relative, although generally speaking is relates to samples where $N\leq30$. However, the T-Distribution is defined in terms of Degrees of Freedom, where $\textrm{degrees of freedom} = N-1$. This is where the intuition of the T-Distribution approaching the Normal Distribution as $N$ increases comes from.
Since $N$ is our denominator in calculating the mean, variance, etc, replacing the $N$ with $N~-1$ will have a larger effect when $N$ is small. For example:

Given a sample where $N~=~30$, the difference between the mean using $\frac{\sum_{i=1}^{30} x_i}{30}$ and the mean using $\frac{\sum_{i=1}^{29} x_i}{29}$ will be a lot greater than,
Given a sample where $N~=~10,000$, the difference between the mean using $\frac{\sum_{i=1}^{10,000} x_i}{10,000}$ and the mean using $\frac{\sum_{i=1}^{9,999} x_i}{9,999}$.

So, pulling back from the math to the visual representation, as $N$ increases, the T-Distribution will asymptotically approach the Normal Distrubtion, since the negative one (-1) in the definition of degrees of freedom has a ever decreasing effect as $N$ increases.
Using statistical terms, the T-Distribution allows your estimate to be unbiased when using a small sample, meaning the estimated statistic from your sample will be closer to the population statistic you are trying to estimate.
Answer: First of all, we must assume the data are normally distributed.  Then for a sample of size $n$, the distribution of the sample average is student $t$ with $n-1$ degrees of freedom.  In small samples, this corrects the tail behavior due to the uncertainty about the nuisance parameter, the standard deviation.
Comment: Although I believe that's what you had in mind, Michael, clearly that's not what your post actually says.  These comments have evidently been posted to encourage you to improve your answer to change it from something that's obviously wrong into what you intended to write.  Although users are allowed to edit any post, here on CV people are very reluctant to edit each others' answers (perhaps because many of them involve subtleties): we have instead evolved a culture of suggesting ways to improve answers and hope the owners of those answers will respond positively to those suggestions.
Comment: The distribution of the sample mean for samples from a Normal distribution is *normally* distributed!  It's the distribution of the sample statistic $\frac{\bar x}{\frac{\hat \sigma}{\sqrt{n}}}$ that is student t distributed.
Comment: Matthew is correct, the statement in this answer: "*for a sample of size n the distribution for the mean is student t with n-1 degrees of freedom*" is wrong.
Comment: I am quite sure I was talking about the test statistic as having exactly a t distribution when the  population distribution is normal.


Guardar e-mail de visitantes (Newsletter) com codeigniter

Question: Bom dia pessoal, sou iniciante em PHP e em codeigniter. Preciso de uma luz, até encontrei o que eu preciso mas não em codeigniter (Pois meu site está em mvc).
Este foi o encontrado e funcionou no meu localhost https://github.com/pinceladasdaweb/Ajax-PHP-MySQL-Newsletter , mas eu não tenho como usa-lo afinal não possui Model e Controllers, e nao consigo entender ainda muito bem o Model no codeigniter.
Alguem possui entendimento do assunto e pode me ajudar?
Minha intenção é receber o E-mail e Nome da pessoa por meio de um modal em bootstrap e guardar no meu banco de dados para futuros envio de e-mails a eles.
Comment: Não é so criar um form simples e depois recuperar os valores com `$this->input->post('nome');`
Comment: Usa o [active record](http://www.codeigniter.com/userguide2/database/active_record.html) do CI. Esse projeto do github nada mais é que um form, um php para manipular o `$_POST` gravar no banco e enviar por email, essa lógica vc pode fazer com o CI de forma bem facil, o css desse projeto vc pode aproveitar caso tenha gostado.
Comment: Não entendi @rray, se eu fizer isso eu posso jogar num banco? como?
Answer: Tente o seguinte:
VIEW
<form method="POST" action="http://www.seusite.com.br/usuario/newsletter">
    Nome
    <input type="text" id="nome" name="nome" required />
    E-mail
    <input type="email" id="email" name="email" required />

    <input type="submit" value="Enviar" />
</form>

CONTROLLER
<?php
class Usuario extends CI_Controller {

    public function __construct() {
        parent::__construct;

        /* Preferencialmente carregue esses helpers e libraries no arquivo
           application/config/autoload.php
        */
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    }

    public function newsletter() {
        $this->form_validation->set_rules('nome', 'Nome do usuário', 'required');
        $this->form_validation->set_rules('email', 'E-mail do usuário', 'required');

        if ($this->form_validation->run()) { // Se os dados foram recebidos com sucesso
            $nome = $this->input->post('nome');
            $email = $this->input->post('email');

            /* Carrega a classe que trata da tabela do usuário no banco.
               Este método pega como referência a pasta application/models.
               Se a classe a ser carregada estiver em algum subdoínio, este deve ser informado também. pe.: $this->load->model('dao/UsuarioDAO');
            */
            $this->load->model('UsuarioDAO');
            $this->UsuarioDAO->cadastrarDadosUsuario($nome, $email);

            // Busque inserir códigos de tratamentos de erros caso o banco gere algum erro.

        } else {
            // código de tratamento de erro...
        }
    }
}

MODEL
<?php
class UsuarioDAO extends CI_Model {

    public function __construct() {
        parent::__construct;

        /* Preferencialmente carregue no arquivo application/config/autoload.php
           A conexão deve estar configurada no arquivo application/config/database.php
        */
        $this->load->database();
    }

    public function cadastrarDadosUsuario($nome, $email) {
        $this->db->query("INSERT INTO usuario (nome, email) VALUES (?, ?)", array($nome, $email));

        // Inserir código de tratamento de erros...
    }
}

Comment: Exatamente o que eu precisava... excelente Paulo ! muito obrigado!
Comment: Foi boa. Disponha! :)


Sites and services design for branches those having same subnet

Question: I have 2012 domain and about 50 of workstation and servers together in it at branch (A) and now I get another branch (B) with about another 75 workstations and servers (domain 2012). I need to consolidate them in one bigger network. I am willing to implement sites and services. But thing is that right now both branches has networks 192.168.0.0/24.
I have never done this before on my own and I did read the instructions but it got me confused what be the right way to get things done.
I am thinking to switch one of branches adresses to 192.168.1.0/24 network. I am not quite sure what to do the best about all it. How is the best practice designs would work on that kind of cases?
Comment: Setting AD Sites and Services aside you'll need to renumber one of the networks if you intend to have arbitrary IP communication between hosts in both locations. I'd also do yourself a favor, from a VPN perspective, and not use 192.168.1.0/24 in either location. That network is used by a _lot_ of home NAT routers. I'd pick something else entirely.
Answer: If you have the same subnet stretching both sites, you can't effectively use AD Sites & Services. It requires different subnets per site. As you've said - switching one site to 192.168.1.0/24 (or any other unsused subnet for that matter) and defining both subnets and assigning one to each site is the basics of what you need to do.
If you ever grow to more than two sites, you'll need to consider site links, but that doesn't matter in a 2 site topology.


Why did I get HTML 404 error while view and action method exists?

Question: In my project, I added action method in SistemGaleri controller and then put related view.
Action method name: GaleriIslemleri
View Name: GaleriIslemleri.cshtml which is located on View/SistemGaleri folder
<code>    public ActionResult GaleriIslemleri()
    {
        var sistemGaleriDosyaAramaKriter = new SistemGaleriDosyaAramaKriter();
        try
        {

        }
        catch (Exception ex)
        {
            //HelperUtils.CmsLogger.Error(ex, "Duyuru/Liste");
        }

        return View();
    }
</code>
Comment: put here your address url and check rout config in start up.
Comment: @hassan.ef Normally this is my url: localhost:4850/SistemGaleri/GaleriIslemleri but my project consists of a lot of modules, and i did not see defined url in route config for every module.
Comment: How do you set up routing in your app? Attribute-based or convention-based?
Comment: it depend about your project, how do you set up routing?
Comment: @vasily.sib convention based routing but every module did not set up on route config. I dont think that problem depends on route config. I did not faced the problem other modules
Comment: Can you show us how do you setup your routes?
Comment: @vasily.lib you can check out my config file on below comment
Answer: <code> public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{query}",
            defaults: new { controller = "AnaSayfa", action = "Index", query = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Dosya",
            url: "{controller}/{action}/{Id}/{query}",
            defaults: new { controller = "Home", action = "Index", query = UrlParameter.Optional },
            constraints: new { Id = "\\d+" }
        );
        routes.MapRoute(
     name: "Dosya Duzenle History",
     url: "{controller}/{action}/{query}/{ishistory}/{Id}",
     defaults: new { controller = "Dosya", action = "DosyaDuzenle", ishistory = UrlParameter.Optional, query = UrlParameter.Optional },
       constraints: new { Id = "\\d+" }
 );

        routes.MapRoute(
            name: "Dosya Versiyon Ekle",
            url: "{controller}/{action}/{Id}/{query}/{ParentRaporId}",
            defaults: new { controller = "Dosya", action = "DosyaVersiyonEkle", query = UrlParameter.Optional },
            constraints: new { Id = "\\d+", ParentRaporId = "\\d+" }
        );

        routes.MapRoute(
           name: "History",
           url: "{controller}/{action}/{ishistory}/{query}",
           defaults: new { controller = "AnaSayfa", action = "Index", ishistory = UrlParameter.Optional, query = UrlParameter.Optional }
       );

        routes.MapRoute(
           name: "raporPaylasim",
           url: "{controller}/{action}/{kod}/{tarih}/{optional}",
           defaults: new
           {
               controller = "Rapor",
               action = "RaporPaylasim"
               ,
               kod = UrlParameter.Optional
               ,
               tarih = UrlParameter.Optional
               ,
               optional = UrlParameter.Optional
           }
           ///, constraints: new { kategoriKod = "[a-zA-Z0-9._-]+" }
       );
    }
}
</code>
@vasily.lib you can check out my config file


How to use a string to get the respective image drawable

Question: private int imageres[] = {
    R.drawable.desk,
    R.drawable.bed,
    R.drawable.chair,
};

private String typeofplace[] = {
    "Desk", //0
    "Bed", //1
    "Desk", //2
    "Chair", //3
    "Bed", //4
    "Chair", //5
};

for (int i = 0; i < typeofplace.length; i++) {
    //how do I get the image (int) based on the `typeofplace`:
    // MyFunction(imageres[R.drawable.{typeofplace}]);
}

Dow do I get the image (int) based on the typeofplace:
MyFunction(imageres[R.drawable.{typeofplace}]);

Answer: I think that there is a better approach to do that, you don't need a HashMap or a string array with the typeofplace. If you know the name of your drawable, simply use:
int imageId = getResources().getIdentifier("desk", "drawable", getPackageName());

Comment: `for (int i = 0; i < typeofplace.length; i++) {
        doSomething(getResources().getIdentifier(typeofplace[i], "drawable", getPackageName());
}`
Comment: So I can use this inside the forloop, and replace `desk` with the array index?
Comment: The point is that if you know the name of your drawable, for example, desk (the resource will be R.drawable.desk) and you want to use it, you can use just the line that I wrote to get the id, so you don't need to save in a hashmap the name, "desk", and the resource R.drawable.desk, because the system can find for you the drawable if you give it the name.
Comment: Disadvantage is that of the resource has to be the same as the resource name. Desk wil referfer to R.drawable.desk. If you're gonna use other formats like R.drawable.ic_desk you've got a problem.
Comment: For some reason I have it working but even through the drawable exist some of them doesn't show up
Comment: AHA!!! Now it makes sense because some of them have space for the typeofplace and doesn't have in imageres...
Answer: You can use a HashMap:
private String typeofplace[] = {
    "Desk", //0
    "Bed", //1
    "Desk", //2
    "Chair", //3
    "Bed", //4
    "Chair", //5
};

...

HashMap hm = new HashMap();
// Put elements to the map
hm.put("Desk", R.drawable.desk);
hm.put("Bed", R.drawable.bed);

for (int i = 0; i < typeofplace.length; i++) {
    doSomething(hm.get(typeofplace[i]));
}

Comment: So will I need one instance of, let's say Desk and it will work no matter how many times it appears? I have the other two variables and now I am creating a third one?
Comment: change just MyFunction(hm.get("Bed"));
Comment: So I think I can get rid of the entire `imageres` array than... am I right?
Comment: Yes, imageres can be removed since we will use a HashMap instead. I changed also the example code, I hope you will understand it.
Comment: Got it. Thanks. So much easier :)
Comment: I get this error: `Syntax error on token(s), misplaced construct(s)`
Comment: Am I using, `import java.util.HashMap;`?
Comment: Correct, you have to use `import java.util.HashMap;` For some reason I don't get an error.
Comment: I get this warning when I initialize: `HashMap is a raw type. References to generic type HashMap should be parameterize`
Comment: Do it like this: `HashMap hm = new HashMap<>();`


CSS3pie - styles not being picked up in IE. How to reference the path?

Question: I've downloaded and enabled the css3pie and libraries modules, and downloaded and extracted the PIE Library to sites/all/libraries/PIE
I initially tried adding the css selectors to admin/config/user-interface/css3pie but because that wasn't working I've now added them in my mysite.info:
settings[css3pie][selectors][] = "#block-block-1"
settings[css3pie][selectors][] = "#block-block-8"
In my css file C:\Projects\mysite\sites\all\themes\mysite\css\layout.css
I've put the following:
block-block-1, #block-block-8 {
<code>background: red;
padding: 2em;
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
border-radius: 1em;
behavior: url(C:/Projects/mysite/sites/all/libraries/PIE/PIE.htc);
</code>
}
The PIE libraries is here:
C:\Projects\mysite\sites\all\libraries\PIE\PIE.htc
What am I missing and doing wrong?
I have a feeling I've got the path wrong :(
Of course you will need to adjust the path to match where you uploaded PIE.htc in step 2. Note: this path is relative to the HTML file being viewed, not the CSS file it is called from.
How do I reference the path correctly?
Answer: The PIE Drupal module should add the behaviour where necessary, you don't do that yourself. This would defeat the point of the Drupal module, and in using the Drupal module you don't need to specify the path yourself. (Though your current path there is incorrect, but I'm not sure on the correct way right now.)
css3pie can seem very touchy, there is a long list of known issues, some of which could be causing your problem. Also ensure that your files directory is writable, and that there are no errors on your sites status page. File permission problems can prevent the css3pie module from creating it's stylesheet. Each setting in the themes .info file should also be on a new line.


THREE.js - morphTargetInfluences on an imported JSON mesh not getting results

Question: I have a basic three.js scene in which I am attempting to get objects exported from Blender (as JSON files with embedded morphs) to function and update their shapes with user input.
Here is a test scene
http://onthez.com/temphosting/three-js-morph-test/morph-test.html
The slab is being resized without morphs by simply scaling a box, which is working just fine.
I must be missing something fundamental with the little monument on top.  It has 3 morphs (width, depth, height) that are intended to allow it to resize.
I am using this code to implement the morph based on users dat.gui input.
<code>folder1.add( params, 'width', 12, 100 ).step(1).name("Width").onChange( function () {
  updateFoundation();
  building.morphTargetInfluences['width'] = params.width/100;
  roofL.morphTargetInfluences['width'] = params.width/100;
  roofR.morphTargetInfluences['width'] = params.width/100;
  building.updateMorphs();
});
</code>
The materials for building, roofL, and roofR each have morphTargets set as true.
I've been going over the three.js examples here:
http://threejs.org/examples/?q=morph#webgl_morphtargets_human
as well as #webgl_morphtargets and #webgl_morphtargets_horse
Any thoughts or input would be much appreciated!
Answer: I believe I've reached a solution for my question  I was under the impression that the JSON loader was preserving the morph target names to be used in place of an index number with morphTargetInfluences
something like morphTargetInfluences['myMorphTargetName']
but, after closer inspection in the console it seems like they should be referred to by number like morphTargetInfluences[0]
Not the most intuitive, but I can work with it.
Comment: To expound on this a bit further, I notice morphTargetDictionary[] can help with this by associating the name of each morph target with it's assigned index. Using myObject.morphTargetInfluences[myObject.morphTargetDictionary['myMorphTargetName']] = 1; gets the proper morph target and applies the value.


finding specific solution to $u_{tt}-u_{xx}=x^2-t^2$ with boundry conditions $u(x,0)=\frac{-x^4}{16}-x, \ u_t(x,0)=1, x \in R$

Question: I am analyzing  the following PDE
$$u_{tt}-u_{xx}=x^2-t^2$$
with boundary conditions $$u(x,0)=\frac{-x^4}{16}-x, \quad u_t(x,0)=1, \quad x \in R$$
I understand how to derive the general solution no problem, just cannot figure out how to get the specific solution which supposed to be $\ \ \mathbf{u(x,t)=\frac{-(x^2-t^2)^2}{16}+t-x}$

I got the following general solution
$$u(x,t)=\frac{-(x^2-t^2)^2}{16}+F(x+t)+G(x-t)$$
applying the first condition $u(x,0)$
I get $$F(x)+G(x)=-x$$
applying second condition $u_t(x,0)=1$ I get
$$F'(x)+G'(x)=1$$
how should this be continued? where the t (second term of the final specific solution) comes from?
Comment: Did you check your result $u(x,t)=\frac{-(x^2+t^2)^2}{16}+F(x+t)+G(x-t)$ ? You just have to put it in the PDE and see if it agrees. You will see that there is a mistake.
Comment: this was a typo in Latex, I corrected it. I got the following equation using the correct general solution.
Comment: I mean I got $F(x)+G(x)=-x$ and $F'(x)+G'(x)=1$ but still cannot figure out how to get the final equation out of it.
Answer: $$u(x,t)=\frac{-(x^2-t^2)^2}{16}+F(x+t)+G(x-t)$$
$$u_t=\frac{-(x^2-t^2)t}{4}+F'(x+t)-G'(x-t)$$
$\begin{cases}
u(x,0)=-\frac{x^4}{16}+F(x)+G(x)=-\frac{x^4}{16}-x \quad\to\quad F(x)+G(x)=-x \\
u_t(x,0)=F'(x)-G'(x)=1  \quad\to\quad F(x)-G(x)=x+c
\end{cases}$
$$\begin{cases}
F(x)=\frac{c}{2} \quad\to\quad F(x-t)=\frac{c}{2}\\
G(x)=-x-\frac{c}{2} \quad\to\quad G(x-t)=-(x-t)-\frac{c}{2}
\end{cases}$$
$u(x,t)=\frac{-(x^2-t^2)^2}{16}+\frac{c}{2}-(x-t)-\frac{c}{2}$
$$u(x,t)=\frac{-(x^2-t^2)^2}{16}-x+t$$


.htacess for removing public/index.php works good in root and not in sub directories

Question: Here is my .htaccess which i have default in laravel it helps me to prevent typing public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    RewriteEngine On
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

So, if i need to access
localhost/public/index.php/home
localhost/public/index.php/login

It is enough to me to type
localhost/home
localhost/login

I want to make exception to for few directories such as 'testproject' and 'betaproject' i.e., where i will have a regular php or html directory or i will have another fresh project and it will have same .htaccess also.
How can i modify my .htaccess file to make it possible.
So that if i want to access
localhost/testproject/public/index.php/home should be accessible by localhost/testproject/home
Answer: In your root .htaccess have this rule to skip 2 directories:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(testproject|betaproject)/(\w+)/?$ $1/public/index.php/$2 [L,NC]

Make sure this rule is very first just below RewriteEngine On line.


Does there exist any integer $ n> 1$ for which $6^{2n}-25$ is prime?

Question: I got this question on a test and I am really curious hoe you would approach it. I tried to prove stuff using the congruence laws but I didn't manage to prove anything.
Answer: We have $$N=6^{2n}-25=(6^n-5)(6^n+5)$$
none of these factors equal $1$(unless for $n=1$), Therefore $N$ is always composite.
Answer: Hint:  You are looking at a difference of squares.


.htaccess RewriteRule help

Question: I have been able to change the 'location' of my images with RewriteRule, but I have 3 lines of code to do this because of subdirectories in the image folders
RewriteRule ^images/([^/]+).(jpg|jpeg|bmp|gif|png)$ /includes/images/$1.$2
RewriteRule ^images/([^/]+)/([^/]+).(jpg|jpeg|bmp|gif|png)$ /includes/images/$1/$2.$3
RewriteRule ^images/([^/]+)/([^/]+)/([^/]+).(jpg|jpeg|bmp|gif|png)$ /includes/images/$1/$2/$3.$4

However, I would like to be able to not need to add to these if I ever add any deeper subdirectories.
I have tried many different approaches to this with no luck, and the following is what I am stuck with atm.
RewriteRule ^(images)(/?[^/])+(.jpg|.jpeg|.bmp|.gif|.png)$ /includes/$&

Does anyone have any ideas on how to get this code to work??
Also, is there any way to view the URL that is being used server-side?
Answer: Perhaps I'm missing something, but I don't see any reason that you couldn't simply do:
RewriteRule ^images/(.+)\.(jpg|jpeg|bmp|gif|png)$ /includes/images/$1.$2

.htaccess RewriteRule help


First Request to IIS Express Fails with 503 Service Unavailable, Second Succeeds

Question: Each time I start my ASP.Net MVC 3 app from Visual Studio 2010, IIS Express launches and IE spins waiting. The request fails with HTTP 503 Service Unavailable. I hit Refresh in IE, and the request succeeds. All subsequent requests succeed until I stop debugging. The next time I go to start debugging, the first request fails again.
Has anyone else experienced this?
In IISExpress\applicationhost.config I have:
<site name="ProjectName" id="6">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
            <virtualDirectory path="/" physicalPath="c:\users\chris\dropbox\code\2010\SolutionName\ProjectName" />
    </application>
    <bindings>
            <binding protocol="http" bindingInformation="*:80:laptop" />
    </bindings>
</site>

I have this in my hosts file:
127.0.0.1    laptop

And my Project is set to start with IIS Express, with Project Url set to:
http://laptop

It's very strange that only the first request fails, perhaps as though Visual Studio isn't waiting long enough for IIS Express to start? Is there some way to make it wait?
Stopping debugging, making a change, and then starting again is one of the most common tasks I do so adding another step to get there is pretty annoying.
Comment: This is not an Answer but I think this deserves follow-up: This did in fact turn out to be a problem with Visual Studio. Once 2 years passed and the next version came out, I upgraded, and this problem was resolved.
Answer: IIS Express supports Failed Request Tracing and it's turned on by default. The logs are written to %IIS_USER_HOME%\TraceLogFiles which is usually at this location:
%USERPROFILE%\Documents\IISExpress\TraceLogFiles

In that folder you'll see a list of subfolders for each of the projects you've run up in IIS Express. In each site's folder there should be a bunch of frXXXXX.xml files and a freb.xsl file.
Using Firefox or Internet Explorer, open the frXXXXX.xml file(s) that has a time stamp closest to when you get these 503 errors. Once opened you'll see something like the following:

Hopefully you should discover the cause of the 503 error.
You could also try and start IIS Express for your project manually from the command line:
C:\Program Files (x86)\IIS Express>iisexpress /path:"[PATH]" /port:16444

Where [PATH] is the file system path to your project folder containing the site code, web.config etc, for example in your case it would be:
c:\users\chris\dropbox\code\2010\SolutionName\ProjectName

This might throw up some interesting errors if IIS Express can't start the site for the first time.
As an aside you can also tell Visual Studio to "Attach to Process" and start debugging that way.
Answer: The first and foremost action you need to take, is to determine what actually happens.
To do so, turn on Detailed Error Pages for local requests:
appcmd.exe set config -section:system.webServer/httpErrors -errorMode:DetailedLocalOnly /commit:apphost

Now all 400 and 500 class http returns will cause IIS to display a much more detailed error page.


How to do multiline substitution using sed?

Question: I have a text file named "a6s" with multiple lines like this:
y
n
yyy
n
y
yyy
yy
y
yyy
n

I used this script:
$ sed -i "s/y$^y/ya\ny/g" a6s;

I want to insert between two "y" chars at ending of last line and the beginning of next line to output:
y
n
yyy
n
ya
yyya
yya
ya
yyy
n

Comment: (^_^)  Sorry, my English is not good! Thanks to Sundeep.
Answer: Using GNU sed (full credit for this great solution goes to @Sundeep, thanks):
sed -i '/y$/ {N; s/y\ny/ya\ny/; P; D}' a6s

In order to work on multiple lines with sed, you have to use N, P and D commands:

{cmds}: group of commands
/y$/ {cmds}: executes the group of commands only if the line ends with y
N: reads next line to the pattern space
s/regex/replacement/: does the substitution, no need for the g flag
P: prints the pattern space up to the first \n character (first line)
D: deletes the pattern space up to the first \n character

My original solution that used unnecessary labels:
sed -i ':a; N; s/y\ny/ya\ny/; {P; D}; ba' a6s

I recommend checking out this great grymoire.com tutorial on working with multiple lines.
Comment: Since you are only comparing at most two lines and the substitution command caters for two lines, perhaps `sed 'N;s/y\ny/ya\ny/;P;D' file` might be suffice?
Comment: @potong Yep, that would do too. `/$y/` only skips the commands if they are not needed :)
Comment: Thanks to PesaThe and Sundeep.
Comment: Thanks to potong. Your script is brief.
Answer: sed is for simple subsitutions on individual lines, that is all. When you try to do anything else with it you are using arcane runes that became redundant in the mid 1980s when awk was invented. With GNU awk for multi-char RS:
$ awk -v RS='^$' -v ORS= '{while(sub(/y\ny/,"ya\ny"));} 1' file
y
n
yyy
n
ya
yyya
yya
ya
yyy
n

The above simply does what it clearly says - loops through the input replacing every y\ny with ya\ny while there are y\nys to replace.
Comment: @PesaThe this is similar to `sed -z ':a s/y\ny/ya\ny/g; ta'` (assuming input doesn't have NUL characters)... you can't use gsub here because once `y\ny` gets replaced, the second `y` won't be available for matching with next line..
Comment: @Sundeep so it wouldn't work correctly for `y\ny\ny` for example, got it, thanks :)
Comment: awk can do gsub() but remember that in any tool a string matching a regexp can't be part of the next regexp segment matched on that same invocation so `sed 's/yy/yay/g` won't change `yyy` into `yayay`, you need `sed 's/yy/yay/g; s/yy/yay/g'` to do that. So I could have used gsub() but it wouldn't have done every replacement, I'd need a loop or 2 invocations for that so I decided to go with a loop to avoid redundancy and when you have a loop, sub() works as well as gsub() and IMHO it's a bit clearer.
Comment: it is clear :) was trying to make a cheeky comment.. should've added `/s` or some smiley..
Comment: @PesaThe Yeah, sed is great for `s/old/new` and before awk was invented you needed to be able to do a bunch of other stuff with it and unfortunately since it's just a stream editor rather than a programming language all of it's commands are cryptic single characters but that was 40+ years ago - time to let it rest... I really wish the GNU guys had removed all of that extra crap from it instead of adding even more crap!
Comment: Oh and by the way, what is the reason for using `while (sub...` instead of `gsub`? I suppose it's a portability thing?
Comment: any tool --> any tool without lookarounds... `perl -0777 -pe 's/y\n(?=y)/ya\n/g'`
Comment: any tool --> any tool evaluating the regexp in question. The string `y` at the end of `y\n(?=y)` does not become part of the regexp match but I'm not sure how to phrase my previous statement to more clearly express that I'm talking about strings that are included in the regexp match other than just saying THIS regexp. I suspect the point is made though.
Answer: Converting the inputfile to a line is not an easy solution: you need to process the file twice:
tr '\n' '\r' < a6s | sed ':a;s/y\ry/ya\ry/g;ta' | tr '\r' '\n'
or
tr '\n' '\r' < a6s | sed 's/y\ry/ya\ry/g;s/y\ry/ya\ry/g' | tr '\r' '\n'


Programa em Java que vem com JRE

Question: Quero criar um programa em Java, mas que a pessoa não precise ter o Java instalado no computador dela. Tem como eu colocar uma JRE junto do meu programa com apenas as classes necessárias?
Um exemplo:
Eu criei um programa e só usei a classe System e as classes que System chama. Não tem como eu fazer um JRE com apenas as classes que estão sendo usadas?
Fora isso, o que eu mais preciso é que eu tenha a JRE junta do programa, e quando eu colocar o programa no pc da pessoa, ele instala a JRE (compactada ou não) e o programa consegue rodar
Conseguiu entender? Se não, me avise.
Comment: Igor, pelo que entendi o que você deveria fazer é criar um instalar personalizado que iria instalar/atualizar o java além de instalar seu software. Procure por softwares criados de instalação que isso pode resolver seu problema
Comment: Se usar JavaFX é exatamente o que ocorre quando usar o [Native Packaging](https://blogs.oracle.com/talkingjavadeployment/entry/native_packaging_for_javafx).
Answer: Você pode adicionar o JRE (ou JDK dependendo da sua aplicação) ao diretório de instalação do seu programa. Para isso, baixe o JRE em formato compactado (tar.gz) e descompacte em um diretório dentro do diretório de instalação do seu programa. Quando for executar o seu programa, utilize o executável do Java que está nesse novo diretório.
Exemplo:
Supondo que você queira usar o JRE 1.7 em um ambiente windows 7 de 64bits, voce deveria fazer o download nesse link do arquivo jre-7u67-windows-x64.tar.gz.
Se o seu programa usar a estrutura abaixo:

bastaria descompactar o JRE em um diretório, por exemplo jre_interno.
Depois é só editar o arquivo bat para usar o novo JRE.
Importante
Como não foi instalado, esse JRE em específico não será atualizado automaticamente (a não ser que você também faça isso) podendo comprometer a segurança do ambiente.
Comment: Muito bom. Só mais uma coisa: o código do bat seria pra executar o arquivo java.exe? Tipo: jre/.../java Programa.class
Comment: @IgorCostaMelo exatamente.

Programa em Java que vem com JRE


EntityFramework Multiple Queries Multiple DataContexts? Multiple Connections?

Question: I'm new to EF, and for the first time I need to execute multiple queries in the same time, lets say I have my BLL and DAL generated by EF, I also have a viewModel, on the BLL I'm referencing DAL and retrieve data like this:
public Decimal getPrice()
    {
        Decimal x = 0;
        siliconContext = new DAL.Entities();
        var result = from d in siliconContext.SILICONs
                     select d.MIN_PRICE;
        foreach (Decimal d in result)
        {
            x = d;
        }
        return x;
    }

all good, on the viewModel I use just this two lines of code:
Silicon sil = new Silicon();
Price = sil.getPrice();

I assumed that the Context will handle the connection, open the connection, do something and then close it, but now I'm in a situation where in my ViewModel I will reference two BLLs which they are going to reference two DALs and of course two different Contexts in the same method, who is going to manage this? is EF 4 is smart enough to open only one connection and let the two - or more - contexts to do their job and then close the connection? here is an example of how my viewModel will look like
Silicon sil = new Silicon();
Price = sil.getPrice();
Glass gl = new Glass();
GlassPrice = gl.getPrice();

Answer: You would need to manage the lifetime of your objectcontext for their proper initialization and disposal. For an excellent resource on context lifetime management, refer to http://blogs.msdn.com/b/alexj/archive/2009/05/07/tip-18-how-to-decide-on-a-lifetime-for-your-objectcontext.aspx
Comment: Thanks for the link , going to see it in a while
Answer: First off you need to close the connection of the DataContext.
public Decimal getPrice()
{
    Decimal x = 0;
    using (DAL.Entities siliconContext = new DAL.Entities())
    {
        var result = from d in siliconContext.SILICONs
                     select d.MIN_PRICE;
        foreach (Decimal d in result)
        {
            x = d;
        }
        return x;
    }
}

Secondly if you want to get data from two tables then do the following.
public Decimal getPrice()
{
    Decimal x = 0;
    using (DAL.Entities siliconContext = new DAL.Entities())
    {
        var result = from d in siliconContext.SILICONs
                     select d.MIN_PRICE;

        var result2 = from d in seliconContext.GLASEs
                      select d.MIN_PRICE;

        //You can then work with results from table GLASE!

        foreach (Decimal d in result)
        {
            x = d;
        }
        return x;
    }
}

Comment: thanks for the reply , I only have one database , in my example I'm trying to retrieve from  two tables , Silicon and Glass , I understood your first code snippet , the second however doesn't reply my questions , are you saying for only one database and multible tables I will still use one context ? , how can I do that then ? to accomplish my last code snippet ?
Comment: agree, I understood something new now, but still please see the last code in my post , I have two different classes(Silicon and Glass) , every class will reference it's DAL class and every DAL class will connect to database on his own ,because every class will execute it's own getPrice() method, thats means two different connections, conections will open and close one after another , for perfromance sake thats is not good , I guess this is a design issue but I'm not sure , I hope you got my point
Comment: Yes, you are bit worried about preformace with always opening and closing the connection to the database. I personlly prefer this method where the life of the connection is only "alive" for that specifiy unit of work so to say. I wouldn't be too concerned about the performance. Also Ragzitsu showed a really good link that will help explain most the questions you have. Hope this helped.


Hibernate: Incrementar a partir de um valor específico

Question: Criei um atributo do tipo Integer chamado matrícula e quero que, quando o usuário for se cadastrar, o valor dessa matrícula seja gerado automaticamente e salvo no mysql a partir de um certo valor(Ex: 95000) e conforme outros vão se cadastrando, será a última matrícula usada + 1 (95001, 95002...).
Tem como fazer isso com o Hibernate?
Answer: Não sei se entendi direito mas vamos lá. Vou assumir que você já possui um banco MySQL rodando e que precisará recuperar a última (maior) matrícula utilizada e utilizá-la para determinar qual o número da matrícula do novo cadastro que está criando.
Primeiro de tudo, utilize uma query para poder recuperar os valores das matrículas e compará-las entre si para descobrir qual é a maior.
private int getUltimaMatricula() {
  EntityManager em = createEntityManagerFactory();
  em.getTransaction().begin();
    Query q = em.createQuery("SELECT t.coluna1 from tabela t where t.campo1 = :campo1");

    // campo1 e o que voce ira utilizar para recuperar as matriculas, utilizando jpql
    // neste caso.
    q.setParameter("campo1", campo1);

    List<Integer> result = q.getResultList();

  int maiorNumero = Integer.MIN_VALUE;

  for(i=0; i<result.size(); i++){
    if (result.get(i) > maiorNumero)
      maiorNumero = result.get(i);
  }

  em.getTransaction().commit();
  em.close();

  return maiorValor;
}

Depois isso, chame este método dentro do seu método "persist" ou algo do tipo e utilize o número retornado +1 para determinar o número da nova matrícula.
Qualquer dúvida, comente aqui.
Answer: Consegui!
Segui a sua ideia e fiz assim:
private void gerarMatricula(Aluno a) {

    session = HibernateUtil.getSessionFactory().openSession();
    transaction = session.beginTransaction();
    query = session.createQuery("select matricula from Aluno");

    List<Integer> result = query.list();
    if (result.isEmpty()) {
        a.setMatricula(45100); //O primeiro aluno cadastrado receberá a matricula 45100,

    } else{
        int maiorNumero = Integer.MIN_VALUE;

        for (int i = 0; i < result.size(); i++) {
            if (result.get(i) > maiorNumero)
                maiorNumero = result.get(i);

        }
        a.setMatricula(maiorNumero + 1);
    }

}

Depois chamei esse método no meu "persist":
public void create(Aluno a) throws Exception {

    session = HibernateUtil.getSessionFactory().openSession();
    transaction = session.beginTransaction();
    gerarMatricula(a);
    CriptografarSenha cs = new CriptografarSenha();
    cs.criptografia(a); //Criptografar a senha
    session.save(a);
    transaction.commit();
    session.close();

}

Obrigado pela ajuda!
Comment: Foi "Obrigado pela ajuda" mesmo, rsrs, porque eu sou o autor da pergunta, mas quando eu perguntei, ainda não estava cadastrado. Perguntei como convidado, por isso o nome está diferente. Postei a solução para ajudar caso alguém precise.
Comment: Você quis dizer `Obrigado pela ajuda!` ou `De nada pela ajuda!` ? rs.. Pois aparentemente você resolveu o problema do autor da pergunta, ou estou enganado?
Comment: Você pode mesclar suas contas entrando em contato pela página: http://pt.stackoverflow.com/contact assim você poderá reaver a autoria da pergunta e aceitar a resposta que mais lhe ajudou, caso considere-a assim.


Com flexbox, centralizar lista alinhando itens a esquerda

Question: Estou usando o Bootstrap 4, conforme documentação (https://getbootstrap.com/docs/4.0/utilities/flex/).
Utilizando a classe justify-content-center eu tenho o seguinte resultado:

Minha div está com as classes: d-flex flex-wrap justify-content-center
Eu gostaria que estes itens menores ficassem centralizados na página, porém, que sua última linha ficasse alinhada a esquerda, desta maneira:

É possível? Aceito sugestões de outra maneira para chegar no mesmo resultado, mesmo que não utilize o Flexbox. Preciso que a solução seja "responsiva", podendo servir para qualquer tamanho e quantidade de elementos.
Comment: Não entendi bem sua pergunta.. Você deseja obter o resultado como na segunda imagem, certo? Porém quando abri o seu link do codepen, o resultado foi igual ao da segunda imagem, [veja esse print](http://prntscr.com/ibbsh7)
Comment: Olá @celsomtrindade, acabei atualizando o CodePen após a primeira interação com o usuário dvd. Retornei agora para o código original. De qualquer modo, ele resolveu meu problema usando JavaScript. Obrigado.
Answer: Creio que conseguirá isto agrupando as divs dentro de uma div-mãe e usando os eventos resize e load (para ajustar no carregamento da página) do jQuery para setar uma largura nesta div do tamanho exato até que caibam o máximo de divs .item dentro dela.
Não precisa mexer em nada no seu código original, apenas criar uma div com um id qualquer (coloquei id="items") e agrupar, veja:

$(window).on("load resize", function(){
   var content = $(".content.d-flex").width();
   var items = $(".item").outerWidth(true);

   var items_width = Math.floor(content / items);

   $("#items").css({
      'max-width':items_width*items+'px'
   });
});
.content {
  max-width: 500px;
  margin: 0 auto;
  border: 1px solid black;
  margin-bottom: 50px;
}

.item {
  width: 100px;
  height: 100px;
  margin: 2px;
  background: gray;
  float: left;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Comment: Olá dvd, esqueci de mencionar que estou pensando na responsividade, sendo as três colunas somente um exemplo. Com seu código, ele já não funciona diminuindo a tela, resultando em:

[![Coluna com dois itens][1]][1]

[1]: http://i68.tinypic.com/o0huc.jpg
Comment: Não consegui abrir a imagem.
Comment: Sou novo no fórum e não estou sabendo anexá-la ao meu comentário. Segue URL: https://uploaddeimagens.com.br/imagens/responsivo-jpg Para ver esse resultado, basta redimensionar a tela com o seu código.
Comment: Atualizei o Codepen: https://codepen.io/natodp/pen/EQgogR basta redimensionar a janela de visualização.
Comment: Blz, vou dar uma olhada aqui e te retorno
Comment: Tranquilo, obrigado!
Comment: @natodp Atualizei a resposta. Creio que só vai conseguir via JS. Abs!
Comment: Tranquilo, me atende. Valeu!


Why is the "Configurations" option not displayed for an Azure DevOps user?

Question: Our organization has the Azure DevOps Test Plans service.
This particular user is a member of a team where members have the following permissions set to Allow (Inherited).

Create test runs
Delete test runs
Manage test configurations
Manage test environments
View test runs

Nonetheless, the Configurations option does not appear in the left navigation panel under Test Plans, so that the user cannot view or otherwise manage test configurations.
Other members of the team do see the Configurations menu item.
I am assuming this is something permission based, and specific to this user, but when I inspect the user's permissions, they're all set to Allow (Inherited), so I can't figure out what's wrong.
Can anyone provide any insight regarding the solution or cause?
Answer: This turned out to be caused by a missing extension in Azure DevOps. We needed to install the Test Manager extension and then assign users to the extension.
Although I still don't understand why some users were able to see the Configuration menu without holding a license for Test Manager; I assume it had something to do with holding a license for Visual Studio Enterprise while others only had licenses for Visual Studio Professional.
Answer: I can think of two issues that might also be the cause of your issue, but none that have to do with the DevOps Test Plan Servies directly.
1. User is a member of a group that has a deny set. (This happened to one of our users for some settings in the Wiki, as some groups had a deny set, even though the user was a collections administrator and the view for the actual permissions of the user was not giving correct effective permissions. Check your other users if they have other group memberships or are missing group memberships compared to problematic user)
2. The user does not have the license enabled. (Happened to us with the NuGet-Repository, where some users where not added with their Visual Studio Subscriber License but only basic and could therefore not access the internal NuGet-Respository. It was the only feature that required a visual studio subscriber license for us and because we still had free basic licenses when adding the user to the system, the person in charge forgot to also change the access level and only added him to the system but not with the right license -> yourorgnamehere.visualstudio.com/_settings/users -> check the user's access level, we were lucky and the user got the html error code 402 = payment required that led us to the right track of the issue)
Comment: I'll look into this as a potential cause, but it would be really strange, as one of the users experiencing the issue is the *owner* of the DevOps system, administrator of the impacted teams, and a DevOps admin. It's all very strange.


Qual a relação entre unhashable e mutabilidade?

Question: Eu sempre uso strings como chaves em dicionários, mas, estudando o tema, notei que é possível usar qualquer objeto imutável. Então, além de strings, dicionários aceitam como chaves objetos como inteiros, floats e tuples. Todos os exemplos abaixo funcionam:
d={"name":"Lucas", 1:'01', (9,10):3}
type(d) #dict

No entanto, se definirmos um dicionário usando listas como chaves, temos o erro TypeError: unhashable type: 'list'. Eu não sei bem o que é hashable, mas li nesta pergunta que tabelas hashes permitem pesquisas eficientes e, ao que me parece, dicionários são um exemplo desse tipo de implementação (isso explicaria o porquê de dicionários serem muito mais eficientes para busca que listas). Mas qual a relação com um objeto ser hashable e sua mutabilidade? A restrição de não usar objetos mutáveis como chaves de dicionário é algo específico do python ou comum a todas as linguagens? Por que dessa restrição?
Comment: Acho que vale mencionar o início [desta resposta](/a/27915/112052): "*dizer que hashes são mais rápidos que listas encadeadas é comparar laranjas com bananas*" - cada estrutura de dados possui prós e contras, e casos em que uma é mais adequada que outra. Aproveitando, atualizei minha resposta (o exemplo anterior com `random` não estava muito bom) :-)
Answer: Imagine que você tem uma lista:
lista = [1,2,3,4,5,6,7,8,9,10]

Se você quiser verificar se um elemento está presente nessa lista, o Python irá precisar percorrer elemento a elemento e comparar um a um:
if (11 in lista): #Irá comparar 11 com 1, depois 11 com 2, depois 11 com 3...

Apenas após comparar todos os elementos da lista ele pode ter a certeza que não achou o elemento que você quer. Um exemplo na vida real seria você procurar um CD de música em um álbum que não está organizado. Você precisa ir página por página até achar (ou não).
Se sua lista tivesse muitos elementos a sua busca demoraria mais.
Dicionário, por sua vez, não importando a quantidade de itens que ele contém, demora em média sempre o mesmo tempo para acessar o conteúdo de uma chave. Um paralelo com a vida real seria você procurar uma palavra em um dicionário. Como ele está organizado alfabeticamente, você sabe exatamente aonde achar a definição (Ou por exemplo se os CD's do exemplo anterior tivessem sido organizados de alguma forma).
Como ele faz isso? As chaves do dicionário precisam ser Hashable (com um neologismo poderíamos dizer Hasheáveis). Não vou entrar em detalhes sobre essa implementação, dado que a outra resposta citada na pergunta já faz isso bem. Mas basicamente o que uma função Hash faz é:
Alguma coisa -> | Função Hash | -> Inteiro (exemplo: 7036520087640895475)

Isto é, se você fornece alguma coisa para essa função, ela calcula um inteiro baseado neste conteúdo fornecido. Boas funções Hash prometem (mas não garantem) que conteúdos diferentes gerem inteiros diferentes, dentre outras características. Nem sempre isso é possível, e é justamente nesse caso em que o acesso pode ser mais demorado. Quando dois conteúdos diferentes geram o mesmo valor, diz-se que houve uma colisão.
Quando você adiciona um par chave-valor ao dicionário, basicamente o que ele faz é:

Calcula o hash da chave que você forneceu. Exemplo: (Chave "Azul" gerou o hash 123)
Armazena o valor em uma posição da memória vinculada a essa hash 123.

(Se for mais didático, ou mais fácil de entender, pode-se pensar que cada dicionário tem uma lista, e segundo o exemplo acima salva na posição 123 dessa lista. Embora a implementação verdadeira não seja bem assim pois teria muitos "espaços vazios".)
Se em uma ocasião futura você quer acessar o conteúdo de uma chave, você não precisa percorrer todos os elementos do dicionário. Você pode simplesmente calcular novamente o Hash, ir nessa posição da memória e verificar o item que está lá. Por isso o acesso (e verificar se contém) demoram tempo constante independente do tamanho do dicionário. Ele vai direto na posição da memória que o objeto está.

Mas qual a relação com um objeto ser hashable e sua mutabilidade?

O que acontece se o conteúdo desse objeto mudar? Seu hash iria mudar também, e seria impossível localizá-lo no dicionário novamente. Então apenas objetos imutáveis podem garantir uma hash para si.

A restrição de não usar objetos mutáveis como chaves de dicionário é algo específico do python ou comum a todas as linguagens?

Por definição, é algo comum a todas as linguagens. O que pode acontecer que talvez algumas linguagens façam, é utilizar como conteúdo para a hash algum ID do objeto em questão. Por exemplo um ponteiro para o objeto em específico ou algum número que defina esse objeto unicamente. Muitas linguagens permitem você definir sua própria função hash também.
Para uma outra explicação, veja esta pergunta (em inglês).
Comment: Boa resposta! Só para ser pedante, o único detalhe que eu mudaria é "demora sempre o _mesmo_ tempo para acessar o conteúdo de uma chave", já que não existe função de _hash_ perfeita (i.e. que evita qualquer tipo de colisão). Penso que, _em média_, o tempo tende a ser constante, embora isso seja mais probabilístico do que certo.
Comment: "*Boas funções Hash prometem que conteúdos diferentes gerem inteiros diferentes*" - Não, uma função de hash deve garantir que conteúdos iguais gerem sempre o mesmo valor, e conteúdos diferentes **podem ou não** retornar o mesmo. Claro que para ser útil, o ideal é que seja diferente e as colisões não sejam frequentes, mas elas podem existir sim ([exemplo](/a/432159/112052)). E justamente por poder ter colisões que **não** demora sempre o mesmo tempo pra acessar o conteúdo de uma chave, pois o mesmo *slot* pode acabar tendo mais de um valor, conforme explicado [aqui](/q/27827/112052)
Comment: Por isso usei a palavra *promete*. Uma promessa pode ser cumprida, ou não. De qualquer forma, vou editar a resposta para ficar mais didático. Como esse não era o objetivo central da pergunta, acabei não focando muito nessa parte. Adicionarei também que o tempo constante de acesso é apenas no caso médio. Obrigado pelas sugestões!
Answer: Conforme visto na pergunta que você citou, o que as tabelas de hash fazem é calcular o valor do hash de cada chave, para que saibam em qual posição da tabela o elemento ficará.
No caso do Python, objetos podem implementar o método __hash__ para retornar o seu respectivo hash code. E de acordo com a documentação, um objeto é hashable se "o valor do seu hash não muda durante o seu tempo de vida, e pode ser comparado com outros objetos" (em suma, além do método __hash__, ele precisa implementar também o __eq__).
A documentação também cita que objetos que são considerados iguais devem retornar o mesmo valor do hash. Então geralmente o que os tipos imutáveis fazem é retornar o hash baseado no seu valor. E como eles são imutáveis, o valor não muda, e portanto o hash também não.
Isso é importante porque se o hash ficar mudando, o objeto não servirá mais como chaves de dicionários, já que eles usam o valor do hash internamente, para fazer o lookup. Veja este exemplo:
class Teste:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        # implementação simples, retorna o hash do valor
        h = hash(self.value)
        print(f'calculando hash de {self.value}={h}')
        return h

    def __eq__(self, other):
        return self.value == other.value

    def __repr__(self):
        return f'Test({self.value})'

t1 = Teste(1)
t2 = Teste('xyz')
d = {}
print('adicionar 1')
d[t1] = 'abc'

print('adicionar xyz')
d[t2] = 2

print(d) # {Test(1): 'abc', Test(xyz): 2}
print('acessando uma chave')
print(d[t1]) # abc
# mesmo sendo outro objeto, se o hash é o mesmo, ele encontra
print(d[Teste(1)]) # abc

Criei uma classe Teste que é hashable (implementa __hash__ e __eq__, e instâncias iguais sempre retornam o mesmo hash). Usei instâncias dessa classe como chaves de um dicionário, e veja como o método __hash__ é chamado, tanto para setar um valor quanto para recuperá-lo. Repare também na última linha, que mesmo sendo outra instância, ele encontra o mesmo valor, já que o valor do hash retornado é o mesmo.
A saída é:
adicionar 1
calculando hash de 1=1
adicionar xyz
calculando hash de xyz=2899992705165252900
{Test(1): 'abc', Test(xyz): 2}
acessando uma chave
calculando hash de 1=1
abc
calculando hash de 1=1
abc

No caso da string "xyz", o hash pode variar a cada execução do Python, conforme explicado aqui - mas ao longo do mesmo processo, ele permanece o mesmo (aqui também explica isso).

Mas se eu mudar o value do objeto, consequentemente o seu hash code também mudará (já que o método __hash__ se baseia no valor do value):
t1 = Teste(1)
d = {}
print('adicionar 1')
d[t1] = 'abc'

print(d) # {Test(1): 'abc', Test(xyz): 2}
print('acessando uma chave')
print(d[t1]) # abc

# mudando o value, o hash code também muda
t1.value = 2
print(d[t1]) # KeyError

Ao mudar o value, o valor do hash code também muda, e ao tentar usar o objeto como chave, dá erro:
adicionar 1
calculando hash de 1=1
{Test(1): 'abc'}
acessando uma chave
calculando hash de 1=1
abc
calculando hash de 2=2

KeyError: Test(2)

Por isso que objetos mutáveis não são bons candidatos a chaves, pois o hash costuma ser baseado no seu valor (seguindo a regra de que objetos iguais retornam hashes iguais). E se o valor pode mudar, consequentemente o hash também muda, e aí não será mais possível localizar o respectivo valor no dicionário, já que este usa o valor do hash para tal.
Algumas linguagens permitem que objetos mutáveis sejam usados como chaves (e aí você que se vire para garantir que eles não mudarão), mas o Python optou por deixar que apenas objetos hashable possam ser usados como chaves.
Vale lembrar que uma tupla só é hashable se os seus elementos também forem:
d = {}

# tupla só contém elementos hashable
t = (1, 'abc')
d[t] = 1

# tupla contém uma lista, que não é hashable
t = (1, [2, 3])
d[t] = 2 # TypeError: unhashable type: 'list'

Isso é comum a todas as linguagens, já que tabela de hash é um conceito mais geral (Estruturas de Dados), e o que muda é a implementação. Em Python, objetos que não são hashable já dão erro logo que você tenta usá-los como chave de um dicionário. Mas Java, por exemplo, é diferente: todos os objetos possuem uma implementação padrão de hashCode (mas que deve ser sobrescrita para que seja de fato útil). Mas a ideia geral é sempre a mesma: calcula-se um valor de hash para encontrar a posição do elemento na tabela de hash (e se esse valor pode mudar, o objeto não é um bom candidato a chave).
Mais detalhes sobre tabelas de hash podem ser vistos nesta pergunta.


Install openLDAP server on pfsense

Question: I have a pfsense router with 25 clients ( linux and windows ). I want to filter the internet traffic for some of the clients using squid guard.  I have researched the options and I would like to use openLDAP for auth on each client and squid filtering.
I have browsed the pfsense documentation and all I can find is connecting pfense with external openLDAP server but not installing openLDAP on pfSense.
Answer: pfSense is a firewall and it should stay a firewall. Increasing the attack surface by installing other kind of software isn't a very good idea.
Run the OpenLDAP server on different hardware. Using it for 25 users is a very lightweight task that can run on quite a small machine or VM.
Comment: I disagree. The OpenLDAP service doesn't belong onto the pfSense machine and if you need the service, you need the hardware. I don't necessarily recommend this but the OpenLDAP server could potentially be something as simple as a Raspberry Pi.
Comment: It makes sense, but as you pointed out, the network is small and it doesn't worth keeping 2 servers running.

Install openLDAP server on pfsense


Error Unable to copy files settings files from BLT into your repository

Question: When I try to run blt sync I am getting the following error.

blt:init:settings
Hash salt already exists.
[error]  Unable to copy files settings files from BLT into your repository.
For troubleshooting guidance and support, see https://docs.acquia.com/blt/support/
The command failed. This often indicates a problem with your configuration. Review the command output above for more detailed errors, and consider re-running with verbose output for more information.
[error]  Command blt:init:settings  exited with code 1.
For troubleshooting guidance and support, see https://docs.acquia.com/blt/support/
Answer: I got resolved the same problem using the following steps.

run the blt sync with -v   blt sync -vvv
Which will help you to find the cause of the error,

In my case, it was permission for the recipe settings.php file.
So I have to run the chmod command outside the box, then ssh into the box, delete the database and ran the blt acsf:init
After all these I ran the blt sync its worked fine.  Hope this will be helpful for those facing the same issue. :)


representation theory of finite-dimensional algebras

Question: Let $K$ be an algebraically closed field and $\Lambda$ a finite-dimensional $K$-algebra. We know that a representation of $\Lambda$ is:

A ring homomorphsim $\theta:\Lambda \to End_{K}V$, where V is a vector space over $K$.

So, a representation is a $\Lambda$-module (not necessarily finitely generated). My question is that: "Why in most books on this subject, $\mathsf{mod}\Lambda$ is investigated?" By $\mathsf{mod}\Lambda$, I mean the category of finitely-generated $\Lambda$-modules. Why don't they study $\mathsf{Mod}\Lambda$, the category of $\Lambda$-modules?
Comment: In general, starting from the category of finitely-presented modules (here f.p. = f.g.) you can take the Ind-category (https://ncatlab.org/nlab/show/ind-object) to get the category of all modules. Conversely, given the category of all modules you can take compact objects (https://ncatlab.org/nlab/show/compact+object) to get f.p. modules.
Comment: Each of these can be recovered from the other so there's not too much of a difference. Finite-dimensional representations are nicer in several ways, e.g. they have characters because the trace is defined.
Comment: @QiaochuYuan: I cannot understand how Λ-modules can be recovered from finitely generated ones.
Answer: One reason is that many applications, and connections with other areas of mathematics, specifically involve finite dimensional modules. For just one example, there are links to algebraic geometry (e.g., via quiver varieties) that consider spaces of finite dimensional representations.
Another reason is just that there is a lot of theory, from classical results like the Krull-Schmidt theorem to powerful techniques originating with Auslander and Reiten, that only applies directly to finitely generated modules. So the more advanced theory is rather different for finitely generated and infinitely generated modules.
But people do study infinite dimensional modules as well. In fact, there are increasingly frequently cases where, even if you're really only interested in finitely generated modules, studying infinitely generated modules can turn out be a useful tool.


Linq merging two classes into a third?

Question: I am trying to merge 2 classes into a third on the date properties, for binding to a graph I have already setup.
public class Last30DaysHours
{
    public DateTime Date { get; set; }
    public float Hours { get; set; }
    public float LostHours { get; set; }
}

public class MachineHours
{
    public DateTime Date { get; set; }
    public float Hours { get; set; }
}

into
public class GraphLast30Days
{
    public DateTime Date { get; set; }
    public float Hours { get; set; }
    public float LostHours { get; set; }
    public float SelectedMachine { get; set; }
}

So far I have this linq statement which almost compiles.
The error with the current statment is "'x' does not exist in the current context".
I know what this means but I don't know how to make it accessable in the statement.
IEnumerable<GraphLast30Days> last30DaysMachineHoursSelect = _last30DaysMachineHours
            .Select(p => (_last30Days
                            .Where(x => x.Date == p.Date)  <=
                            (new GraphLast30Days {
                                                    Date = x.Date,
                                                    Hours = x.Hours,
                                                    LostHours = x.LostHours,
                                                    SelectedMachine = p.Hours
                                                  })));

My question is how do I make x accessable by the second half of the statement or what is a better statement to achieve the same results?
Thanks for the help.
Answer: You'd wont to use join to join your collections by date (not sure I got the correct proeprties, but you got the idea):
IEnumerable<GraphLast30Days> last30DaysMachineHoursSelect =
        from machineHours in _last30DaysMachineHours
        join last30 in _last30Days on machineHours.Date equals last30.Date
        select
        new GraphLast30Days {
            Date = machineHours.Date,
            Hours = machineHours.Hours,
            LostHours = last30.LostHours,
            SelectedMachine = machineHours.Hours
            };

Or with alternative syntax:
    var result = _last30DaysMachineHours.Join(_last30Days, graph => graph.Date, last30 => last30.Date,
                                             (graph, last30) => new GraphLast30Days
                                                                {
                                                                        Date            = graph.Date,
                                                                        Hours           = graph.Hours,
                                                                        LostHours       = last30.LostHours,
                                                                        SelectedMachine = graph.Hours
                                                                });

In case you don't wont to filter out missing values you'll need to do left join:
IEnumerable<GraphLast30Days> last30DaysMachineHoursSelect =
    from last30 in _last30Days
    from machineHours in _last30DaysMachineHours.Where (h => h.Date == last30.Date).DefaultIfEmpty()
    select
    new GraphLast30Days {
        Date = last30.Date,
        Hours = last30.Hours,
        LostHours = last30.LostHours,
        SelectedMachine = machineHours == null ? 0 : machineHours.Hours
        }

Comment: Looks to be what I am after, just testing it now :) just out of curiosity how would you do it using the style of linq I was using? eg select(x => x.Date)?
Comment: Ok its very close to what I am after but the join isn't what I need. The _Last30Days collection always contaions 30 records but the _last30DaysMachineHours doesn't, this means most of the _Last30Days data is getting dropped and with my current data only 4 points are plotted. Hope i've explained this ok, In sql I think what I am after is a left join on the _last30Days?
Comment: Thank you :) Exactly what I was after

Linq merging two classes into a third?


Caracteres indesejados usando jquery + php

Question: Estou com um pequeno problema, quando uso o append do jquery para exibir elementos retornados de uma consulta php.
Obs: esse não é o append completo, ele é um pouco extenso e coloquei só a parte que preciso que vocês vejam.
$("#topics").append('
'+dados.sumario+'
')

O sumário é um campo na minha tabela de tópicos que é adicionado e editado com uma textarea usando tinymce, o problema é que quando o append exibi o sumário ele está aparecendo todas as tags html vindas do tinymce, exemplo:

É como se não estivesse reconhecendo as tags e exibindo tudo como uma string
Quero que reconheça todas as formatações que o tinymce fizer, como por exemplo bold, italic, ou o embed de um video etc... mas do jeito que estar não vai dar certo
Comment: O motivo pelo qual os carateres são guardados como `<` e `>` em vez de `<` e `>` é evitar esse tipo de ataques. Se tiver a certeza que só tem etiquetas não perigosas nos dados (`
Comment: `console.log(dados.sumario);` mostra o que ? Qual a informação que foi de facto guardada na tabela do banco de dados  ?
Comment: No bd está armazenado tudo em utf8: "teste de tags" e o console.log exibi exatamente o que está no bd @Isac
Comment: `<` é a mesma coisa que `<` logo é apenas a representação do caratere `<` e não o próprio caratere. Se quiser pode literalmente substituir o que vem do banco com `replace` mas tenha cuidado que isso pode ser perigoso no que toca ataques *XSS*, isto é, assumindo que é o usuário que insere dados nessa tabela
Comment: Mas quais são minhas opções então além dessa? @Isac
Comment: A resposta abaixo não resolveu?
Comment: @ÐvÐ deu sim, é que esqueci de por como resolvido.
Answer: Utilize essa função nativa do PHP: html_entity_decode()
Ex.:
<?php
    echo html_entity_decode('<p>teste de <strong>tags</strong></p>');

    // Saída: teste de tags

Recomendo que leia a documentação da função, pois existem outros parâmetros extremamente importantes a serem passados, já que definem o charset da conversão e como será o tratamento das aspas e apóstrofos.