Como posso criar uma lista

Question: Eu preciso criar uma lista, onde a mesma listará todos os itens existente dentro de um pedido.
No método abaixo eu consigo trazer um item, porém não consigo trazer caso tenha mais de um.
A minha dúvida seria, tenho que criar um método no code behind  e na classe não sei como funciona a lógica de listas.
Código(observar a linha [itemPedido]):
protected void ExibirProtocoloPedido(PedidoVenda objPed)
{
    try
    {
       PedidoVendaItens objItPed = new PedidoVendaItens();
       Produtos objProd = new Produtos();

    Session["pedEmpresa"] = objPed.PedEmpresa;
    Session["numPedido"] = objPed.PedNumero;
    Session["msgOfertas"] = (!string.IsNullOrEmpty(objPed.pedMsgOfertas.ToString()) ? objPed.pedMsgOfertas.ToString() : "");
    Session["itemPedido"] = objItPed.ItPProduto + " - " + objProd.ProdDescr + "/" + "Qtde.:" + objItPed.ItPQtde  + " / " + "Total:" + objItPed.ItPrecoComp;
    Session["msgMatApoio"] = (!string.IsNullOrEmpty(objPed.pedMsgMatApoio.ToString()) ? objPed.pedMsgMatApoio.ToString() : "");
    Session["msgReorderGerado"] = (!string.IsNullOrEmpty(objPed.pedMsgReorderGerado.ToString()) ? objPed.pedMsgReorderGerado.ToString() : "");
    Session["msgReorderAtendido"] = (!string.IsNullOrEmpty(objPed.pedMsgReorderAtendido.ToString()) ? objPed.pedMsgReorderAtendido.ToString() : "");
    Session["msgReorderNaoAtendido"] = (!string.IsNullOrEmpty(objPed.pedMsgReorderNaoAtendido.ToString()) ? objPed.pedMsgReorderNaoAtendido.ToString() : "");
    Session["msgPendencias"] = (!string.IsNullOrEmpty(objPed.pedMsgPendencias.ToString()) ? objPed.pedMsgPendencias.ToString() : "");
    Session["valorPedido"] = (!string.IsNullOrEmpty(txtValACobrar.Text) ? string.Format("{0:0,0.00}", txtValACobrar.Text) : "0");
    Session["statusPed"] = objPed.PedStatus;
    Session["formaPagto"] = objPed.PedForPgto;
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowProtocolo();", true);
}
catch (Exception ex)
{
    throw ex;
    }
}

O resultado que me retorna desse método é:

2210 - Devione 125ML / Qtde.: 1 / Total: 15,75
Comment: A primeira coisa que você deve fazer neste código é tirar o `try-catch`, está fazendo nada. Na verdade está fazendo algo, prejudicando o *stack trace*, mas nada útil. Não entendi o que deseja saber. Que listas? Tem muitas. Que lógica? O que quer fazer?
Comment: @bigown Seria listar item a item, separando por linha...
Como eu mencionei na pergunta, esse metódo lista um item. AGora quando tem mais de um item, ele só traz o primeiro item, então queria saber como pode ser criado um tipo de lista
para criar quantidade de linhas de acordo com a quantidade de itens no pedido.
Answer: Você precisar criar um objeto do tipo List PedidoVendaItens
Assim:
List<PedidoVendaItens> objLista = new List<PedidoVendaItens>();

Depois usar o método Add para adicionar os itens à lista.
Answer: Cara, o que entendi pela pergunta é que precisa colocar uma lista de produtos dentro da sessão. é isso?
Se for, você não consegue colocar a lista como um objeto. Vai precisar serializar a sua lista.
Se for este o caso, recomendo o newtonsoft.
Caso não seja esta a pergunta, pode me esclarecer um pouco mais?

Como posso criar uma lista


Seeking some details about what is denoted by the partition function $P(n,k)$

Question: Quoting from Wolfram MathWorld, "$P(n,k)$ denotes the number of ways of writing $n$ as a sum of exactly $k$ terms or, equivalently, the number of partitions into parts of which the largest is exactly $k$."
Why are these two definitions equivalent? What is the mapping?
The page also states a recurrence,
$$P(n,k)=P(n-1,k-1)+P(n-k,k)$$
Why is this true?
Answer: For the first see Ferrers diagram in Wikipedia's article on partition function.  For the second, the first term on the right is the number of ways to write $n$ as a sum of $k$ plus terms smaller than $k$, as if you reduce the $k$ term by 1 you have a way to write $n-1$ as terms with largest term $k-1$.  The second term is the number of ways to write $n$ as a sum of terms with at least two terms $k$ and nothing larger.


Why isn't str.trim() removing all the whitespace with certain words?

Question: I'm attempting to take a text file that has assembly-like code inside it and parsing it into an array in java. The text file looks like this:
        begin
        LDA #10     ;load $0A into accumulator
        LDX $15      ;load $15m into X
_loop   TAX         ;transfer A to X
        SEC         ;set carry flag
        end

At the moment the code I have reads the text file line by line and stores each line as a separate string in an array. This works fine, and the code keeps the whitespace in the strings as expected. Next I pass each line from the array to the code below, this then divides each line up using str.split(" ") and then trims each new string before placing it into another array and returning the array.
So just to be clear the process goes like this:

LDA #10     ;load $0A into accumulator one large line
dividedLine[] = ["LDA", "#10", ";load", "etc.."] line is divided up into its elements

The only problem is that with some of the words the whitespace is removed entirely by str.trim() but with some other words the whitespace remains. I think it might be something to do with the tabs I'm using but I'm not sure.
Here's the output I'm getting:
beginLDA#10;load$0AintoaccumulatorLDX$15;load$15mintoX_loop    TAX     ;transferAtoXSEC        ;setcarryflagend
As you can see there is a large amount of whitespace between 'loop' and 'TAX' and between 'SEC' and ';set' which shouldn't be there.
Here's the raw text file I'm using, since I altered it a bit to make it easier to read on stack: https://gist.github.com/anonymous/c802ca31d5402c702ada237bea47f223
Here's my code:
public String[] divideLine(String line)
    {
        String[] lineArray = line.split(" ");
        for(String str : lineArray)
        {
            str = str.trim();
            System.out.print(str);
        }
        return lineArray;
    }

If it is the tabs causing the problem, is there a way I can convert all tabs to spaces before processing each line?
Comment: try split("\\s+"), this will split around any whitespace where as " " only splits it around a single white space.
Comment: I wouldn't use `split()` at all for this. Just write a few lines of code to parse the format. There are only three columns, after all. You don't want to de-space the comments, for example.
Comment: Try `line.trim().split("\\s+")`. That way, you won't need to `trim()` the words in the returned array, since they've already been trimmed. The `trim()` before `split()` is to ensure you don't get an empty words as the first value.
Comment: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
Comment: An easier solution might be using [StringTokenizer](https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html).
Comment: View the file in a hex viewer, perhaps the spaces you see are tabs instead
Answer: If you split on a single whitespace character then the pieces will have tabs some places which accounts for the whitespace you see.
For example, the fifth line of your raw file is
SEC     ;set carry flag, or with the tab character as \t,
\tSEC\t\t;set carry flag
"  SEC     ;set carry flag".split(" ") returns the array
[  SEC     ;set, carry, flag],
or with the tab character as \t, you have
[\tSEC\t\t;set, carry, flag]
As others have mentioned, you can change your code to split on a different regex like "\\s+".
Answer: May be apache's library commons-lang3 will be helpful. There's class StringUtils in that library.
See https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#normalizeSpace-java.lang.String-
normalizeSpace removes starting and ending spaces and replaces each sequence of space-like symbols to 1 space. I think it is what you want.


How to write a T4 template to create DTO's from Entityframework 6?

Question: I have a large database from which I am using a database-first model in Entityframework. This sits on an internet server and communicates through WCF. The domain model uses all lowercase letters for the names of the entities, stored procedures, and columns/properties.
In my client applications, I wish to use the standard PascalCase for the naming convention.
Could a T4 template create the data transfer objects from the Entityframework with the correct naming convention?
If so, could someone please give me a starting point on how to write it?
Just to be clear, I am not wanting to change any of the code that the Entityframework generated, but rather add simple POCO classes with the appropriate CamelCase naming using the Entityframework model as input to another file which can then be referenced by the WCF service and perhaps by Automapper (or something similar).
Thanks for any suggestions.

Database:  PostgreSQL 9.5
Interface to database:  Npgsql 3.0.5
.NET 4.5
Entityframework 6.0
Answer: In lieu of anybody answering this and to hopefully help any other newbie like myself, here is what I did to create a T4 transform, DTOclasses.tt that yields only simple class definitions.
Note: this is NOT replacing the .tt files of the .edmx, but rather is run after the .edmx templates have produced the .edmx file. (I did not want to change any of the code used to produce the domain model).
Visual Studio 2015
Entityframework 6.0
.NET Framework 4.6.1
<code>♦ Notes on Creating DTOclassess.tt

        This T4 transform was created by first copying the working transform used to build the entity model, MedicalOfficeModel.tt.
        Then, parts of it that were not needed for creation of POCO classes to be used for DTO's (data transfer objects) were removed.

    ♦ Changes made to DTOclassses.tt

        •   Adding "DTO" to namespace.
                public void BeginNamespace(CodeGenerationTools code)
                {
                    var codeNamespace = String.Format("{0}.{1}",code.VsNamespaceSuggestion(), "DTO");
                    if (!String.IsNullOrEmpty(codeNamespace))
                    {
                #>
                namespace <#=code.EscapeNamespace(codeNamespace)#>
                {
                <#+
                        PushIndent("    ");
                    }
                }

        •  Put all POCO classes in single file DTOclasses.cs

                <#
                EndNamespace(code);
            }

            fileManager.Process(false);             <--**False stops the splitting of classes into different files. Default is true.

            #>

        •  Change the property naming code:

                    public string Property(EdmProperty edmProperty)
                    {
                        return string.Format(
                            CultureInfo.InvariantCulture,
                            "{0} {1} {2} {{ {3}get; {4}set; }}",
                            Accessibility.ForProperty(edmProperty),
                            _typeMapper.GetTypeName(edmProperty.TypeUsage),
                            GetPascalCase(_code.Escape(edmProperty)),
                            _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
                            _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
                    }

        •  Change the class naming code:

                    public string EntityClassOpening(EntityType entity)
                    {
                        return string.Format(
                            CultureInfo.InvariantCulture,
                            "{0} {1}partial class {2}{3}",
                            Accessibility.ForType(entity),
                            _code.SpaceAfter(_code.AbstractOption(entity)),
                            GetPascalCase(_code.Escape(entity)),
                            _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
                    }

        •  Removed all the navigational stuff. Replaced everything above the helper functions (i.e., above <#+) with:
                            <#@ template debug="false" hostspecific="true" language="C#" #>
                            <#@ assembly name="System.Core" #>
                            <#@ import namespace="System.Linq" #>
                            <#@ import namespace="System.Text" #>
                            <#@ import namespace="System.Collections.Generic" #>
                            <#@ import namespace="System.Text.RegularExpressions" #>
                            <#@ include file="EF6.Utility.CS.ttinclude" #>
                            <#@ output extension=".cs" #>
                            <#

                            const string inputFile = @"MedicalOfficeModel.edmx";
                            var textTransform = DynamicTextTransformation.Create(this);
                            var code = new CodeGenerationTools(this);
                            var ef = new MetadataTools(this);
                            var typeMapper = new TypeMapper(code, ef, textTransform.Errors);
                            var fileManager = EntityFrameworkTemplateFileManager.Create(this);
                            var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile);
                            var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef);

                            if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile))
                            {
                                return string.Empty;
                            }

                            WriteHeader(codeStringGenerator, fileManager);

                            foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
                            {
                                fileManager.StartNewFile(entity.Name + ".cs");
                                BeginNamespace(code);
                            #>
                            <#=codeStringGenerator.UsingDirectives(inHeader: false)#>
                            <#=codeStringGenerator.EntityClassOpening(entity)#>
                            {
                            <#
                                var simpleProperties = typeMapper.GetSimpleProperties(entity);
                                if (simpleProperties.Any())
                                {
                                    foreach (var edmProperty in simpleProperties)
                                    {
                            #>
                                <#=codeStringGenerator.Property(edmProperty)#>
                            <#
                                    }
                                }
                            #>
                            }
                            <#
                                EndNamespace(code);
                            }
                            fileManager.Process(false);

                            #>

        ♦  Added my helper function:
                    <#+

                        public static string GetPascalCase(string name)
                        {
                            return Regex.Replace(name, @"^\w|_\w",
                                (match) => match.Value.Replace("_", "").ToUpper());
                        }
                    #>
</code>
When all is done, this runs perfectly (in VS2015) to do exactly what I needed. :)
Comment: Hi does this create a separate partial class for each DTO? My entities re from Sql Server would there be a difference or any changes here.


How to properly connect my PC's external audio interface to my combo bass amp?

Question: I want to modify my sound with VST before sending it to my amplifier.
My audio interface is the Focusrite Scarlett 2i4 and my amp is the Ampeg BA108.
So it will look like this: Bass -> Audio Interface input -> PC -> Audio Interface output -> Amp
My question is what input on my amp should i use and what cable do i need?
Amp inputs:

Effect Loop RETURN & SEND
CD Input
Instrument Jack input

Audio interface outputs:

RCA
Answer: There appear to be more than one version of the Ampeg BA108 on the market. I'm not sure which one you have.
You want to use a pair of the unbalanced RCA outputs from your Focusrite audio interface, connecting this to the pair of "CD Input" jacks on your Ampeg amp. This will provide the correct impedance and line signal levels for the amp's inputs.

You need a basic RCA stereo pair cable, like this:

Take note of the fact that by doing this, the signal from your bass, processed through your PC and output from the Focusrite, will go into the Ampeg amp's auxiliary input, which will bypass the amp's own "Treble" "Mid" and "Bass" tone controls. The "CD Level" knob will control the volume of the signal coming into the "CD Input" jacks, and the "Volume" control on the left may function as a master volume.
Answer: You have a couple of options here. Consider that by plugging your bass directly into the Focusrite, you're not really using the bass amp for what it was designed for (amplifying an instrument signal), and instead having it do what would be better served by a set of full-range monitor speakers. You'd be effectively using the Focusrite as a DI box and your bass amp as a monitor. The Focusrite is perfectly good at that, but you might want to get some more benefit from your bass amp.
One option would be using the effects send and return jacks on the amp to create an "effects loop" using your Focusrite and VST processors. You'd just need regular TS 1/4 inch patch cables. Your signal chain would go from your bass to the regular input on your amp, then connect the amp's effects send to a line level input on the Focusrite, then from a mono line level output of the Focusrite to the effects return on your amp. (You can always plug a balanced jack into an unbalanced one or use a TS cable instead of TRS -- it just means the whole connection is unbalanced, so don't do it over long distances.)
I'm an amateur at reading circuit diagrams, but I believe that the effects return on your amp will create a bypass of the existing signal, so you get the benefit of the preamp inside your Ampeg, you can do whatever you want to your sound on your PC, and have that come out of the amp speaker. You still get to use all of the controls on the amp, they just affect the signal before it goes into your effects processing.
Comment: Also, based on your question, you have the original version of the BA-108 with the effects send/return on the back panel. And your Focusrite has 1/4" balanced outputs next to the RCA jacks. If those are in use, you can still use one of the RCA outputs to go to the effects return, you'd just need one half of a stereo RCA cable, and a 1/4"-RCA adapter on one end.


Resultado de uma procura MYSQL em linha, não coluna

Question: Bom dia. Possuo uma tabela que lista uma série de motivos cada vez que eles acontecem. Estou usando um select para agrupar esses motivos e ter como resultado os 5 mais recorrentes. Esse é o meu código:
SELECT count(*) as NumeroDeVezes, motivos FROM relatoriomotivos GROUP BY motivos ORDER BY NumeroDeVezes DESC LIMIT 5

O problema é que eu necessitava que a resposta fosse uma linha só para os motivos e uma linha só para o número de vezes, enquanto estou recebendo uma coluna para os motivos e outra para o número de vezes. Existe alguma forma de ajustar isso?
Comment: Você realmente precisa que seja em linhas separadas ? Qual o impacto?
Comment: Infelizmente sim, estou usando essas informações para a programação de um gráfico e ele só aceita a entrada em linha.
Comment: No SQL Server dá para fazer isso usando `PIVOT` como subselect, mas aparentemente o mysql não tem isso, [você precisaria construir algo que seja reutilizável](http://buysql.com/mysql/14-how-to-automate-pivot-tables.html) para não precisar mudar a query toda vez que um motivo novo for incluído.
Answer: Não é uma solução completa, mas já é um ponto de partida.
Se conseguir fazer uma amostra dos dados no SQL Fiddle, e dar mais detalhes na pergunta, posso editar a resposta e elaborar melhor
Se o número de colunas for fixo, pode usar o IF para calcular:
SELECT
   SUM( IF( motivo='A'), 1, 0 ) AS motivo_a,
   SUM( IF( motivo='B'), 1, 0 ) AS motivo_b,
   SUM( IF( motivo='C'), 1, 0 ) AS motivo_c,
   SUM( IF( motivo='D'), 1, 0 ) AS motivo_d,
   SUM( IF( motivo='E'), 1, 0 ) AS motivo_e
FROM
   motivos

Caso alguém precise da solução para outros DBs que não tenham suporte à função IF, dá para fazer o mesmo com CASE.
Veja este post para mais detalhes:

Controle de fluxo com MySQL

Para os títulos, infelizmente também teria que ser manual. O UNIONpermite gerar as duas linhas, uma com título, outra com contagem:
SELECT 'Motivo A', 'Motivo B', 'Motivo C'
UNION
SELECT
   SUM( IF( motivo='A'), 1, 0 ),
   SUM( IF( motivo='B'), 1, 0 ),
   SUM( IF( motivo='C'), 1, 0 )

Outra coisa que pode interessar é o GROUP_CONCAT, que traz vários resultados em uma linha só, mas aí já não seriam colunas separadas. Seria uma coluna com dados separados por vírgula.
Answer: Você pode trabalhar o resultado de sua consulta como string, de forma a possibilitar sua manipulação sem precisar presumir sua existência de forma "hard-coded".
Utilize a função de agregação GROUP_CONCAT para "fundir" em uma linha cada coluna de sua consulta, usando o separador que preferir (aqui estou usando ;):
select
    GROUP_CONCAT(motivo SEPARATOR ';') as motivos,
    GROUP_CONCAT(numero SEPARATOR ';') as numeros
from (
  select count(*) as numero, motivo from motivos
  group by motivo order by numero desc limit 5
) tmp;

 ***
|                                      motivos |   numeros |
|----------------------------------------------|-----------|
| motivo 1;motivo 2;motivo 3;motivo 4;motivo 5 | 3;3;3;3;1 |

Depois, para que cada coluna retorne em uma linha, concatene-as novamente, utilizando com um caractere de quebra de linha \n entre elas. Uso aqui a função CONCAT_WS por permitir definir o separador geral no início, possibilitando a inclusão de mais linhas de forma elegante, sem ter que ficar repetindo o \n:
select
  CONCAT_WS (
    '\n',
    GROUP_CONCAT(motivo SEPARATOR ';'),
    GROUP_CONCAT(numero SEPARATOR ';')
   ) as resultado
from (
  select count(*) as numero, motivo from motivos
  group by motivo order by numero desc limit 5
) tmp;

 ***
|                                              resultado |
|--------------------------------------------------------|
| motivo 1;motivo 2;motivo 3;motivo 4;motivo 5
3;3;3;3;1 |

Perceba que o resultado é apenas uma coluna de um registro, com quebra de linha entre o grupo de motivos e o grupo de números.
Caso você queira dois registros, um para cada grupo, acredito que um UNION resolva o problema, com um pouco de redundância. Seria mais elegante se o MySQL suportasse Common Table Expressions, mas isso só virá na versão 8, portanto segue exemplo com UNION:
select
    GROUP_CONCAT(motivo SEPARATOR ';') as resultado
from (
  select count(*) as numero, motivo from motivos
  group by motivo order by numero desc limit 5
) tmp
UNION
select
    GROUP_CONCAT(numero SEPARATOR ';') as resultado
from (
  select count(*) as numero, motivo from motivos
  group by motivo order by numero desc limit 5
) tmp;

 ***
|                                    resultado |
|----------------------------------------------|
| motivo 1;motivo 2;motivo 3;motivo 4;motivo 5 |
|                                    3;3;3;3;1 |

Segue SQL Fiddle contendo os exemplos acima: http://sqlfiddle.com/#!9/644b0b/26

Dito isso, só para fins complementares, o UNION com uso de CTE ficaria assim:
with consulta as (
  select
      GROUP_CONCAT(motivo SEPARATOR ';') as motivos,
      GROUP_CONCAT(numero SEPARATOR ';') as numeros
  from (
    select count(*) as numero, motivo from motivos
    group by motivo order by numero desc limit 5
  ) tmp
)
select motivos from consulta
union
select numeros from consulta;


Dúvida com JavaScript arrow function

Question: No código abaixo, o método showName() naturalmente retornará undefined, pois irá buscar uma propriedade nome no escopo onde está inserido o obj.
A minha pergunta é, nesse caso eu obrigatoriamente teria que usar uma function convencional, a arrow function não serviria nesse caso?

var obj = {
  nome: 'object',
  showName: () => {
    return this.nome
  }
}

console.log(obj.showName());
Comment: Possível duplicata de [Variável não definida, mesmo estando definida](https://pt.stackoverflow.com/questions/206872/vari%c3%a1vel-n%c3%a3o-definida-mesmo-estando-definida). PS: o this não vai funcionar neste caso, estou analisando o ecma para ver detalhamentos e atualizar a resposta, lhe notificarei.
Comment: Dentro do `console.log` não deveria ser `showName()`?
Comment: Sim, já alterei, obrigado
Comment: quando se usa *arrow function*, dispensa o `return`.
Comment: @GuilhermeNascimento minha dúvida é qual a melhor forma de escrever isso e não a questão do escopo.
Comment: @FelipeCoelho por isso estou lendo na ecma pra ver se tem outra maneira, não to falando de escopo, estou falando do que é possivel até o momento conforme o ecmascript ;)
Comment: @GuilhermeNascimento ok, obrigado
Answer: O melhor nesse caso é usar uma function "normal". Esse é um caso de beco sem saída. O objeto é criado num dado contexto, a arrow function vai usar o contexto no momento da criação e não pode por isso apontar para si próprio.
Dá para criar um cenário parecido, em que isso ia funcionar, mas é pleno exercício, não estou a ver um caso de uso que não dê para fazer de outra maneira:

var obj = (function() {
    this.nome = 'object';
    this.showName = () => {
        return this.nome;
    }
    return this;
}).call({});

console.log(obj.showName()); // object

O mesmo já não se aplica a classes, que seria mais interessante que um objeto simples (pois se tens arrow functions podes benefeciar de classes ES6). Nesse caso a classe cria um contexto próprio e a arrow function seria muito útil:

class Obj {
  constructor() {
    this.nome = 'object',
      this.showName = () => {
        return this.nome;
      }
  }
}
var obj = new Obj();
console.log(obj.showName()); // object

Ou usando notação com class properties (em fase de proposta/estudo para implementar na linguagem).

class Obj {
  nome = 'object';
  showName = () => {
    return this.nome;
  }

}
var obj = new Obj();
console.log(obj.showName()); // object

Dúvida com JavaScript arrow function


Type of predictors for logistic regression

Question: Can predictors in logistic regression be categorical, numerical and ordinal?
If categorical, can they be trichotomous?
Comment: Yes. Long answer to meet the requirement of 15 letters: why not?
Comment: Yes, it can. But You have to make dummy variables for every level (minus 1) of ordinal vars.
Answer: The situation is the same as for ordinary linear regression. Namely, the model allows you to posit a linear relationship between an IV and the (log odds of the) DV, which is appropriate for many numerical predictors, and also suffices for categorical predictors on a nominal scale if you code each predictor into k - 1 dummy variables where k is the number of levels (don't forget to include an intercept term). The ordinal case is more difficult, because inserting an ordinal predictor as a single model term treats the differences between levels as equal, and dummy-coding an ordinal predictor makes the order information unavailable to the model. If you need more sophistication than either of those methods, you'll need a fancier model. Here's an article that discusses the question of what to do with one kind of ordinal predictor, rating scales:
Tutz, G., & Gertheiss, J. (2014). Rating scales as predictors—The old question of scale level and some answers. Psychometrika, 79, 357–376. doi:10.1007/s11336-013-9343-3


Background não aparece [HTML5]

Question: (Resolvido)
Não sei o quê eu fiz, só sei que agora ta funcionando :thinking:
Bom dia/tarde/noite.
Comecei a estudar Html5 essa semana, porém acabei ficando preso na hora de inserir uma imagem de fundo no projeto. Já tentei colocar o diretório inteiro da imagem, entretanto continua não dando certo...
Aqui vai uma parte do código em questão

<!DOCTYPE html>

  <meta charset="UTF-8"/>
  <title>Google glass foi uma bosta</title>

Comment: Não sei se vai resolver, mas vc não precisa colocar aspas no nome da imagem dentro de background-image: url( site-background.jpg ); e confere se a extensão é .jpg ou .jpge vc tb pode tentar colocar uma altura no body, tipo height:100%
Comment: Possível duplicata de [Uso de CSS background-image e background-color](https://pt.stackoverflow.com/questions/250385/uso-de-css-background-image-e-background-color)
Answer: Tenta colocar ela no body. Faz esse teste. Se a imagem aparecer tem algo errado na tag style.

img src="imagens/foto.png" alt="Imagem de página não encontrada"
  width="330" height="202"

Comment: A imagem apareceu Igor. Deve ser algo errado na tag
Comment: Eu não faço a mínima ideia do que eu fiz, mas agora ta funcionando...
Comment: Se está funcionando e você não fez nada por ser cache, cuidado. Limpe o cache e veja se ainda funciona.
Comment: Limpar o cache do navegador?

Background não aparece [HTML5]


regex para validação de url

Question: Pessoal fiz esta regex para validar URL:
const std::regex pattern(
   "(?:(ftp|http[s]?:[//])?)?([w]{3}[.])?"
   "(.*[.](com|php|net|org|br|dk|at|us|tv|info|uk|co.uk|biz|se)?)?"
   "(.*[.](aspx|htm|html|HTM|HTML|jhtm|jhtml|JHTM|JHTML|xhtm|xhtml|XHTM|XHTML)?)?"
);

Até então está validando, mas ao meu ver isso também é uma URL:
pt.stackforum.stack/questions/ask

ou até mesmo:
pt.stackforum.stack/questions/

Tentei incluir este tipo de validação na minha regex mas não consegui.
Este é o programa completo.
#include <regex>
#include <iostream>

#define this (*this)

struct url
{
 url(std::string url): _url(url){}

 ~url()
  {
   if(_url.length() != 0)_url.clear();
  }

  bool isUrl()
  {
    std::smatch url_smatch;
    const std::regex pattern(
                             "(?:(ftp|http[s]?:[//])?)?([w]{3}[.])?"
                             "(.*[.](com|php|net|org|br|dk|at|us|tv|info|uk|co.uk|biz|se)?)?"
                             "(.*[.](aspx|htm|html|HTM|HTML|jhtm|jhtml|JHTM|JHTML|xhtm|xhtml|XHTM|XHTML)?)?"
                            );
    return std::regex_match(this._url, url_smatch, pattern);
  }

 url* print()
 {
  std::cout<<"\n\tUrl: "<<this._url<<(url(this._url).isUrl()?"\n":" is Invalid\n");
 }

  private:
  std::string _url;
};

int main()
{
  const std::string urls[11] = {"http://docs.microsoft.com/pt-br/sql/reporting-services/tools/url-examples-for-items-on-a-report-server-sharepoint-mode/",
                                "https://www.uolhost.uol.com.br/faq/v2/loja-virtual/o-que-e-um-endereco-de-url.php",
                                "https://www.uolhost.uol.com.br/index.asp",
                                "www.uolhost.uol.com.br/INDEX.htm",
                                "ftp://ftp.uolhost.uol.com.br/index.html",
                                "ftps://uolhost.uol.com.br/downloads/source",
                                "ftp.uolhost.uol.com.br/downloads/source/",
                                "ftp.uolhost.uol.com.br/downloads/source/index.jhtml",
                                "ftp.uolhost.uol.com.br/downloads/source/index.xhtml",
                                "ftp.uolhost.uol.com.br/downloads/source/index.aspx",
                                "ftp.uolhost.uol.com.br/downloads/source/index.XHTML"};

    for(int i=0; i<11; i++)
    url(urls[i]).print();
}

Answer: Tenta essa abaixo, fiz e testei no Testador de Regex fiz para aceitar url local e ip
^[a-zA-Z0-9-_]+[:./\\]+([a-zA-Z0-9 -_./:=&"'?%+@#$!])+$

Testei todos os valores abaixo e deu certo
http://server/dev/Formularios/Cadastro_Usuario/Professor/Atualizar/Usuario.php?usuario_id=1245&nome=Ricardo%20Teixeira%Souza&cidade=Itabuna
https://www.google.com.br/search?q=%2520%25+space&oq=%2520%25+space&aqs=chrome..69i57j0l5.9863j0j7&sourceid=chrome&ie=UTF-8
localhost:8080
localhost/user/test.com/index.php
C:\Windows
google.com
ftp://teste.com
192.168.0.1
teste_server.com
teste-server.com

Comment: nao funcionou ela da invalida na std::regex tentei consertar e deu na mesma...
Answer: Da uma olhada nessa alteração aqui:
    const std::regex pattern(
        "(?:(ftp|http[s]?:[//])?)?([w]{3}[.])?"
        "(.*[.](com|php|net|org|br|dk|at|us|tv|info|uk|co.uk|biz|se)?)?"
        "(.*[.](aspx|htm|html|HTM|HTML|jhtm|jhtml|JHTM|JHTML|xhtm|xhtml|XHTM|XHTML)?)?"
        "(\\w+(\\.(\\w|-)+)*(/(\\w|-)+)*/?)?"
    );

Pra aceitar letras/numeros e o caracter -, caso queira aceitar outros caracteres, adiciona eles separados por | nos termos que tão precedidos pelo +.

regex para validação de url


how to print part of regex match in sed when parsing source code?

Question: I would like to print part between regex match like this:
echo "this is foo and another foo quux" | sed 's/this\(.*\)another.*/\1/'

which prints
 is foo and

what is perfectly ok as I want to get part between this and another printed.
But, If I want to parse my source code and use:
cat source_code | sed 's/.*AdulterateFood\(.*\)DangerousFood.*/\1/'

and I do know that AdulterateFood and DangerousFood is only once in the source code, it still prints everything, whole file:( I am wondering why.. AdulterateFood and DangerousFood are on different lines.
Thank you for your suggestions.
Answer: sed prints each input line by default. If you don't want that behavior you need to add the -n option. If you then want it to print the lines that match your RE you have to add a "p" to the end of the substitution command to tell sed TO print that line. So this:
sed -n 's/.*AdulterateFood\(.*\)DangerousFood.*/\1/p' source_code

seems to be what you're asking for but since you didn't provide any sample input and expected output it's just a guess.
Answer: To print all lines between AdulterateFood and Dangerous food:
sed -n '/AdulterateFood/,/DangerousFood/p' file


I am facing some issues in importing CSS modules and using it in classname

Question: //here is the import of css module
import * as styles from './global-offices.module.css';
and when I am using it inside my div for example className={styles.iAmClass}
so it is giving me warning that iAmClass is not exported from './global-offices.module.css'
here is the css file:
.wrapper {
    height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
    padding: 20px 0px;
    background: #fff;
    margin: var(--mobile-component-buffer);

    @media (min-width: 834px) {
        margin: var(--desktop-component-buffer);
        padding: 20px 20px;

        &#galleryWrapper {
            padding: 20px 40px;
        }
    }
    .gallery {
        overflow: hidden;
        padding: 0;
        margin: 0 auto;

        .officeCard {
            min-width: 235px;
            width: 280px;
            height: auto;
            display: inline-block;
            margin: 0 10px;
            overflow: visible;
            text-align: center;
            vertical-align: top;
            background: var(--color-gray);
            padding: 0 0 1rem;

            &:first-of-type {
                margin: 0 10px 0 10px;
            }

            @media (min-width: 414px) {
                width: 280px;
                min-height: 515px;

                &:first-of-type {
                    margin: 0 10px;
                }
            }
        }
        h5 {
            margin: 1rem 0;
        }
        p {
            margin: 0.5rem 0;

            &.siteUrl {
                color: var(--color-orange);
            }
        }
    }
    .prevArrowButton {
        position: absolute;
        top: 35%;
        left: -12px;

        @media (min-width: 834px) {
            left: 2px;
        }

        @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
            width: 90px;
        }
    }
    .nextArrowButton {
        position: absolute;
        top: 35%;
        right: -12px;

        @media (min-width: 834px) {
            right: 2px;
        }

        @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
            width: 90px;
        }
    }
    svg {
        height: 2.5rem;
    }
    .dots {
        width: 100%;
        text-align: center;
        margin-top: 15px;
        span {
            border: 1px solid #ccc;
            border-radius: 50%;
            font-size: 0;
            padding: 6px;
            margin: 0 2px;
        }
    }
}

.countrySelector {
    text-align: center;
    width: 250px;
    margin: 20px auto;
    select {
        appearance: menulist;
        margin-top: -1px;
        border: 2px solid var(--color-gray);
    }

    @media (min-width: 834px) {
        width: 650px;
    }
}

.mapContainer {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 100%;

    @media screen and (min-width: 834px) {
        max-width: 90%;
        padding-bottom: 56.25%;
        margin: 0 auto;
    }
}

.mapFrame {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

I am attaching screenshot of one of uses for reference

These are the warnings I am getting when I am running it locally

I am also attaching typescript code for css module exports that I am using:
declare module '*.css' {
    const content: { [className: string]: string };
    export default content;
}

Comment: Can you add relevant css file?.
Comment: @dhaker I have added relevent css file
Comment: Nesting of classes is not allowed in css, that's why it is not working for you. Move all css classes to 1st level.
Comment: @dhaker this nested css structure was working fine earlier it's just i think the problem is in the way of typescript exporting i guess
Answer: I had similar problem in my CRA, however I was using CSS modules (not scss/sass), also my application was using default CSS loader from CRA (which comes out of the box). Problem was solved by:

Creating file Globals.d.ts in ./src.
Adding these lines in created file
declare module '*.module.css' { const Styles: { [className: string]: string }; export default Styles; }
Adding /**/*.d.ts inside eslintignore since eslint was treating created file as js one.
Installing npm install typescript-plugin-css-modules --save-dev
Creating a directory named .vscode at the root of the project (if it doesn't already exist), and adding a new file called settings.json with the following lines: { "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }

After listed above I could import my styles within tsx files like this import Styles from './index.module.css';
I hope this helps


Sequence closed expression or others

Question: What are closed expression or any other expression (involving integrals, specials functions...) for
$\sum_{k=0}^{n}(n-2k)^t\frac{n!}{k!(n-k)!}$
where $t>0$ integer
Thank you
Comment: If $t$ is an odd integer the sum is null.
Answer: Define $$f\left(x\right)=\left(2\cosh\left(x\right)\right)^{n}=\left(e^{x}+e^{-x}\right)^{n}.$$
 By binomial theorem$$f\left(x\right)=\sum_{k=0}^{n}\dbinom{n}{k}e^{\left(n-k\right)x}e^{-kx}=\sum_{k=0}^{n}\dbinom{n}{k}e^{\left(n-2k\right)x}$$
 hence$$\frac{d^{t}f}{dx^{t}}\left(x\right)=\sum_{k=0}^{n}\dbinom{n}{k}\left(n-2k\right)^{t}e^{\left(n-2k\right)x}$$
 then$$\sum_{k=0}^{n}\dbinom{n}{k}\left(n-2k\right)^{t}=\frac{d^{t}f}{dx^{t}}\left(0\right).$$

Sequence closed expression or others


Track time stamp to check Option Group Checkbox (YES or NO)in Access

Question: I would like to track timestamp to store in one field when the user check as 'Yes' from Option group checkbox and same for another field as 'No'. Please help me with this.
Basically I want to track Yes checkbox timestamp and No checkbox timestamp in access form.
Answer: It seems a little weird to have separate text boxes for yes and no, but I created another field for "TestTimeStamp" and then just update that value when the check box is updated.
<code>Private Sub TestCheck_AfterUpdate()
    Forms!TestForm.TestTimestamp.Value = Now()
End Sub
</code>


How much are retained players supposed to be paid in the IPL?

Question: After the IPL auction, we know the amount that teams bought the players for and they will be paid according to that.
But I couldn't find the amount that retained players are to be paid.
It's not available in this list.
Who determines the amount retained players will be paid in the IPL? Is it negotiable?
Answer: For retained players the salary cap will be charged as follows.

For Capped Players

Rs. 12.5 crores for the first capped Player so retained
Rs. 9.5 crores for the second capped Player so retained
Rs. 7.5 crores for the third capped Player so retained
Rs. 5.5 crores for the fourth capped Player so retained
Rs. 4 crores for the fifth capped Player so retained

For Uncapped Players

Rs. 4 crores for each uncapped Player so retained

Source.
Comment: The above amounts are non-negotiable. Stipulated by IPL Committee


Random effect on scale parameter

Question: I am trying to use random effects on both the location and scale parameters in a lognormal regression.  As you can see in the JAGS code below, I am essentially fitting a accelerated failure time model with interval censored log-normal failure times.  I am having problems coming up with decent non-informative priors for the random effects of the scale parameter (for which I use disp in the code).  The way I have it set up now is really sensitive to priors specification. Anyone have any suggestions on how to proceed?
With no random effect on the scale parameter and using a $U(0,big)$ on the inverse of the srqt of the scale, the model seems to converge just fine with estimates that make sense.
Eventually I want to add fixed effects to this regression but am simply trying to fit this simpler model at the moment.
<code>model{
      for (i in 1:study){
          for (j in offset[i] : (offset[i+1] - 1) ){
              y[j] ~ dinterval(t[j], lim.s[j,1:2])
              t[j] ~ dlnorm(mu[i],disp[i])
           }
       }
     for (j in 1:study){
       beta1[j] ~ dnorm(0,taup)
       mu[j] <- beta0 + beta1[j]
       alpha1[j] ~ dnorm(0,taup.d)
       inv.disp[j] ~ dlnorm(log.inv.disp.hat[j],disp.inv.disp)
       log.inv.disp.hat[j] <- alpha0 + alpha1[j]
       disp[i] <- 1/inv.disp[j]^2
     }

    ## random effects
    alpha0 ~ dnorm(0,0.001)
    beta0 ~ dnorm(0,0.001)

    ## hyperprior on  sqrt(inverse dispersion) for prior on dispersion
    inv.disp.inv.disp ~ dunif(0.01,100)
    disp.inv.disp <- 1/inv.disp.inv.disp^2

    ## hyper prior for beta1
    sigmap ~ dunif(0.01,100)
    taup <- 1/(sigmap*sigmap)

    ## hyper prior for alpha1
    sigmap.d ~ dunif(0.01,100)
    taup.d <- 1/(sigmap.d*sigmap.d)
}
</code>
Answer: I have had some luck ($N=1$) with the following: Prior distributions for variance parameters in hierarchical models.  In the paper, the variances are not themselves hierarchical, but it might provide an alternative starting point.  There's also some good information about speeding up MCMC convergence using redundant parameterizations, which may prove useful.
Comment: Thanks. The parameterization I am using is also from Gelman.  I'll give this paper a re-read to see if I get any ideas.

Random effect on scale parameter


Http to https behavior for visits from Internet Explorer client

Question: My website has an SSL cert (example url: https://subdomain.example.com).  Under Apache it's set up for both port 80 and port 443.  So under the following configuration, anyone who goes to http://subdomain.example.com is sent to https://subdomain.example.com .  But for visits from Internet Explorer, the redirect doesn't happen.  Instead, http visits get a "Internet Explorer cannot display the web page." with a list of client-side solutions to try.
Any ideas on how to fix the config so IE visits have the same behavior as the other browsers (that is, send http to https automatically)?
NameVirtualHost *:443

<VirtualHost *:80>
  DocumentRoot /var/www/somewebroot
  ServerName subdomain.example.com
</VirtualHost>

<VirtualHost *:443>
     DocumentRoot /var/www/somewebroot
     ServerName subdomain.example.com
    #   SSL CERTS HERE
</VirtualHost>

*Tested IE8, IE9 beta
Answer: Placing this code in the HTTP  virtual host's definition should do it.
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^/(.*) https://subdomain.example.com [R=301,L]
If you are testing changes you may have problems with IE unless you shut down all IE windows and restart.  IE can be use its cache aggressively.
EDIT: You need to ensure mod_rewrite is enabled. Command is a2enmod rewrite. It will tell you if the module is already enabled.  If not you will need to shutdown and restart the server after enabling the module.
Add the lines above to your virtual host definition and use apache2ctl graceful to reload the modified configuration.  The Apache documentation has details on rewriting.
You should see the redirect as a 301 status request in your access log followed by a 200 or 304 status on the HTTPS connection.  The displayed URL should change to the new location.
Logging the port in an extend log format helps to see which connection things are happening on.  Alternatively, use separate logs for each virtual server.


problem building GD on Ubuntu 'Jaunty'

Question: I'm having trouble building gdlib. As far as I can tell, zlib, png and all the rest are installed in either /lib or /usr/lib. It does not seem to matter whether I use --prefix or one or all of the --with-, the configure script keeps on insisting that it can't find any of the supporting libraries.
** Configuration summary for gd 2.0.34:

   Support for PNG library:          no
   Support for JPEG library:         no
   Support for Freetype 2.x library: no
   Support for Fontconfig library:   no
   Support for Xpm library:          no
   Support for pthreads:             yes

[EDIT]
Now I've noticed that libpthread was found. Hunting around the disk I find libpthread.so. What I don't find is libpng.so. What I do find is /usr/lib/libpng12.so.0. So what's this zero on the end? Is this why Gd's configure isn't working? What do I do about this?
This is all because Concrete5's installer is telling me it can't find GD.
Comment: It also helped to install the -dev versions of the various libraries.
Answer: # cd /usr/lib
# ln -s libpng.so libpng12.so.0
# ldconfig

This creates a softlink to libpng12.so.0 using the filename that compilation expects, then runs ldconfig (must be run as root!) to rebuild the library cache.
If you want to check if your system knows about libraries or not, use the following command:
# ldconfig -p |grep <library_name>

Comment: Isn't it 'ln -s thing linktothing'? Anyway, I figured it out and it works at treat. Thanks!
Answer: try running ldconfig to refresh the list of libraries

problem building GD on Ubuntu 'Jaunty'


Laravel MAMP Vhosts issue

Question: Have the below config in vhosts.  Its always returns 500 error when i run it through MAMP.   Not sure what is wrong.  Stopped mamp  and ran it using valet.  laravel website runs successfully.  Permissions of bootstrap/cache and storage looks good.  Error logs are empty cant debug and debug setting set to true in .env file.  Only access log exists with 500 error.  Below is the vhosts config that i have for MAMP.  Other website in vhosts file work.
<code><VirtualHost *:80>
 ServerName elearn.localhost
 ServerAlias elearn.localhost
 DocumentRoot "/Users/user1/code/elearn/public"
 ErrorLog "/Users/user1/logs/elearn.localhost-error_log"
 CustomLog "/Users/user1/logs/elearn.localhost-access_log" common
  <Directory "/Users/user1/code/elearn/public">
            DirectoryIndex index.php
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
   Order allow,deny
   Allow from all
   Require all granted
   Satisfy Any
 </Directory>
</VirtualHost>
</code>
Comment: can anyone help me?
Comment: can anyone help regarding this issue
Comment: Somewhere you should be able to access some error log with some details, since this is missing I am assuming the simple mistakes. Do you have a .htaccess file in your root folder to enable pretty URL's?
Comment: did you check laravel.log file ? If it is 500 error then it must log the error in storage/logs/laravel.log file
Answer: What version of Laravel are you using, if it is 5.6 make sure you're running PHP at at least 7.1 in MAMP - fallen foul of that myself a couple of times?
Comment: Thanks for the info.  Your correct.  MAMP that i was using  was using PHP 7.0   Upgraded MAMP it works now
Answer: Alrighty, checklist:

is MAMP running under your user?
make sure it's not permissions issues: commit, chmod 777 on project root, try again, if you still get 500 then it's ruled out
stop valet, restart mamp, just to be sure no services parts are conflicting
remove the vendor folder and composer install again, better be safe then sorry
lastly, add a dd() to any route and test it, if you see the dd, means it's not related to mamp, valet or laravel, probably config, driver or other issues.

Laravel MAMP Vhosts issue


How is the net run rate calculated if the match stopped due to rain?

Question: Here we already discussed how the net run rate is calculated.
If the match gets stopped due to rain, then how is the NRR calculated?
Consider both of these situations:

Match stopped due to rain, but the result decided by DL method
Match stopped without result after bowled a few overs in second innings
Answer: Note that net run rate is not part of the Laws, being only applicable to games played within a tournament, and so the precise method of calculation will depend on how the tournament specifies it (although I believe it remains virtually identical across tournaments, with possibly no changes at all). In the ICC Champions Trophy 2013, this is how net run rate will be calculated in a D/L adjusted match:

Only those matches where results are achieved will count for the purpose of net run rate calculations. Where a match is abandoned, but a result is achieved under Duckworth/Lewis, for net run rate purposes Team 1 will be accredited with Team 2's Par Score on abandonment off the same number of overs faced by Team 2. Where a match is concluded but with Duckworth/Lewis having been applied at an earlier point in the match, Team 1 will be accredited with 1 run less than the final Target Score for Team 2 off the total number of overs allocated to Team 2 to reach the target.
Answer: In matches where Duckworth-Lewis revised targets are set due to interruptions which reduce the number of overs bowled, those revised targets and revised overs are used to calculate the net run rate for both teams.
    For example, in a 50-over World Cup first-round group match, Team A are dismissed for 165 in 33.5 overs.
    Team B progresses to 150-2, but play is halted after 26 overs due to rain. And the match never starts. The DL par score for team B is calculated as 149.
    Because the target was revised, and Team A were bowled out, Team A's total is reset to 149 from 44 overs, thus their RR = 149/44 ,approx 3.39. Team B's RR, however, is computed as normal:150/26.33 ,approx 5.70.
    Computing the match NRR for Team A gives us 3.39 - 5.70 = -2.31. Team B's NRR is: 5.70 - 3.39 = 2.31.
Answer: During a D/L affected-result, the reduced target and overs are considered for NRR.
For instance, take up India vs Pakistan match in 2019 World Cup.
The scorecard reads:
India = 336/5 in 50 Overs
Pakistan = 222/6 (40)
India won by 89 Runs here according to D/l method.
Now the calculation will be,
D/L Target for Pakistan - 301 in 40 Overs,
So you should consider India's total as 300 in 40 Overs
Thereby, India Run Rate = 300/40 = 7.5
Pakistan Run Rate = 222/40 = 5.55
So, it is +1.95 for India and -1.95 for Pakistan
The NRR calculations for every scenario in Cricket is brilliantly depicted in this blog.


What's the limit of drupal?

Question: I want to know what's the limit of drupal?:

Maximum number of nodes .
Maximum number of content type .
Maximum of files 's size .

And That without interruption of service .
I am using Apache + mysql +redhat  .
Thank you very much
Comment: 1. Defined by your MySQL instance (depends on [max integer](http://drupal.stackexchange.com/questions/32675/what-if-nid-reaches-the-maximum)). 2. Ditto. 3. Defined by your apache/php settings. Whether or not your site is _happy and responsive_ with extreme numbers of nodes is down to your server infrastructure and very little else. Basically as @Bart said, there's no real answer to this question
Comment: I had a same question with some great info check it http://drupal.stackexchange.com/questions/32675/what-if-nid-reaches-the-maximum
Answer: That depends on a lot of factors: hardware, configuration of your LAMP stack, ...
The only real way to test this is to benchmark it yourself, on your hardware, under your circumstances.
There's no real answer to this question.
Comment: As I said, even if you'd give every detail of your setup, we'd still be guessing. The only real way to test this is to benchmark it. To be honest, I wouldn't worry to much about the limits of Drupal. If you get close to reaching the limits of Drupal, there will be ways to work around that. For example you could use MongoDB instead of MySQL for storing fields, logs, ...
Comment: I have a mysql server 5.1 and php5.4 and redhat server with 4Go of ram and apache2
Answer: I've worked with sites that:
 - have millions of nodes.
 - hundreds of thousands of files.
 - sites that deal with video (gb sized files).
In the above cases it's something that drupal is built on top of and not drupal it's self that can be an issue. Million of nodes; use a database that can handle a lot of I/O (read this blog). Hundreds of thousands of files; setup your directory structure so you have less than 5,000 files in a dir. Large file sizes; there are workarounds, this is a PHP limit not a drupal one.
Answer: There are limits set both within Drupal's configuration and by the limitations of your server. For example, the PHP memory limit is set by the admin, and determines how much system memory Drupal can use up. The hard drive space of your system determines how many gigs of code, database contents, and files can be stored. There are many such limitations, some of them available for change as settings, and some inherent in the limitations of your hardware and software setup itself.
Because the performance-determining variables and their potential combinations are so numerous, it's more practical to do some in-situ benchmark testing with your particular site on your particular stack on your particular hardware using your particular internet connection than it is to try to predict the performance from some kind of calculation of every possible variable.
Even then, your metrics may be very different in a dev environment with just a few users making requests than they would be in production use, where traffic to your site could be dramatically more voluminous.
Comment: Thank you very much,I asked that question because i'm conception a new system when it's possible to make 2000 nodes per hour, so im wondering if drupal will do it or i have to develop my own system
Comment: It depends on what the nodes contain and how they're generated, as well as your storage space and your PHP memory limit. There's no way to answer your question without testing your machine.
Comment: 2000 nodes per hour is not that large ;)
Comment: @AyeshK Can you please explain a bit more?
Comment: sorry i was saying, adding 2000 nodes per hour will not make the site perform worse in most normal sites -- not related to practical php and mysql. I have had a site that crawls ~12000 nodes per hour and still it works for normal users.

What's the limit of drupal?


How to replace commas with white spaces in a csv, but inserting a different number of space after each column?

Question: I have a file in the following format:
s1,23,789
s2,25,689

and I would like to transform it into a file in the following format:
s1      23  789
s2      25  689

i.e 6 white spaces between the 1st and 2nd column and only 3 white spaces between the 2nd and 3rd column?
Is there a quick way of pulling this off using sed or awk?
Comment: See also the unix command `column -t ` if you just want to throw all even column formatting over to an existing command after you replace the commas.
Answer: you can try with sed
sed -r 's/(\S+),(\S+),(\S+)/\1      \2   \3/g' file

or awk using Modifiers for printf Formats
awk -vFS="," '{printf "%2s%8s%5s\n",$1,$2,$3}' file

you get,
s1      23   789
s2      25   689

Answer: using awk it's as simple as
awk -F, '{ print $1,"      ",$2,"   ",$3 }'

Answer: just for future seekers, I used the answer from Naumann and modified it to for my own use. My purpose is to remove commas between two columns and put a white space there.
The following worked for me:
awk -F, '{ print $1,$2 }' n64215_my_file_name.txt > log_new_file_name.txt


Is there a more compact way of notating two-note duplet division tremolos?

Question: Is there a really compact way of notating the following bar? I'm already using slash notehead on beats 2 and 3 to indicate "repeat the previous beat". But is there some way of writing just a pair of notes for the first beat and maybe somehow using tremolo notation to indicate the sextuplet? Or some other notation?
Comment: Many thanks in advance to Laurence Payne for his tip about the slash noteheads.
Answer: I was considering the proposed below, but can't say I've seen it in notation, but it might exist.
Comment: I actually might have seen the proposed notation or a triplet equivalent in a Schubert work.
Comment: Your "proposed" notation looks the best to me, but I think I'd still have to explain it, as it's not notation you come across every day.
Comment: I would say definitely explain it! I've not seen it. But I think the train of thought makes sense in the above diagram.
Answer: If there's a few of them in succession, this might be acceptable.   But don't obsess on compacting to the extent of holding up reading with a 'wtf?' moment.


Single sign on between different Drupal versions

Question: Is it possible to have this module working with different Drupal versions?
We have some big projects in Drupal 6 and we want to start with a migration plan. Without being able to migrate parts of our sites, the task is much more complex than being able to do small migrations and tests.
I have seen there is the Bakery Single Sign-On System, but I don't know if it can be used when the subdomains use different Drupal versions.
Comment: Do you mean this module http://drupal.org/project/sso ?
Comment: this module has no version for D7, hasn't it? I have also seen the bakery Single Sign-On System (http://drupal.org/node/1942854) but i don't know if what i need is achievable between different Drupal versions
Comment: Oh sorry, i meant the bakery project, yes
Answer: With the drupal-6 site override hook_login_validate() and write your own authentication mechanism. Simpler than it sounds, as any function that returns TRUE or FALSE based on success will work. It could directly access the database or connect via a JSON web service to the drupal-7 server. I described how to implement authentication via JSON on stackoverflow.
<code>function mymodule_login_validate($form, &$form_state) {
   $username = $form_state['values']['name'];

   // do if condition to see if your authentication is required.
   // e.g. you might want to keep the drupal administration users.
   if (_mymodule_use_webservice_login($username)) {
     // We are logging in using service.
     if (_mymodule_validate_password($username, $form_state['values']['pass']) {
       user_external_login_register($username, 'mymodule');
       user_authenticate_finalize($form_state['values'];
    } // else drop through to the end and return nothing - Drupal will handle the rejection for us
   }
} else {
    // Username is not an member number, so use standard Drupal authentication function
    user_login_authenticate_validate($form, &$form_state);
}
</code>
_mymodule_validate_password() is where the authentication occurs and the only other function you need to implement. See the stackoverflow site for calling a JSON web service. Try to use SSL as passing passwords over SSL is not great, although your main site may not be SSL anyway.
Implementing the web service is a function return TRUE or FALSE - drupal_json_output. You need to set up a menu, with a function callback. The function callback would call user_authenticate().
You could also try one of the SSO modules. http://groups.drupal.org/node/182004. It is usually good policy to not implement your own security code so that the code gets tried as much as possible.
Comment: i will take a look during the weekend, thank you for your effort in this elaborated answer Interlated :-)


Shared client & server modules with angularjs and pongular

Question: Looking for advice from javascript experts -- is there a better (terser? safer?) way to do this?
I'm writing modules that work with the DI syntax for both angularjs (client-side) and pongular (server-side).
di = (typeof window!='undefined') && window.angular || require('pongular').pongular
di.module 'thecrewApp'

.factory 'fbRoot', ['fbUrl', 'Firebase', (fbUrl, Firebase)-> new Firebase(fbUrl)]

My client-side angular app can use this injectable, as can my server-side node app.  I do this for a bunch of injectables that are used on both client and server.
Is there a better way to express this?  The first line, where I pick which DI engine to use based on typeof window... feels hacky.
Comment: Perhaps adding function require() { return angular; } to your browser-side code...?
Comment: Also, look into using ES6, with babel or traceur for the front-end.
Comment: defining require is a great tip, suggest it as an answer, awesome, thanks!
Answer: I can think of some possible solutions:

Include in the shared files only the array of dependencies and the function call (e.g. module('moduleName').factory(["$http", function($http) { ... }]);), and use a preprocessor to wrap the file with angular. or pongular.
Define angular or pongular globally in one environment. Or, define a function globally that returns the proper reference, e.g.
// in the browser
function require() { return angular; }

Then your require code will work across environments.

Look into using ES6 modules.


Twitter Bootstrap - Row Div and Span Divs 1px Size

Question: I am currently creating a Landing page in Twitter Bootstrap and have run into a problem.  The row and that spans contained within that row are you being filled by the content.  They are each coming across as 1px in height.
http://www.landing.xeonweb.com.au - Is the URL
Below is the code:

<link href="css/bootstrap.css" rel="stylesheet" media="all">
<link href="css/bootstrap-responsive.css" rel="stylesheet" media="all">

                    <button class="btn btn-large btn-block btn-success" type="button">Contact Us</button>

  ‹
  ›

<!-end Head wrap-->

The header is not responsive eiether which I am thinking is because of this?  Any help would be appreciated.
Answer: Try

instead of

Answer: Well you have messed up the whole bootstrap code , the best practice is to write custom styling in a different css file than to include them into the bootstrap main css .
Try this --
Plz use the default styling -

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrapcombined.min.css" rel="stylesheet">

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

View details »


Como fazer um ComboBox com GridView?

Question: Estou tentando fazer um ComboBox que ai clicar seja preenchido com uma GridView, sei que é do DevExpress, hoje utilizo a versão 16.1.
exemplo:
Comment: Não entendi muito bem, poderia ser mais especifico?
Comment: Como você pretende adicionar valores da GridView no combo box? Quais são os campos? Como esta a sua rotina responsável?
Answer: Chama-se GridLookUpEdit.

Pode-se encapsular um gridview em um combobox.

Como fazer um ComboBox com GridView?


Unable to deserialize JSON into List in C# 4.0

Question: I am trying to deserialize JSON into List. I have .NET 4.0. Normal deserialization into an object works fine. I am an absolute beginner in C#.
I wrote the following code with the help from various forums. When I am trying to load the deserialized JSON into a List for Lad type, it doesn't give any error but when I check Lads object it's just blank.
using System;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace RESTServicesJSONParserExample
{
    public class MyDate
    {
        public int year { get; set; }
        public int month { get; set; }
        public int day { get; set; }
    }

    public class Lad
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public MyDate dateOfBirth { get; set; }
    }

    class Program
    {
        static void Main()
        {
            var obj = new Lad
            {
                firstName = "Markoff",
                lastName = "Chaney",
                dateOfBirth = new MyDate
                {
                    year = 1901,
                    month = 4,
                    day = 30
                }

            };
            var json = new JavaScriptSerializer().Serialize(obj);
            Console.WriteLine(json);

            //This fails to load desereialized JSON in the List
            List<Lad> Lads = new JavaScriptSerializer().Deserialize<List<Lad>>(json);
            Lad Lad1 = new JavaScriptSerializer().Deserialize<Lad>(json);

            Console.WriteLine(Lad1.firstName);

            //Nothing returned here
            foreach (Lad Lad2 in Lads)
            {
                Console.WriteLine(Lad2.firstName);
            }

            Console.ReadLine();
        }
    }
}

Answer: You are serializing a single Lad. You can't deserialize it as a collection of Lads!
You could change the code in:
var obj = new List<Lad>
{
    new Lad
    {
        firstName = "Markoff",
        lastName = "Chaney",
        dateOfBirth = new MyDate
        {
            year = 1901,
            month = 4,
            day = 30
        }
    }
};

Now Lads will have one Lad, while Lad1 will crash (because you can't deserialize a collection as a single element).
Just as a curiosity, your "original" json was
{"firstName":"Markoff","lastName":"Chaney","dateOfBirth":{"year":1901,"month":4,"day":30}}

Introducing the new List<> it becomes:
[{"firstName":"Markoff","lastName":"Chaney","dateOfBirth":{"year":1901,"month":4,"day":30}}]

Se the initial and final []? Now there is an array of objects in the json object!
Comment: Worked! and thanks for the super quick response and explanation.
Answer: I actually just had to do this yesterday and this is how I did it (not sure if there's an easier way, but it worked for me). I deserialized each object and added that object to my List. I had a list of json objects (generic objects) so I looped through them with a foreach, adding them to the List. Also, I use JsonConvert.DeserializeObject, but I believe it should work the same way.Try this though:
List<Lad> Lads = new List<Lad>();

Lads.Add(new JavaScriptSerializer().Deserialize<Lad>(json));


Learning path for soloing and improvisation

Question: I'm still not sure what it's called , I thought it may be these two I mentioned in the title.
What I want to learn is being able to follow with the lead guitar and do the licks just like in an indie band, the lead is playing some chords and the other guitar is doing some follow up solos or improvisation .
I hope I can find my answer and know what are the prerequisites to be able to learn all of that and be able to reach that level.
Comment: http://music.stackexchange.com/questions/16307/guitar-solo-techniques?rq=1
Answer: There are already plenty of similar questions here with great answers. Things like - know some scales, in the keys you play in, be able to change what you play according to the chords played, LISTENING TO THE OTHERS!, etc. Look on the right of screen for lots of good tips.


Asymmetric ease of improvisation during modulation

Question: I've been learning about modes, and one thing I was interested in at first was to change modes while improvising (to get to know them better technically as well as to have a better understanding of what their flavour is). For instance, I improvised in minor pentatonic, and used its ambiguity with the relative minor modes to try to explore their differences. This lead me to question how to properly change modes in a convincing way, and even how to properly change key.
I don't know anything about the theory of modulation, but I wanted to try and experiment to figure out how it could be done.

I first picked two keys at random : E aeolian and G# aeolian.
I basically did what I think is a common-chord modulation. My idea was to pick the common notes between the two keys, and use them to transition from one key to the other. Here, the common notes are B E F#, which are a Bsus4 triad, so I used that chord to transition between the two keys. Going to E aeolian I let Bsus4 resolve to Bm, and going to G# aeolian I let Bsus4 resolve to B.
I used this very simple progression (on a loop) and improvised in E minor pentatonic/E aeolian, going to G# minor pentatonic/G# aeolian and back, to keep it as simple as I could.
Em Am | Em Am | Bsus4 B | G#m C#m | G#m C#m | Bsus4 Bm
My observation is that I managed to change key in a way that sounded pretty good (at least to me) when the change was from E to G#, but not the other way around, I found it much more difficult to sound even decent.

I thought it could be because Bm triad is B D F# and F# is not in Em pentatonic, while the B triad is B D# F# which are all in G# pentatonic. So I changed F# to the closest note in Em pentatonic, G, which means I'm left with a G triad. So I tried this :
Em Am | Em Am | Bsus4 B | G#m C#m | G#m C#m | Bsus4 G
But the chord themselves didn't sound that good (even if I tried to play G in first inversion to keep B at the bass, to have some sense of resolution for the suspended chord), and when I tried to improvise the problem remained.
I thought it could be because of the resolution sus4 -> minor which isn't as appealing as sus4 -> major, so I tried this progression :
Em Am | Em Am | Bsus4 B | G#m C#m | G#m C#m | Bsus2 Bm
Bsus2 isn't part of both keys, but at least the resolution Bsus2 -> Bm sounds better. But alas, improvising a melody that sounded good when going from G# aeolian to E aeolian was still a challenge.

Coming back to my initial progression
Em Am | Em Am | Bsus4 B | G#m C#m | G#m C#m | Bsus4 Bm
I don't get how this doesn't work. I thought it could also be that B doesn't have the same function in both keys, but it happens to be that B is V in E aeolian and III in G# aeolian. Functionnally it should work, even if I'm only mostly going from Em penta to G# penta and back, shouldn't it ? Even if that's the issue, I've tried to change B to G, which is III in E aeolian (see first point above) but it doesn't work !
Since I've never tried modulating while improvising before, I doubt it could be my improvising itself that is the issue. If it is, why is it so easy for me to change from E to G# but not the other way around ? And even if it's just my ear that is not accustomed to this change, why is there a difference really ?
I'm also thinking that maybe from E to G# your going up a major third while from G# to E you're going up a sixth, but I'm not sure I understand why it could be that that makes that much difference. Obviously E and G# are as far away from each other as G# and E are in the circle of fifths.
Is it maybe because of the relative functions of the common notes in both keys ? In E aeolian, E F# B are I, II, VI, and in G# aeolian they are II, VI, VII. I'm not sure were to go from there if that's the reason.

TL;DR : Using a common-chord modulation from E aeolian to G# aeolian and improvising, going from E to G# sounds good pretty easily, but not the other way around. Why is that ? I'm using the same method to come up with the chords, and I've never improvised in such a modulation context before, so there is no apparent reason why one change should be easier than the other.
Comment: Would you mind clarifying some of your chord qualities? Those G♯ and C♯ chords are all minor, correct?
Comment: Yes indeed, mistake on my part !
Comment: (original post edited)
Comment: I think the same problems will be there even if you modulate from E major to G# major, and use diatonic notes. When modulating, usually, the ultimate chord before the change is V of the new key. Going from E to G# (majors) will need D#(7), while returning will need B(7). Same problem, I think. That lack of leading note, as Richard spotted, is a bigger problem.
Answer: One possible fix might be found in this sentence:

it happens to be that B is V in E aeolian

I wonder if you're conflating V as a dominant major triad with the triad built on the fifth scale degree. Because the triad built on the fifth scale degree is B minor (v), which doesn't lead back to an E tonic as smoothly as a B-major triad (V) would.
Technically, this B-major chord doesn't fit your stipulation that you want this chord to be diatonic in the subsequent key (in this case, E Aeolian). But when I play your progression, the D♮ in that chord sticks out to me as a "wrong" note. And culturally, we're really accustomed to hearing a B-major triad move to an E tonic. This means that, just by playing a D♯ in that chord, you really strengthen the resolution to E and make clear to your listeners that you're looping back to the beginning.
And this doesn't interrupt your improvisation either; you can continue to use G♯ Aeolian above this chord if you like. It is, after all, the relative key/scale of this B-major chord!


Propagation of Error question?

Question: If I have a function $$f(r,V,B)=\frac {2V}{r^2B^2} = 2Vr^{-2}B^{-2}$$ what is the propagation of error?
If I use the power rules and multiplication rules described here http://www.fas.harvard.edu/~scphys/nsta/error_propagation.pdf
and
http://www.physics.pomona.edu/sixideas/labs/LRM/LR09.pdf
I get:
$$ \sigma_f = \mid f\mid*\sqrt{\frac{4}{r^2}(\sigma_r)^2 + \frac {(\sigma_V)^2}{V^2}+\frac{4}{B^2}(\sigma_B)^2} $$
Is this correct?
Answer: Your answer is correct. The underlying theory of propogation is alluded to in the footnote of the first link you provide.
Generally, if you assume that the errors in your measurements (say of, r, V, B to use your example) are unbiased with variance $\sigma_r^2,\sigma_V^2,\sigma_B^2$, respectivley, then a given function of these variables, $f(r,V,B)$, will be affected by the uncertainty in the underlying variables through its first derivative (NOTE: this is only valid if the errors are assumed to be "small", so that the function is well approximated by a line over the expected range of error):
From calculus, the total derivative of $f$ is: $df = \frac{\partial f}{\partial r} dr + \frac{\partial f}{\partial V}dV +\frac{\partial f}{\partial B}dB$.
Now, we re assuming that $dr, dV, dB$ are small, independent, random errors, with $E[dr]=E[dV]=E[dB]=0$ and variances $\sigma_r^2,\sigma_V^2,\sigma_B^2$.
From the linearity of expectation, we get the usual variance formula:
$\sigma_f^2 = \left(\frac{\partial f}{\partial r}\right)^2\sigma_r^2 + \left(\frac{\partial f}{\partial V}\right)^2 \sigma_V^2 +\left(\frac{\partial f}{\partial B}\right)^2 \sigma_B^2$
Therefore, the standard deviation of $f$ is just the square root of the above. If the errors are assumed to be normally distributed, then $f$ is normally distributed about the estiamted value with the above variance.
Comment: I understand the usual variance formula that you provided. However, isn't the propagated error if I use the partial of f with respect to r/V/B different than if I use the power law rules for uncertainty in the first link that I provide? (i.e. (df/dr)^2 does not equal 4/r^2)
Comment: @user136816 That is true, but you pulled out $f$ in your standard deviation equation. Re-integrate the $f$ into the square root and you will get the proper result.
Comment: I understand now. Many thanks.

Propagation of Error question?


Remote server RDP resolution

Question: I have a remote 2012 R2 base server in the cloud, I am running some scripts that are very dependent on the resolution.
When i connect via RDP and record my mouse actions everything is fine, but as soon as i disconnect the RDP, the resolution changes and everything goes wrong...
It is not possible to keep my computer on 24/7 hence I got that server.
Due to this unstable resolution it's becoming very difficult.
I'm looking for two options:

how to keep the RDP alive even after switching off the PC
how to get the resolution of the server after disconnecting so that I can record all mouse events in that resolution.
Answer: First of all, instead of using mouse clicks to script, which is going to be fragile whatever you do, I'd suggest investigating ways of scripting things without relying on mouse clicks.
But if this is really what you need to do, then instead of using RDP, if your cloud provider provides remote console access, you would be able to use the system console instead. You can then set up the server to Autologin (https://superuser.com/questions/499724/auto-login-windows-server-2012) to the user running the script on boot. You'd probably want a seperate user for this.
If your cloud provider doesn't allow remote console access, then you might be able to get access to the remote console anyway (at least after the server is booted, which is all you need in this case), using something like TeamViewer. (I'd try this process: Set up unattended remote access, reboot the server, and then connect back with Teamviewer. Hopefully you should then be remoted in to the console session of the server.)

Remote server RDP resolution


is it possible to get Z-score ranging from -17 to +20

Question: I have a data set in which I am trying to find outliers. I am using python libraries to get the Z-score value using below code :
<code>df['z_score']=stats.zscore(df[column_Name])
new_df=df.loc[df['z_score'].abs()>3]
</code>
Now the problem is that I get a good percent of my sample data which is having Z-Score > 3 or <-3. And due to which I cant drop it.
So, I checked the Z-Scores for all these columns and rows. The value of Z-Score is ranging from -17 to +20. Is it normal to get so high values of Z-Scores. And what does it shows about my data?
And in this case, how should I proceed, clearly I cant have Z-Score compared with 3. So, how do we do this in real world.
I am new to data science, I googled but did not find much help regarding this. So any leads will be appreciated.
Also, I am not able to understand this range  of -5 to 10 which gets displayed at the bottom of box plot. If I look at that, it looks like the data beyond this value of -5 to 10 is my outlier.
Comment: Is $z$-score basically the mean value divided by standard deviation?  In that case it is perfectly normal.  But what do you want to achieve with your analysis?
Comment: The master is against outlier detection: https://statmodeling.stat.columbia.edu/2014/06/02/hate-stepwise-regression/. Plenty of people will do it, but Gelman is right that statisticians tend not to think highly of it. What would you want to do with your data after you've discarded the outliers, though?
Comment: Please do say what you want to do with your data. A number of common tests make assumptions that this tendency to have extreme points (the high kurtosis I mention in my answer) might violate quite severely.
Comment: i wanted to find out the outliers and drop them to better tune my model
Comment: We generally discourage dropping extreme points. What do you want to model?
Comment: oh, then what do you suggest for extreme points. I read many articles for this, and all this seem to pointing towards discarding extreme points. I am sorry this is a broad question, you can just give me a very high level information if you want
Answer: This is totally fine. It might be inconvenient, but it doesn't meant that there's something wrong with the data.
What it means is that your data set is more prone to extreme observations than a normal distribution with the same variance. For a norma distribution, you have about a $0.06\%$ chance of getting an observation with a z-score of magnitude greater than $3$, and it's extraordinarily unusual to observe z-scores with magnitudes like $17$ and $20$.
So you don't have a normal distribution.
This is related to a quantity called kurtosis, which quantifies the propensity of a distribution to have extreme values. Every normal distribution has a kurtosis of $3$. If you stick your data into R and call kurtosis in the moments package, I would expect you to get quite a bit higher value than 3. The Python implementation, since you're into Python, is scipy.stats.kurtosis, though I think scipy subtracts 3 to give you the so-called excess kurtosis.
Answer: $Z$-scores with magnitude $\sim 15$ are extremely uncommon given that your data is drawn from a normal distribution. If the underlying population has heavy tails (i.e. $t$ or Cauchy distribution) or if there is heavy skew (i.e. exponential, lognormal) then it is not uncommon for a $Z$-score to be much larger than $3$.
For example, consider taking $n=10000$ draws from (i) a normal distribution, (ii) a $T$ distribution with $3$ degrees of freedom and (iii) an Exponential distribution. This figure shows the Z-scores corresponding to each distribution. Notice that the range of the Z-scores corresponding to the $t$-distribution is quite extreme, i.e. $-15$ to $15$.

So what does this tell you about your data? I would say that you can safely conclude that a normal distribution is not an appropriate model for your data. Based on your provided boxplots, the data is generated by a distribution with heavy tails.


SMTP Set up - where do I configure mail accounts on Windows Server 2008?

Question: I know about MX records, have configured SMTP and mail leaves my PICKUP folder on inetroot folder within Windows Server 2008 but I am stumped on where I actually configure the email addresses before I add them to Outlook 2010.
For example.
Sales@
Info@
PayPal@
I use Outlook as mentioned but when trying to set my email up (email@example.com) it asks for a username and password (I have not created a username and password, or this email in effect? Do I use the username and password used to log-onto the server?
When using EKM Mail subscription they made username and password for me, was this just a user account on the server or is there somewhere to configure this and the email itself?
Am I right in thinking once you've set up and configured a domain and an SMTP server for that domain, you can go ahead and use firstname.lastname@example.com as an email address? And the username and password is infact the username on the server E.G Administrator and the password is the one you created to log into the server.
I have used an email.rbs (I believe it was .rbs) file that stated "email sent" so I know SMTP is working.
Microsoft Exchange in itself is a mail server, which is what I have set SMTP up for myself, to avoid needing this and its cost right?
As mentioned I am using outlook to try to receive from mail.upnorthsound.co.uk but it fails to log on to incoming mail server (MX record setup with 123reg some time ago). I also get an error when Microsoft tries to send the test email. 550 5.7.1 Unable to relay
I have also tried to use smtpdiag.exe to get a black screen flash of the window but the .exe will not open.
Please take it lightly on me, this is my first time configuring a server and I'm learning slowly. This is the only issue can't seem to get past at the minute. Thanks for your time in advance and as I say take it easy on me if this is a stupid question.
Comment: PS: When I sent a test email, it left the pickup folder but didn't hit the Gmail account I had sent it too and didn't reside in the badmail folder.
Comment: Are you wanting this 2008 server to be an SMTP MTA (route mail) or an actual mailbox/email account server with local mailboxes?  Is mail.upnorthsound.co.uk your server or a 3rd party mail server?
Answer: The Windows Server SMTP feature doesn't allow you to create accounts, store email in inboxes, or deliver email to your Outlook clients. It's simply a SMTP forwarder.
If you want to create mail accounts for email@example.com and similar, you're looking for Microsoft Exchange or another full featured mail server.
The SMTP role on Windows Server is meant so that applications can send email from the server that they are running on. It is not meant to be a replacement for Exchange, Zimbra, etc. As a matter of fact, this role been deprecated in newer versions of Windows because it hasn't been terribly useful to most people for quite a while.

To answer your specific questions:

I use Outlook as mentioned but when trying to set my email up (email@example.com) it asks for a username and password (I have not created a username and password, or this email in effect? Do I use the username and password used to log-onto the server?

You would use Active Directory users for this and assign them a mailbox through the Exchange management tools. You can't do this using Microsoft tools without Exchange and AD.

Am I right in thinking once you've set up and configured a domain and an SMTP server for that domain, you can go ahead and use firstname.lastname@example.com as an email address? And the username and password is infact the username on the server E.G Administrator and the password is the one you created to log into the server.

Nope. That's not right. Exchange leverages Active Directory users for this. It's not local users on the server.

I have used an email.rbs (I believe it was .rbs) file that stated "email sent" so I know SMTP is working.

The mail was "sent" but likely marked as spam immediately by the receiver if you don't have things like MX, DKIM, and rDNS in place.

Microsoft Exchange in itself is a mail server, which is what I have set SMTP up for myself, to avoid needing this and its cost right?

Nope, you need Exchange here (or another mail server.) Exchange is the most common mail server on Windows, though you do see Domino from time to time (shudder).

I have also tried to use smtpdiag.exe to get a black screen flash of the window but the .exe will not open.

That is a command-line tool. You need to launch it from a command prompt. The executable is in fact launching, completing, and exiting, which is the black flash you're seeing. If you launch it from within a command prompt or PowerShell environment, the window will not close immediately and you can inspect the output.

Please take it lightly on me, this is my first time configuring a server and I'm learning slowly.

Good Luck!
Comment: user173421 - The SMTP role is not and never was a "mailbox" server. It's simply an SMTP server. What you're probably referring to is the POP server that was deprecated sometime around the release of Windows Server 2008. You don't necessarily need an Exchange server, you can try hMailServer or MDaemon or any one of a number of other "email" servers that are available for Windows.
Comment: Ok Great, just before I read your post I had watched this video which basically shows the user adding an Active Directory User within the domain. Then using exchange to configure the mailbox, then onto Outlook. Guess I need to go and get Exchange/Zimbra then... What has the SMTP role been replaced with if it has not become useful these days out of curiosity?
Comment: Yep. You need Active Directory and Exchange if you want to do this with the Windows email stack.
Comment: @user173421 .Net has a native mail function that allows you to specify a remote SMTP server, so most applications just send the mail themselves directly to the Exchange (or other vendor's) mail server. Back in the good old days, this wasn't the case and the application needed the server that it was currently running on to be able to send the mail on its behalf. There's no need to replace it, since all that it did was act as a dumb relay. It never could do what you wanted it to do, and now its usefulness is limited to legacy applications in old languages.
Comment: MDMarra, thankyou Sir! -  I am now looking into all available mail server options.


Assist me to understand the ethtool output

Question: We have two servers that connect to a third party platform. One server has constant communication issues, the other does not.
I validated using the 'route' command that both servers use 'eth0'
When I do 'ethtool eth0' on the server that has NO connectivity problems I get this:
   Settings for eth0:
        Supported ports: [ Backplane ]
        Supported link modes:   100000baseKR4/Full
                                100000baseSR4/Full
                                100000baseCR4/Full
                                100000baseLR4_ER4/Full
        Supported pause frame use: Symmetric
        Supports auto-negotiation: Yes
        Supported FEC modes: Not reported
        Advertised link modes:  100000baseKR4/Full
                                100000baseSR4/Full
                                100000baseCR4/Full
                                100000baseLR4_ER4/Full
        Advertised pause frame use: No
        Advertised auto-negotiation: Yes
        Advertised FEC modes: Not reported
        Speed: 100000Mb/s
        Duplex: Full
        Auto-negotiation: on
        Port: Direct Attach Copper
        PHYAD: 0
        Transceiver: internal
        Current message level: 0x000000f7 (247)
                               drv probe link ifdown ifup rx_err tx_err
        Link detected: yes

When I check the server that has BAD connectivity problems I see a lot different:
Settings for eth0:
        Supported ports: [  ]
        Supported link modes:   Not reported
        Supported pause frame use: Symmetric
        Supports auto-negotiation: Yes
        Supported FEC modes: Not reported
        Advertised link modes:  Not reported
        Advertised pause frame use: No
        Advertised auto-negotiation: No
        Advertised FEC modes: Not reported
        Speed: 50000Mb/s
        Duplex: Unknown! (255)
        Auto-negotiation: off
        Port: None
        PHYAD: 0
        Transceiver: internal
        Current message level: 0x000000f7 (247)
                               drv probe link ifdown ifup rx_err tx_err
        Link detected: yes

These servers are both Ubuntu 22.04 servers hosted on Azure
Where does this configuration come from? How can I change the one to be like the other?
Answer: Try running
ip -s link show eth0

It might be due to some missing driver so try comparing the output of lsmod on both servers.


RSpec Not Seeing Model Destroy

Question: RSpec is not seeing the destruction of the model when I call destroy from the controller. Is there some additional command I need to have in the ProjectsController#destroy method to make rails actually perform the destroy? Or to tell RSpec to reload the Project count after the destroy completes? (Rails 3.2.2)
<code>class ProjectsController < ApplicationController
  def destroy
    @project = current_user.my_projects.find params[:id]
    @project.destroy
  end
end

describe ProjectsController do
  let(:current_user) { Factory(:user) }
  let(:current_user_project) { current_user.my_projects.create(Factory.attributes_for(:project, owner: nil)) }

  context "one of the current users projects" do
    before { delete :destroy, format: :json, id: current_user_project }
    it { response.should be_success }
    it { expect { delete :destroy, format: :json, id: current_user_project }.to change(Project, :count).by(-1) }
  end
end
</code>
Answer: As much as I remember, in Rails calling destroy only deletes the record in your database and  only freezes your object, meaning you cannot assign values anymore. But it does not actually delete your object. So you have to reload to see your changes.
Comment: How do I reload in the test?

RSpec Not Seeing Model Destroy


Android - Ciclo para verificar se uma CheckBox está ativada ou não

Question: Dentro do evento de um Button tenho um ciclo while que está constantemente a verificar o estado de uma CheckBox. O problema é que se a CheckBox for ativada a Atividade congela!
Alguém me pode ajudar na solução deste problema?
botao.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        while(checkbox1.isSelected()){

            Toast.makeText(MainActivity.this, "CheckBox está ativada!", Toast.LENGTH_SHORT).show();

            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {e.printStackTrace();}
        }

        Toast.makeText(MainActivity.this, "CheckBox já não está ativada!", Toast.LENGTH_SHORT).show();

    }
});

Comment: Congela porque a execução não sai do `while`. Se explicar qual é o objectivo que quer conseguir com esse código, talvez se encontre uma forma alternativa.
Comment: Congela durante quanto tempo?
Comment: Não entendi o porquê daquele *sleep*.
Comment: O objetivo do `while` é só verificar se a `checkbox` está ativa?
Comment: Me parece que aquele `while` poderia ser substituído por um `if`.
Comment: A ideia, é de tempo a tempo ser executado um código que vai alterar a mensagem de uma TextView, mas só no caso da Checkbox estar ativa (razão do sleep dentro do While).
Comment: Você deve usar um `AsyncTask` para fazer isso. Vou preparar uma resposta.
Comment: ramaral, desde já obrigado pela sua ajuda. Fico aguardar a sua resposta...
Comment: @ramaral, talvez um `TimerTask` junto com um `Timer` seja uma melhor solução que uma `AsyncTask`, pela natureza do problema, não tenho certeza. Isso também porque o `Timer` roda em uma Thread separada da `MainThread`.
Comment: Podia mostrar-me um exemplo? Obrigado.
Comment: @Wakim Sim tem razão. Dê você a resposta.
Answer: Seguindo a sugestão do Wakim o código seria este:
public class TesteActivity extends Activity {

    Timer timer;
    TimerTask timerTask;
    final Handler handler = new Handler();

    CheckBox checkBox1;
    TextView textView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.teste);

        textView1 = (TextView)findViewById(R.id.textView1);
        checkBox1 = (CheckBox)findViewById(R.id.checkBox1);

        checkBox1.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                if(((CheckBox) v).isChecked()){//Se está checado inicializa o TimerTask

                    startTimer();
                }
                else{//se não pára o TimerTask
                    stopTimerTask();
                }
            }
        });
    }

    public void startTimer() {

        timer = new Timer();

        //Inicializa o TimerTask
        initializeTimerTask();

        //Executa imediatamente o TimerTask, repetindo-o a cada 1s
        timer.schedule(timerTask, 0, 1000); //
    }

    int i = 0;
    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                handler.post(new Runnable() {
                    public void run() {

                        //Coloque aqui o código que quer que seja executado quando
                        //o CheckBox está checked
                        //Neste exemplo o valor do textView será incementado em 1 a cada segundo
                        i++;
                        textView1.setText(Integer.toString(i));
                    }
                });
            }
        };
    }

    public void stopTimerTask() {
        //Pára o timer
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}

Quando o CheckBox é checado o TimerTask  é iniciado. Quando o ckeck é retirado o TimerTask é parado.
Se o TimerTask não necessitar de estar rodando quando a Activity estiver em segundo plano, faça o override dos métodos onPause e onResume desta forma:
@Override
protected void onPause() {
    super.onPause();

    stopTimerTask();
}

@Override
protected void onResume() {
    super.onResume();

    if(checkBox1.isChecked()){
        startTimer();
    }
}

Comment: Wakim e ramaral, obrigados pelos dois exemplos. Eu hoje não vou poder testar, mas amanhã deixo aqui uma resposta. Obrigados.
Comment: Wakim e ramaral, a vossa ajuda funciona perfeitamente. Obrigado aos dois.
Answer: Minha sugestão é bem simples, usar um Timer para executar uma tarefa de verificação em determinados períodos:
private static final long INTERVAL = 4000l;

Timer mTimer;
Button mButton;
Checkbox mCheckbox;

TimerTask mVerifyTask = new TimerTask() {
    @Override
    public void run() {
        verificarCheckbox();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Realizar sua inicializacao

    mTimer = new Timer();

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTimer.cancel();
            mTimer.scheduleAtFixedRate(mVerifyTask, INTERVAL);
        }
    });

void verificarCheckbox() {
    if(mCheckbox.isChecked()) {
        if(Looper.myLooper() != Looper.getMainLooper()) {
            runOnUiThread(new Runnable() { notificarNaMainThread });
        } else {
            notificarNaMainThread();
        }
    }
}

void notificarNaMainThread() {
    Toast.makeText(MainActivity.this, "CheckBox está ativada!", Toast.LENGTH_SHORT).show();
}

Uma observação: Não é permitido alterações de View's fora da MainThread, mas consultas ao estado é permitido. Se não houver aproveitamento do método verificarCheckbox para ser usado no `Timer´ e fora dele, então o
if(Looper.myLooper() != Looper.getMainLooper()) {

não é necessário, podendo ser simplificado.
Comment: Como você não respondia, estive a preparar uma resposta. Se não levar mal irei postá-la.
Comment: É que estava a caminho do trabalho, mas pode postar sem problema nenhum, posso até apagar a minha hehe.
Comment: Ficam as duas .
Comment: (+1) O OP escolheu a minha resposta, no entanto a sugestão foi sua.