Upload de PDF por ajax

Question: Tenho um form com varias inputs text e 1 input file (onde faço o envio de um arquivo PDF). Se eu enviar por ajax ele não faz o envio do "FILE", testei enviar sem ajax, apenas por submit, e funcionou. A questao esta mesmo no envio por ajax. Fiz algumas varias pesquisas sobre o assunto, mas não consegui solucionar. Poderiam me apontar uma solução para esse caso por favor.
Esse é o script js:
$("#cadastrarJob").click(function (){
var trabalho  = $("#jobTrabalho").val();
var cliente   = $("#jobCliente").val();
var valor     = $("#jobValorContrato").val();
var gastos    = $("#jobGastos").val();
var descricao = $("#jobDescricao").val();
var file      = $("#jobFile").val();

if(trabalho == '' || cliente == '' || valor == '' || gastos == '' || descricao == '' || file == ''){
    $.notify({
        message: 'Preencha todos os campos!',
        },{
        // settings
        element: 'body',
        position: null,
        type: "danger",
        placement: {
            from: "top",
            align: "center"
        }
    });
}else{
    var data = $("#formAddJob").serialize();

    $.ajax({
        type : 'POST',
        url  : '../conexao/addJob.php',
        data : data,
        dataType: 'json',
        success :  function(retorno){
            if(retorno.erro == 0){
                alert(retorno.mensagem);
            }
        }
    });
}
});

Esse é o PHP:
<?php
if(isset($_POST['trabalho']) && $_POST['trabalho'] != ''):

$trabalho   = (isset($_POST['trabalho'])) ? $_POST['trabalho'] : '' ;
$cliente    = (isset($_POST['cliente'])) ? $_POST['cliente'] : '' ;
$vContrato  = (isset($_POST['valor'])) ? $_POST['valor'] : '' ;
$gEstimados = (isset($_POST['gastos'])) ? $_POST['gastos'] : '' ;
$descricao  = (isset($_POST['descricao'])) ? $_POST['descricao'] : '' ;

// Pasta onde o arquivo vai ser salvo
$_UP['pasta'] = '../img/logoClientes/';
// Tamanho máximo do arquivo (em Bytes)
$_UP['tamanho'] = 1024 * 1024 * 10; // 10Mb
// Array com as extensões permitidas
$_UP['extensoes'] = array('pdf', 'doc', 'docx', 'jpg');
// Renomeia o arquivo? (Se true, o arquivo será salvo como .jpg e um nome único)
$_UP['renomeia'] = false;
// Array com os tipos de erros de upload do PHP
$_UP['erros'][0] = 'Não houve erro';
$_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do PHP';
$_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
$_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
$_UP['erros'][4] = 'Não foi feito o upload do arquivo';
// Verifica se houve algum erro com o upload. Se sim, exibe a mensagem do erro
if ($_FILES['file']['error'] != 0) {

  die("Não foi possível fazer o upload, erro:" . $_UP['erros'][$_FILES['file']['error']]);
  exit; // Para a execução do script
}
// Caso script chegue a esse ponto, não houve erro com o upload e o PHP pode continuar
// Faz a verificação da extensão do arquivo
$arquivo = $_FILES['file']['name'];
$arr = explode('.', $arquivo);
$extensao = strtolower(end($arr));
if (array_search($extensao, $_UP['extensoes']) === false) {
  echo "Por favor, envie arquivos com as seguintes extensões: jpg, doc ou pdf";
  exit;
}
// Faz a verificação do tamanho do arquivo
if ($_UP['tamanho'] < $_FILES['file']['size']) {
  echo "O arquivo enviado é muito grande, envie arquivos de até 10Mb.";
  exit;
}
// O arquivo passou em todas as verificações, hora de tentar movê-lo para a pasta
// Primeiro verifica se deve trocar o nome do arquivo
if ($_UP['renomeia'] == true) {
  // Cria um nome baseado no UNIX TIMESTAMP atual e com extensão .jpg
  $nome_final = md5(time()).'.jpg';
} else {
  // Mantém o nome original do arquivo
  $nome_final = $_FILES['file']['name'];
}

// Depois verifica se é possível mover o arquivo para a pasta escolhida
if (move_uploaded_file($_FILES['file']['tmp_name'], $_UP['pasta'] . $nome_final)) {
  // Upload efetuado com sucesso, exibe uma mensagem e um link para o arquivo
  echo "Upload efetuado com sucesso!";
  echo 'Clique aqui para acessar o arquivo';
} else {
  // Não foi possível fazer o upload, provavelmente a pasta está incorreta
  echo "Não foi possível enviar o arquivo, tente novamente";
}

    $retorno['erro']     = '0';
    $retorno['mensagem'] = 'Tem post';
    echo json_encode($retorno);
else:
    $retorno['erro']     = '0';
    $retorno['mensagem'] = 'Não tem post';
    echo json_encode($retorno);
endif;
?>

Lembrando que o codigo PHP esta funcionando perfeitamente, pois testei ele sem ajax, apenas por submit e funcionou certinho.
Answer: O problema é que o Jquery não encontra o caminho até ao ficheiro que você quer fazer upload, ou seja, se você fizer um alert ao input file você vai ver que vai dar por exemplo C:/fakepath/(nome_do_ficheiro.pdf)
Penso que não seja possível fazer uploads através de Jquery
Answer: Então para realizar o upload precisa realizar a chamada do ajax da seguinte forma
Pega o arquivo do formulário
 var file_data = $('#take-picture').prop('files')[0];
 var form_data = new FormData();

jqxhr = $.ajax( {
    type: 'POST',
    url  : '../conexao/addJob.php',
    data:form_data,
    processData:false,
    contentType:false,
})
insira o código aqui

processData:false // impede o processamento automático que por padrão é chave valor
contentType:false // diz a requisição que não gere um cabeçalho padrão para o envio, por padrão essa configuração vem como true no jquery, isso adiciona um cabeçalho uft-8 que pode impedir o envio de arquivos
FormData //Permite anexar objetos de arquivo para solicitações XHR (solicitações Ajax)

Upload de PDF por ajax


Calling controller method using @Url.Action in angularjs

Question: I want to call controller method by using @Url.Action in href,
how can we do the same?

            {{parent.menuname}}

                {{child.menuname}}

{{children.menuname}}

Answer: Since URL.Action is Razor code and it will execute at server so you can not pass your client side data to it.
either you can do it as follows

which will construct the URL controller and action name or you can do it via plain Html way

by any of the above way you can redirect your link to the desired controller+action


Reflection or Dynamic Dispatching

Question: I'm writing a abstract file parser (C#) which is extended by two concrete parsers. Both need to perform several checks. Currently there is a validate method in the abstract parser, which uses reflection to call all methods with a name starting with 'test'. That way adding checks is as easy as adding a method with a name that starts with 'test'.
Now recently I've had some comments about the use of reflection and it being better to use dynamic dispatching. My question to you is, why not use reflection and how would you implement this? Also how should I use dynamic dispatch to solve this problem?
    public bool Validate()
    {
        bool combinedResult = true;
        Type t = this.GetType();
        MethodInfo[] mInfos = t.GetMethods();

        foreach (MethodInfo m in mInfos)
        {
            if (m.Name.StartsWith("Check") && m.IsPublic)
            {
                combinedResult &= (bool)m.Invoke(this, null);
            }
        }
        return combinedResult;
    }

Answer: You should use regular OOP and not reflection for this. Have you abstract class expose an abstract method like Validate. Each parser will have to implement it. In the Validate, each parser will call the revelent Check methods to do the work.
Comment: Definitely best to stay with standard OOP practices.  Reflection is quite useful, but not as efficient as standard function calls.
Comment: Also, when it comes to abstract syntax trees (if your using them) check out the visitor Pattern.
Answer: There's nothing wrong with code that works... until someone comes to maintain it. In particular, this kind of convention would need to be documented quite carefully as it's not immediately obvious how your class will do what it does.
(As an aside, however, using Reflection for this will be rather slow.)
The most obvious way might be to have an abstract base method bool Validate() that is implemented by the subclasses. The subclasses then have e.g.
public override bool Validate()
{
    return TestFirst() &&
        TestSecond() &&
        TestThird();
 }

While this looks bulky it's immediately obvious what's going on. It also makes unit testing of Validate() a breeze.
It might also be possible to have the Testxxx() methods register themselves with the superclass in the constructor so they are called automatically - but that's more work and probably less maintainable.
If you really want to do this with reflection, consider marking the Testxxx() methods with attributes and reflecting on those instead. Then your code remains readable.
Answer: As far as I understand, dynamic dispatch is for the cases when you need to determine the method to call based on the type of its arguments. In your case, you call methods with no arguments, so I am not sure what dynamic dispatch has to do with this.
I like your approach for quick-and-dirty stuff. For production-quality code, I see the following potential problems with your approach:

you don't check for argument types and return types, so if you or someone adds a method string CheckWithWrongReturnType then your code breaks.
every time you call this function it calls GetMethods() and goes through the list. This is probably inefficient. Might be better to cache this list in an array.

To avoid reflection, I would create a delegate and make each class return a list of delegates.
delegate bool Validator();

bool F1() { return true;  }
bool F2() { return false; }

List<Validator> validators = new List<Validator>(F1, F2);

// then in the main class you can do this:
foreach(Validator v in validators)
{
   combinedResult &= v();
}

Reflection or Dynamic Dispatching


trapezodial rule matlab

Question: I want to integrate "\int_{0}^{1}(exp(-int_{0}^{y}f(x)dx))dy" with my basic trapezoid algorithm. I recieve an error declaration, but I should define g as a function. Do you have any idea  how to do it?
Thanks a lot for any answer!
function y = trapapadbl(low1, up1,low2,up2,intstep1,intstep2,f)
g = 0;
step1 = (up1 - low1) / intstep1;
step2 = (up2 - low2) / intstep2;

for j = low1 : step1 : up1
    g = g + feval(f,j);
end
g = @(y)(g - (feval(f, low1) + feval(f, up1))/2) * step1;
for i = low2 : step2 : up2
    y= y + feval(g,i);
end
y= (y - (feval(g, low2) + feval(g, up2))/2) * step2;

Comment: Could you provide an example call?
Comment: Can you also display the error message?
Comment: tesekkurler @İsmail Arı:) What I want to evaluate is for example  int_{0}^{2}int_{0}^{y}exp(x)dx dy=? I have a poor experience on programming, but I think I probaly should define a function for inner integral. "How" is actually my question? tesekkürler tekrar...
Comment: f=@(x)x^2

f =

    @(x)x^2

>> trapapadbl(0, 1,2,3,10,10,f)
??? Undefined function or variable "y".

Error in ==> trapapadbl at 18
    y= y + feval(g,i);
Answer: >> trapapadbl(0,1,0.1,0,1,0.1,@sin)

??? Undefined function or variable "y".

Error in ==> trapapadbl at 12
    y= y + feval(g,i);

Without working too hard to try to understand your code (!) the error is that y was never initialized.  You can't add anything to y until it has a value.  When I initialize y to 0, the code runs, but I get 0 as an output, which is not what happens when you integrate sin from 0 to 1.  I may be calling the function wrong, but it's something to look out for!
Furthermore, your code is confusing, because you use the variable g as both a double (a number) and a function, even in the same line!  The same problem happens as y is the input to your anonymous function, but also a double later on.  It's syntactically correct, but a little hard to read.  Consider using a different variable name, or including clear comments (or both!)
Comment: thank you @alexplanation! Now I found my question also a bit confusing:)

trapezodial rule matlab


IPTables quota not working on Ubuntu 12.04

Question: I've been struggling porting IPTable rules from Ubuntu 10.04 to Ubuntu 12.04. The problem is that quota seems to be broken. Take this very simple instance of a quota rule.

iptables -t mangle -A POSTROUTING -o eth0 -p tcp -m quota --quota 500000 -j ACCEPT

On Ubuntu 10.04 this is what we see when we transfer bytes though eth0.

(root@dev)-(~) $ iptables -L -t mangle -v | grep quota
146  111K ACCEPT     tcp  --  any    eth0    anywhere             anywhere            quota: 389148 bytes
(root@dev)-(~) $ iptables -L -t mangle -v | grep quota
667  348K ACCEPT     tcp  --  any    eth0    anywhere             anywhere            quota: 152577 bytes

You can see the quota is going down while the used bytes are going up (second column).
However when I use the same rules on Ubuntu 12.04 the following happens.

(root@LU1)-(~) $ iptables -L -t mangle -v | grep quota
14  2544 ACCEPT     tcp  --  any    eth0    anywhere             anywhere             quota: 500000 bytes
(root@LU1)-(~) $ iptables -L -t mangle -v | grep quota
19  3188 ACCEPT     tcp  --  any    eth0    anywhere             anywhere             quota: 500000 bytes

The used bytes counter is going up but the quota is not going down. However it is counting it and if the quota is used up it will continue to the next rule. There is a second problem though because when you reboot the server, and you save the rules, the quota gets reset again even if it was all used up.
So basically there are two problems: The quota is not visibly going down and it resets on reboot even though I'm saving the rules.
Kernel on Ubuntu 12.04 is 3.2.0-44-generic
lsmod output: http://sprunge.us/OfEc
Can anybody explain to me what's happening and where this difference between behaviour is coming from? Or even better propose a solution? I am really stuck on this and I would appreciate any of you can give me.
Answer: I answered my own question when digging through the kernel changes.
I've stumbled upon this commit. The thing I assumed was a bug was actual intended behaviour by the patcher. I've made a patch on the recent 3.2 kernel to revert this commit and everything works again. I hope this might save somebody else some hours of googling.


TFS integration - how to set environment variables accessible from test code

Question: I'm writing a TFS / VSTS integration with our server by using extension.
I want to present extra data after the build, specifically I want to show an IFRAME and navigate to our server, to a specific URL, determined in part by a dynamically generated unique string.
I have the function that generates the string, but I need to set it as an environment variable before the tests start to run. This is important because the tests need to create that string on the server.
I searched the documentation, examples and other places, but couldn't find a complete example that sets a dynamically generated environment variable and then runs tests.
How do I do it?
Comment: Are the tests run through the following task in build?
Comment: If your question is if the tests run in the next step - that can be arranged, as the test step is coming right after the build step. If you regard a specific task, then it seems you've forgot to state the task name... :-)
Answer: You can add/set an environment variable through Logging Commands (e.g. PS: Write-Host "##vso[task.setvariable variable=testvar;]testvalue"), then the following tasks can get this variable as general variable.
With Logging Commands, you also can add additional information in build summary. (##vso[task.uploadsummary]local file path)
You also can deploy a build result extension to display additional information. vsts-extension-samples
Comment: Thank you, I already came across that example. What I'm missing is how to write a task (and what type of task) that actually sets that variable, in extension code. Any references for that?
Comment: @ItaiBar-Haim Many task can do it, such as PowerShell task: `Write-Host "##vso[task.setvariable variable=testvar;]testvalue"`; Command Line task: `echo "##vso[task.setvariable variable=testvar;]testvalue"`; NodeJS: `Console.log("##vso[task.setvariable variable=testvar;]testvalue")`. Does the extension means build task extension? If so, the same way, just call Write-Host, Console.log etc...
Comment: When using built-in tasks like the ones you mentioned, as far as I understand, I can only pass a constant value, not something that is dynamically generated. For that I need to create a new task. Am I right?
Comment: @ItaiBar-Haim No, you can generate a string in the same task too, then set the variable value.
Comment: Based on the build info object? If so, how?
Comment: @ItaiBar-Haim What's build info object? Provide the details of build info object.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157442/discussion-between-itai-bar-haim-and-starain-msft).
Comment: @ItaiBar-Haim Could you do it in a task (e.g. PowerShell)?
Comment: I started writing a task, but I can't get it to work (I see the task running, but nothing happens, and no logs are written). I've moved on for now. Thank you for your help, BTW. I'll be in touch if and when I'll need further assistance.


Como acessar Virtual Machine (feita em qemu-kvm)

Question: Tenho um servidor Linux Centos7, sem interface gráfica. Usando Qemu-KVM consegui instalar dentro dele uma máquina virtual com windows2008server.
Usei o seguinte comando pra criar a maquina virtual:
<code> virt-install --name=windows --ram=3096 --vcpus=1 --cdrom=/opt/win2008server.iso --os-type=windows --os-variant=win2k8 --network bridge=virbr0 --graphics=spice --disk path=/var/lib/libvirt/images/win.dsk,size=15
</code>
A máquina virtual foi criada com sucesso, e está rodando.
Porém agora não sei como fazer pra acessa-la remotamente. Tentei o virt-viewer de uma estação Ubuntu, até acessa, mas na hora de formar a tela, dá um erro de falta de uma biblioteca libspice. Já instalei tais bibliotecas, mas nada.
Alguém tem alguma dica de como acessar (pode ser via Windows ou Linux) essa máquina virtual que está nesse servidor sem interface gráfica? Que software devo usar?
Notem que no comando de criação da vm, tem a opção graphics, onde escolhi spice.
Eu poderia tentar outra opção para o parâmetro graphics?
Obrigado.
Answer: Galera, já consegui... bastou mudar a opção --graphics para "vnc".
Com isso consegui acessar de outra estação windows usando o virt-viewer.


GPO Enforced Precedence

Question: What is the precedence for Enforeced GPOs, I can't really find any MS articles which give a refined answer.
My current understanding is as follows:
Lets say we have 5 GPO's - GPO1 through GP05. I will use an exam question to put into context.
GPO    Linked to   Enforced
GP01 - contoso.com - No
GP02 - contoso.com - Yes
GP03 -    Site 1   - Yes
GP04 -     OU1     - No
GP05 -     OU1     - Yes

Now my understanding would mean they would apply in this order, from the first to apply to the last to apply (thus the one with most precedence).
GP01 -> GP04 -> GP05 -> GP02 -> GP03 (meaning 3 has the final say on any duplicates)

Am I correct in my understanding? Many thanks!
Comment: your "apply in this order" is right in terms of WHAT gets applied but not necessarily on WHEN that gpo gets sequenced.  See my answer for clarification on that part.
Answer: I wrote about this here: http://myotherpcisacloud.com/post/2012/08/14/GPO-Application-Precedence-Just-Because-You-Can-Edition.aspx
TL;DR - The uppermost or parent GPO that is also enforced will win.
From Microsoft:

You can specify that the settings in a GPO link should take precedence
  over the settings of any child object by setting that link to
  Enforced. GPO-links that are enforced cannot be blocked from the
  parent container. Without enforcement from above, the settings of the
  GPO links at the higher level (parent) are overwritten by settings in
  GPOs linked to child organizational units, if the GPOs contain
  conflicting settings. With enforcement, the parent GPO link always has
  precedence. By default, GPO links are not enforced.

EDIT:
See here as well: GPO provides unexpected value
There it specifically states:

The Enforce setting is a property of the link between an Active Directory container and a GPO. It is used to force that GPO to all Active Directory objects within a container, no matter how deeply they are nested. The settings within a GPO that is enforced override other settings that would prevail because they are applied later. If there are conflicting settings in GPOs that are enforced at two levels of the hierarchy, the setting enforced furthest from the client prevails. This is a reversal of the usual rule, in which the setting from the nearest-linked GPO would prevail.
Comment: So then it's correct, in the above instance, the GPO linked to the Site will indeed win. Thankyou.
Comment: TheD - Just to be clear, this is relevant for settings that are common to both GPO's. If you have settings in the OU linked GPO that aren't set in the Site linked GPO then those settings will be applied by the OU linked GPO. Only when there are common settings in both GPO's does enforcement hierarchy come into play.
Answer: Ryan (and I :P ) answered the question on how 2 or more enforced GPOs are handled, but I wanted to clarify that while GPO3 linked to the site will "win", the OPs sequence of how they are applied isn't correct.
The OP states:

Now my understanding would mean they would apply in this order, from
  the first to apply to the last to apply (thus the one with most
  precedence).

GP01 -> GP04 -> GP05 -> GP02 -> GP03 (meaning 3 has the final say on any duplicates)

Remembering that:

As far as the sequence goes itself (including enforcement, but specifically the sequence order that the GPOs are looked at when processing):
GPO3 (with any of its settings enforced and taking precedence from here on out)
->
GPO1 or GPO2 (depending on link order at the domain level of these 2, with GPO2 being enforced except where GPO3 settings overrule because GPO3 is enforced at the site level)
->
GPO4 or GPO5 (depending on link order at the OU level of these 2, with GPO5 being enforced except where GPO2 or GPO3 settings overrule)
Comment: Sorry, but what is the order of processing then, like: GPOx -> GPOx, apologies but your explanation confused me just a little bit!
Comment: Lets say the link order hasn't been changed, so simply the GPO's are linked to the OU and Site .etc., what order are they processed in with regards to the first GPO to the last GPO.
Comment: The question itself says order them in the Order they will be applied to the client PC. Thanks!
Comment: I can't answer based on what a quiz WANTS the answer to be...but there is ALWAYS a link order when 2 or more GPOs are applied at a level even if you don't set one manually.  You can see this in the GPMC looking at the "Linked GPOs" tab for whatever level you are on.  GPOs are always processed in the ORDER that is in the pic I posted.  That doesn't mean they will take precedence or apply, only that it is the order they are looked at when deciding.  I've changed the "code" I posted to help clarify for you.
Comment: My query is, you show that GP03 is actually processed first, but I thought those with the highest precedence and processed last hence have the final say on the Policy.
Comment: No, site GPOs get processed before domain or OU (as in the pic).  So in your example GPO3 would be the start of the GPO settings sequence, but would also be flagged as "enforced" for its settings, so it would continue to be enforced as the GPO sequence continues on through the domain and OU levels.  Think of it more as going GPO3 then at the domain level the settings say "enable this...oh wait GPO3 says disable it and is enforced, nevermind", continuing on to do the same at the OU level.
Comment: To simplify and think in your terms...enforcing a single GPO doesn't mean "apply this last", it means "apply this in its sequence and then enforce it on any GPOs sequenced AFTER me".  Hence a GPO enforced at a site level will take precedence over any GPOs "below" it (like JoeQwerty said, assuming same settings are being changed within the GPOs).  It is the "reverse" of the norm, as I clarified in Ryan's answer.
Comment: Thanks, this has cleared it up. Thanks again for your assistance!
Answer: Linked Group Policy Objects
I also have not been facing with GPO for a long time, so I just use the tab "Linked Group Policy Object" in GPMC for recall

GPO Enforced Precedence


SQL Server | Agrupar linhas e dividir seus valores

Question: Gostaria de agrupar a linha 1 e 2 dos resultados da query e dividir seus valores (Valor1/Valor2). A tabela é a seguinte:

Preciso que resulte no seguinte:
1 - % Conversão de orçamentos - 0,944
A Query que a gerou esses resultados é:
SELECT
    'Quant média diária vendas', AVG([VALORORIGINAL]) AS Valor1, 0 AS Valor2, [tipo]

    FROM [dbo].[VIEW_MU_INDICADORES_SF]

        WHERE TIPO = 'QUANTIDADE VENDAS'

GROUP BY TIPO

UNION

SELECT
    'Quant média diária orçamentos', AVG([VALORORIGINAL]) AS Valor, 0 As Valor2, [tipo]

    FROM [dbo].[VIEW_MU_INDICADORES_SF]

        WHERE TIPO = 'QUANTIDADE PEDIDO VENDAS'

GROUP BY TIPO

UNION

SELECT
    '% Conversão orçamentos', CASE WHEN TIPO = 'QUANTIDADE VENDAS' THEN SUM([VALORORIGINAL]) END AS Valor, CASE WHEN TIPO = 'QUANTIDADE PEDIDO VENDAS' THEN SUM([VALORORIGINAL]) END AS Valor2, [TIPO]

    FROM [dbo].[VIEW_MU_INDICADORES_SF]

        WHERE TIPO = 'QUANTIDADE VENDAS' OR TIPO = 'QUANTIDADE PEDIDO VENDAS'

GROUP BY TIPO

A View informada na Query é:

Já tentei algumas soluções postadas aqui para perguntas correlatas, mas nenhuma funcionou.
Comment: para retirar evitar esse erro experimente colocar o Case dentro do Sum e especificar um valor fixo para a coluna Tipo no último trecho
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Se entendi : nomear a 1@ coluna , agrupar por ela , retirar o "tipo" do agrupamento.
Comment: Motta, a primeira coluna, não é uma coluna da view portanto não consigo agrupar por ela (ou não sei como fazer).

Se eu tirar o tipo do agrupamento, retorna o erro:

 "...is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
Answer: Experimente utilizar o código abaixo:
SELECT
    CASE WHEN [TIPO] = 'QUANTIDADE VENDAS' THEN AVG([VALORORIGINAL]) END
    /
    CASE WHEN [TIPO] = 'QUANTIDADE PEDIDO VENDAS' THEN AVG([VALORORIGINAL]) END
    AS '% Conversão orçamentos'
    FROM [dbo].[VIEW_MU_INDICADORES_SF]
        WHERE TIPO = 'QUANTIDADE VENDAS' OR
        TIPO = 'QUANTIDADE PEDIDO VENDAS'

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: resolvido, obrigado.


Custom filesystem provider to service multiple disks

Question: I have created custom filesystem service provider for setup my google cloud storage. I have multiple buckets so I created multiple disks in filesystems.php. But since all of these buckets are using similar settings I want to use single service provider. Can we achieve that?
ServicePrivider boot()
<code>Storage::extend('gcs_images_1', function ($app, $config) {
    $client = new StorageClient([
        'projectId' => $config['project_id'],
        'keyFilePath' => storage_path($config['key_file'])
    ]);

    $bucket = $client->bucket($config['bucket']);

    $pathPrefix = array_get($config, 'path_prefix');

    $storageApiUri = array_get($config, 'storage_api_uri');

    $adapter = new GoogleStorageAdapter($client, $bucket, $pathPrefix, $storageApiUri);

    return new Filesystem($adapter);
});
</code>
config/filesystems.php
<code>'gcs_images_1' => [
            'driver' => 'gcs_images_1',
            'project_id' => env('GOOGLE_CLOUD_PROJECT_ID'),
            'key_file' => env('GOOGLE_CLOUD_KEY_FILE'),
            'bucket' => 'img',
            'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', null),
            'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', null)
        ],
        'gcs_docs_1' => [
            'driver' => 'gcs_docs_1',
            'project_id' => env('GOOGLE_CLOUD_PROJECT_ID'),
            'key_file' => env('GOOGLE_CLOUD_KEY_FILE'),
            'bucket' => 'doc',
            'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', null),
            'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', null)
        ],
</code>
Answer: use Laravel Flysystem for filesystem
https://github.com/GrahamCampbell/Laravel-Flysystem
Answer: So after all solution was simple. Returning array of Filesystem instances
<code>        $fileSystems = array();
        foreach ($this->gcsDisks as $disk) {
            $fileSystems[] = $this->getFileSystem($disk);
        }
        return $fileSystems;
</code>
But still more clear way to do this is welcome as a answer


How to add auto taxonomy to node fields?

Question: How to add auto categorization(Taxonomy Term) to node based on node body/description.
Node Body/Description: Retro is back in style, so flaunt the same when wearing this T-shirt from PUMA. Fashioned for men, this piece can be easily worn when heading out for a crazy day ahead with friends. Live in the moment by wearing this T-shirt with casual trousers and flip-flops when you hit the street with your best buddies
Here i have : ->T-Shirts, flip-flops, MEN etc,
By reading this content i want to assign auto taxonomy term reference in node field as T-Shirts to node.
Is it possible to do this?
Anyone help me ASAP.
Thanks in advance.
Answer: If I understand you, there is a few modules which can handle it:

Word Link (I recommend it)

The Word Link module allows you to automatically convert specific
  words into links. It works as text filter. This can be useful for
  crossposting your site's pages, or for the contextual advertising of
  your partners (SEO).

Active Taxonomy Links

Active Taxonomy Links module processes nodes of selected content types
  replacing words in the nodes with links to taxonomy terms.

Glossify (this one supports Drupal 6 also)

The Glossify module provides filters that scan and parse content and
  replace terms in the text with links to their pages. The d7 version is
  a complete rewrite of the module to be as simple and performant as
  possible.


RestTemplate mapping to object

Question: I am trying to use RestTemplate to call a webservice, currently I am using the Object type rather than a concrete user defined one which is what I want to do.
Currently the response from the web service is:
{Locales=[{Code=ar-AE, Name=العربية (الإمارات العربية المتحدة)}, {Code=az-AZ, Name=Azərbaycanılı (Azərbaycan)}, {Code=bg-BG, Name=български (България)}]}

I am currently doing this:
Object locales = restTemplate.getForObject(localeUrl, Object.class, apiKey);

which is I want to be able to map it to a class that I have defined, but not sure how my class should be laid out, my class currently looks like this:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement(name = "Locales")
@XmlAccessorType(XmlAccessType.FIELD)
public class Locales {
    private List<Locale> Locales = new ArrayList<>();

    private Locales(){};

    public List<Locale> getLocales() {
        return Locales;
    }

    public void setLocales(ArrayList<Locale> newLocales) {
        this.Locales = newLocales;
    }
}

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Locale {
    private String Code;
    private String Name;

    private Locale(){}

    public String getCode() {
        return this.Code;
    }

    public void setCode(String Code) {
        this.Code = Code;
    }

    public String getName() {
        return this.Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }
}

Comment: You need to create your class which will map with the output. Better read this tutorial - https://spring.io/guides/gs/consuming-rest/
Comment: Hi @VikasSachdeva should my class be a class containing a List of objects which contains a code and name?
Answer: Use below code for calling API -
Locales locales = restTemplate.getForObject(localeUrl, Locales.class, apiKey);

Create one class Locales -
@XmlRootElement(name = "Locales")
@XmlAccessorType(XmlAccessType.FIELD)
public class Locales{
    private List<Locale> locales = new ArrayList<>();

    // getter and setter

}

Comment: I have tried this and got Locales(locales=[]) when dumping out to logs.  I will update my code above
Comment: Create getter and setter method in your Locales class with public access-specifier. I wrote in answer in comment to create getter and setter. Also, your Locale class should have getter and setter
Comment: Another way is to declare fields with public access-specifier. However, it is not recommended way.
Comment: Vikas, I am using Lombok data annotation and this creates getters and setters for me
Comment: I am not aware how Lombok data annotation works, maybe you can try to manually create getter/setter OR make your fields public and use annotation @XmlAccessorType(XmlAccessType.FIELD). It may be possible when jackson is looking for getter/setter to map json response, it is not able to find them.
Comment: I have attempted what you suggested but I am still getting a Locales(locales=[]), however when I set them all to public this seems to work fine.  I have updated my post above to reflect what I have changed in my models
Comment: So it means it is working after creating public getter/setter. This is what I suggested in comments. You can refer to this link for more details and alternative ways - http://stackoverflow.com/questions/6836657/jackson-1-8-0-objectmapper-to-serialize-deserialize-arbitrary-classes
Comment: Did you try removing @Data annotation and creating public getter/setter
Comment: Just read something useful http://stackoverflow.com/questions/39779219/jackson-not-recognizing-fields-that-exist . Maybe it will help

RestTemplate mapping to object


Can you stop embedded Flickr Images from following their link if the user clicks the image, thus leaving your Drupal website?

Question:
Using Drupal 7.37, Omega4-SubTheme
Acquia Dev-Desktop Stack (Development)
Windows 7 HP

Using Media Module with the Flickr provider Module installed, the Media_YouTube, and the Media_SoundCloud providers installed as well (along with their dependencies).
I set up some dummy-content via a customized Create-Content node. Added Flickr-Images as a field-type bundled with various tags to distinguish properties of my Media-Files for later categorization.  I have other Media-File-Types and their Providers installed as well (Media_YouTube, Media_SoundCloud) and they work fine without adding outbound-site-leaving-links.
Then I set up Views to output all the content of the website along with respective fields.  All this works and displays small representations of the media in a table along with my added fields.
In this Views display, Flickr embedded-images show up fine and can be styled, but unlike YouTube-Videos or SoundCloud_Audio-Files, Flickr-Embedded-Images will leave the website when clicked.  Both YouTube and SoundCloud do not exhibit this behavior and instead only play their respective Media.
Is there anyway to block, stop, or (best) redirect the Flickr-Images to show their associated node rather than linking to Flickr?
I have tried every configuration Option I can find.  I have tried options in the Create-Image-Content node GUI but I see nothing to suppress the outbound-links.  I have tried the Views-Display GUI, but again, I see nothing in the Views-Settings that suppresses the outbound-links.  And I have also tried the Administration>>Configuration>>Media>>File-Types setting for my Image-File-Types (this control-panel is very mysterious).  In none of these locations can I come across something which shuts-off this outbound behavior.
I have spent much time trying all kinds of option-permutations and searching for any kind of documentation but have come up with no solution.
Is there an option-solution or a css-workaround or do I have to abandon the Flickr-provider-module because this is its hard-wired behavior?
Comment: as a worst case, you could add a couple lines of jQuery to create a DIV over top of the image which would prevent it acting as a link
Comment: I decided just to strip out Flickr, Media_YouTube and Media_SoundCloud and go with Media_Oembed.  One Module handles all of the Embeds without Flickr-Images out-linking.
Answer: For now I have completely disabled Flickr as well as Media_YouTube and Media_SoundCloud in favor of using the Media_Oembed Module. Media_Oembed handles the all of the above Embed needs (and more).  In Media_Oembed, the Flickr Module does not out-link.  Probably a better overall solution in general.
 There are two OEmbeds!! At first, I tried Oembed, which is still in beta (as of 2015-06-03) and I could not get it to work; I don't know what the problem was, but Media_oEmbed seems to work fine.


How to track a CollectionView cell by time in Swift

Question: I've been working on a feature to detect when a user sees a post and when he doesn't. When the user does see the post I turn the cell's background into green, when it doesn't then it stays red. Now after doing that I notice that I turn on all the cells into green even tho the user only scroll-down the page, so I added a timer but I couldn't understand how to use it right so I thought myself maybe you guys have a suggestion to me cause I'm kinda stuck with it for like two days :(

Edit: Forgot to mention that a cell marks as seen if it passes the minimum length which is 2 seconds.

Here's my Code:
My VC(CollectionView):
import UIKit

class ViewController: UIViewController,UIScrollViewDelegate {

    var impressionEventStalker: ImpressionStalker?
    var impressionTracker: ImpressionTracker?

    var indexPathsOfCellsTurnedGreen = [IndexPath]() // All the read "posts"

    @IBOutlet weak var collectionView: UICollectionView!{
        didSet{
            collectionView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
            impressionEventStalker = ImpressionStalker(minimumPercentageOfCell: 0.70, collectionView: collectionView, delegate: self)

        }
    }

    func registerCollectionViewCells(){
        let cellNib = UINib(nibName: CustomCollectionViewCell.nibName, bundle: nil)
        collectionView.register(cellNib, forCellWithReuseIdentifier: CustomCollectionViewCell.reuseIdentifier)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        collectionView.delegate = self
        collectionView.dataSource = self

        registerCollectionViewCells()

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        impressionEventStalker?.stalkCells()

    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        impressionEventStalker?.stalkCells()
    }

}

// MARK: CollectionView Delegate + DataSource Methods
extension ViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        guard let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCollectionViewCell.reuseIdentifier, for: indexPath) as? CustomCollectionViewCell else {
            fatalError()
        }

        customCell.textLabel.text = "\(indexPath.row)"

        if indexPathsOfCellsTurnedGreen.contains(indexPath){
            customCell.cellBackground.backgroundColor = .green
        }else{
            customCell.cellBackground.backgroundColor = .red
        }

        return customCell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 150, height: 225)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) // Setting up the padding
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        //Start The Clock:
        if let trackableCell = cell as? TrackableView {
            trackableCell.tracker = ImpressionTracker(delegate: trackableCell)
            trackableCell.tracker?.start()

        }
    }

    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        //Stop The Clock:
        (cell as? TrackableView)?.tracker?.stop()
    }

}

// MARK: - Delegate Method:
extension ViewController:ImpressionStalkerDelegate{
    func sendEventForCell(atIndexPath indexPath: IndexPath) {

        guard let customCell = collectionView.cellForItem(at: indexPath) as? CustomCollectionViewCell else {
            return
        }

        customCell.cellBackground.backgroundColor = .green
        indexPathsOfCellsTurnedGreen.append(indexPath) // We append all the visable Cells into an array
    }
}

my ImpressionStalker:
import Foundation
import UIKit

protocol ImpressionStalkerDelegate:NSObjectProtocol {
    func sendEventForCell(atIndexPath indexPath:IndexPath)
}

protocol ImpressionItem {
    func getUniqueId()->String
}

class ImpressionStalker: NSObject {

    //MARK: Variables & Constants
    let minimumPercentageOfCell: CGFloat
    weak var collectionView: UICollectionView?

    static var alreadySentIdentifiers = [String]()
    weak var delegate: ImpressionStalkerDelegate?

    //MARK: Initializer
    init(minimumPercentageOfCell: CGFloat, collectionView: UICollectionView, delegate:ImpressionStalkerDelegate ) {
            self.minimumPercentageOfCell = minimumPercentageOfCell
            self.collectionView = collectionView
            self.delegate = delegate
        }

    // Checks which cell is visible:
    func stalkCells() {
        for cell in collectionView!.visibleCells {
            if let visibleCell = cell as? UICollectionViewCell & ImpressionItem {
                let visiblePercentOfCell = percentOfVisiblePart(ofCell: visibleCell, inCollectionView: collectionView!)

                if visiblePercentOfCell >= minimumPercentageOfCell,!ImpressionStalker.alreadySentIdentifiers.contains(visibleCell.getUniqueId()){ // >0.70 and not seen yet then...
                    guard let indexPath = collectionView!.indexPath(for: visibleCell), let delegate = delegate else {
                        continue
                    }

                    delegate.sendEventForCell(atIndexPath: indexPath) // send the cell's index since its visible.

                    ImpressionStalker.alreadySentIdentifiers.append(visibleCell.getUniqueId()) // to avoid double events to show up.
                }
            }
        }
    }

    // Func Which Calculate the % Of Visible of each Cell:
    private func percentOfVisiblePart(ofCell cell:UICollectionViewCell, inCollectionView collectionView:UICollectionView) -> CGFloat{

           guard let indexPathForCell = collectionView.indexPath(for: cell),
               let layoutAttributes = collectionView.layoutAttributesForItem(at: indexPathForCell) else {
                   return CGFloat.leastNonzeroMagnitude
           }

           let cellFrameInSuper = collectionView.convert(layoutAttributes.frame, to: collectionView.superview)

           let interSectionRect = cellFrameInSuper.intersection(collectionView.frame)
           let percentOfIntersection: CGFloat = interSectionRect.height/cellFrameInSuper.height

           return percentOfIntersection
       }
}

ImpressionTracker:
import Foundation
import UIKit

protocol ViewTracker {

    init(delegate: TrackableView)
    func start()
    func pause()
    func stop()

}

final class ImpressionTracker: ViewTracker {
    private weak var viewToTrack: TrackableView?

    private var timer: CADisplayLink?
    private var startedTimeStamp: CFTimeInterval = 0
    private var endTimeStamp: CFTimeInterval = 0

     init(delegate: TrackableView) {
        viewToTrack = delegate
        setupTimer()
    }

    func setupTimer() {
        timer = (viewToTrack as? UIView)?.window?.screen.displayLink(withTarget: self, selector: #selector(update))
        timer?.add(to: RunLoop.main, forMode: .default)
        timer?.isPaused = true
    }

    func start() {
        guard viewToTrack != nil else { return }
        timer?.isPaused = false
        startedTimeStamp = CACurrentMediaTime() // Current Time in seconds.
    }

    func pause() {
        guard viewToTrack != nil else { return }
        timer?.isPaused = true
        endTimeStamp = CACurrentMediaTime()
        print("Im paused!")
    }

    func stop() {
        timer?.isPaused = true
        timer?.invalidate()
    }

    @objc func update() {
        guard let viewToTrack = viewToTrack else {
            stop()
            return
        }

        guard viewToTrack.precondition() else {
            startedTimeStamp = 0
            endTimeStamp = 0
            return
        }

        endTimeStamp = CACurrentMediaTime()
        trackIfThresholdCrossed()
    }

    private func trackIfThresholdCrossed() {

        guard let viewToTrack = viewToTrack else { return }
        let elapsedTime = endTimeStamp - startedTimeStamp
        if  elapsedTime >= viewToTrack.thresholdTimeInSeconds() {
            viewToTrack.viewDidStayOnViewPortForARound()

            startedTimeStamp = endTimeStamp
        }
    }
}

my customCell:
import UIKit

protocol TrackableView: NSObject {
    var tracker: ViewTracker? { get set }
    func thresholdTimeInSeconds() -> Double //Takes care of the screen's time, how much "second" counts.
    func viewDidStayOnViewPortForARound() // Counter for how long the "Post" stays on screen.
    func precondition() -> Bool // Checks if the View is full displayed so the counter can go on fire.
}

class CustomCollectionViewCell: UICollectionViewCell {
    var tracker: ViewTracker?

    static let nibName = "CustomCollectionViewCell"
    static let reuseIdentifier = "customCell"

    @IBOutlet weak var cellBackground: UIView!
    @IBOutlet weak var textLabel: UILabel!

    var numberOfTimesTracked : Int = 0 {
        didSet {
            self.textLabel.text = "\(numberOfTimesTracked)"
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        cellBackground.backgroundColor = .red
        layer.borderWidth = 0.5
        layer.borderColor = UIColor.lightGray.cgColor
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        print("Hello")
        tracker?.stop()
        tracker = nil

    }
}

extension CustomCollectionViewCell: ImpressionItem{
    func getUniqueId() -> String {
        return self.textLabel.text!
    }
}

extension CustomCollectionViewCell: TrackableView {
    func thresholdTimeInSeconds() -> Double { // every 2 seconds counts as a view.
        return 2
    }

    func viewDidStayOnViewPortForARound() {
        numberOfTimesTracked += 1 // counts for how long the view stays on screen.
    }

    func precondition() -> Bool {
        let screenRect = UIScreen.main.bounds
        let viewRect = convert(bounds, to: nil)
        let intersection = screenRect.intersection(viewRect)
        return intersection.height == bounds.height && intersection.width == bounds.width
    }
}

Comment: To clarify... you only want to mark a cell (message) as "seen" if the cell has been visible for a minimum length of time?
Comment: @DonMag yes sorry forgot to mention that, I want to mark it as seen after its been visible for minimum 2 seconds, for example you get into facebook u watch a post for 2 seconds it counts as "Seen".
Answer: The approach you probably want to use...
In you posted code, you've created an array of "read posts":
var indexPathsOfCellsTurnedGreen = [IndexPath]() // All the read "posts"

Assuming your real data will have multiple properties, such as:
struct TrackPost {
    var message: String = ""
    var postAuthor: String = ""
    var postDate: Date = Date()
    // ... other stuff
}

add another property to track whether or not it has been "seen":
struct TrackPost {
    var message: String = ""
    var postAuthor: String = ""
    var postDate: Date = Date()
    // ... other stuff

    var hasBeenSeen: Bool = false
}

Move all of your "tracking" code out of the controller, and instead add a Timer to your cell class.
When the cell appears:

if hasBeenSeen for that cell's Data is false

start a 2-second timer
if the timer elapses, the cell has been visible for 2 seconds, so set hasBeenSeen to true (use a closure or protocol / delegate pattern to tell the controller to update the data source) and change the backgroundColor
if the cell is scrolled off-screen before the timer elapses, stop the timer and don't tell the controller anything

if hasBeenSeen is true to begin with, don't start the 2-second timer

Now, your cellForItemAt code will look something like this:
    let p: TrackPost = myData[indexPath.row]

    customCell.authorLabel.text = p.postAuthor
    customCell.dateLabel.text = myDateFormat(p.postDate) // formatted as a string
    customCell.textLabel.text = p.message

    // setting hasBeenSeen in your cell should also set the backgroundColor
    //  and will be used so the cell knows whether or not to start the timer
    customCell.hasBeenSeen = p.hasBeenSeen

    // this will be called by the cell if the timer elapsed
    customCell.wasSeenCallback = { [weak self] in
        guard let self = self else { return }
        self.myData[indexPath.item].hasBeenSeen = true
    }

Comment: Wow Thanks for the reply :) I will try that!
Answer: What about a much simpler approach like:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    for subview in collectionView!.visibleCells {
        if /* check visible percentage */ {
             if !(subview as! TrackableCollectionViewCell).timerRunning {
                  (subview as! TrackableCollectionViewCell).startTimer()
             }
        } else {
             if (subview as! TrackableCollectionViewCell).timerRunning {
                  (subview as! TrackableCollectionViewCell).stopTimer()
             }
        }
    }
}

With a Cell-Class extended by:
class TrackableCollectionViewCell {

    static let minimumVisibleTime: TimeInterval = 2.0

    var timerRunning: Bool = true
    private var timer: Timer = Timer()

    func startTimer() {

        if timerRunning {
            return
        }

        timerRunning = true
        timer = Timer.scheduledTimer(withTimeInterval: minimumVisibleTime, repeats: false) { (_) in
            // mark cell as seen
        }
    }

    func stopTimer() {
         timerRunning = false
         timer.invalidate()
    }

}

Comment: I was thinking about another way, Im using stalkCells() to know if each cell is displayed for more than 70% now I was thinking maybe to use the willDisplay delegate method of CollectionView, then to use  DispatchQueue.main.asyncAfter(deadline: .now() + seconds)  to delay "stalkCells()" so basically after 4 seconds stalkCells will be called.


How to let users access Virtual Machines created in Xenserver

Question: I have created 5 VM in my xenserver, i would like to know if theres any way to have weblogin interface or something which allow our users to connect to a specific VM? or anyway how can i let my users access the virtual machines?
Answer: How would your users access a physical server? SAME THING.
Basically concfigure the VM's to have some sort of network login capacitiy - noone wants to go through the hypervisor on a day to day basis to do work in a VM.
Now, depending what you use - windows or unix - those two totally support network access since many many many many years.
Comment: does it mean i have to go for windows remote desktop since im using windows to access the virtual machine?
Comment: Exactly. No need to invovle the host here.
Comment: another question which might be not related to this topic, i have like 5 VM in my LAN network here and i have 1 static public ip which i forwarded the remote desktop port from my router to the machine running xserver. so in order to connect to these VM's through public wan ip can you recommend a solution? because if i enter the public ip in my remote it will try to connect to xenserver...
Comment: THen ask the question. Dont comment. Ask a new question. And it has to be relevant fo professional administration and show basic knowledge - both this additional question misses.


Reduce DeepLearning4j dependency size of exported jar

Question: In my application, I would like to use Deeplearning4j. Deeplearning4j has over 120mb of dependencies, which is a lot considering my own code is only 0.5mb.

Is it possible to reduce the dependencies required? Would loading an already-trained network allow me to ship my application with a smaller file size?
Answer: There are many ways to reduce the size of your jar depending on what your use case is. We cover this more recently in our docs, but I'll summarize some things to try here:

DL4j is heavily based on javacpp. You can add -Djavacpp.platform=$YOUR_PLATFORM (linux-x86_64, windows-x86_64,..) to your build to reduce the number of native dependencies in there.

If you are using deeplearning4j-core, that includes a lot of extra dependencies you may not need. In this case, you may only need deeplearning4j-nn for the configuration. The same goes for if you are using only samediff, you do not need the dl4j apis. I don't know enough about your use case to confirm what you do and don't need though.

If you are deploying on an embedded platform, we also have the ability to reduce the number of supported operations and data types now as well. This feature is mainly for advanced users right now (involves building from source) but if you think that could also be applicable despite the first 2, please do confirm and I can try to clarify that a bit.
Comment: @Joehot200 It's still possible to limit it to the specific platforms you need to support, for example, you can remove the ones for Android if you don't need those: https://github.com/bytedeco/javacpp-presets/wiki/Reducing-the-Number-of-Dependencies
Comment: Sadly I have to export a one-size-fits-all, so cannot adjust to different operating systems... But thanks! This told me what I needed to know :)


subMenu in Android

Question: I want to attach a menu item on click of which a sub menu opens.
I am able to get the output but my menu item always appears in the overflow menu. With some research I found out that setShowAsAction can be used to make it visible on the Action Bar but I can't set them for subMenu item.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //(this is valid) menu.add("File").setShowAsAction(2);
        SubMenu sm = menu.addSubMenu("File");
        //(can't do this) sm.setShowAsAction(2);
        sm.add("Open");
        sm.add("Close");
        return true;
    }

Answer: Use sm.getItem() to get the actual MenuItem for the submenu. You can then call setShowAsAction() on that.

subMenu in Android


Finding a point having the radius, chord length and another point

Question: Me and a friend have been trying to find a way to get the position of a second point (B on the picture) having the first point (A), the length of the chord (d) and the radius (r).
It must be possible right? We know the solution will be two possible points but since it's a semicircle we also know the x coordinate of B will have to be lower than A and the y coordinate must be always greater than 0.
Think you can help?
Here's a picture to illustrate the example:

Thanks in advance!
Answer: I prefer a trigonometric approach.

Points $A$ and $B$ on an origin-centered circle of radius $r$ can be represented as
$$A := (r \cos\alpha, r \sin\alpha) \qquad B := (r\cos\beta, r\sin\beta)$$
for angles $\alpha$ and $\beta$ as shown in the image.
Now, simply note that $\beta = \alpha - \theta$, where (as shown below) $\theta = 2\;\mathrm{asin}\frac{d}{2r}$, to get the location of $B$.

The formula for $\theta$ follows from the Law of Cosines:
$$d^2 = r^2 + r^2 - 2 r^2 \cos\theta = 2 r^2 ( 1 - \cos\theta) = 4 r^2 \sin^2\frac{\theta}{2} = \left( 2 r \sin\frac{\theta}{2} \right)^2$$
Therefore, $d = \pm 2 r \sin\frac{\theta}{2}$, although we can take the "$\pm$" to be "$+$". This gives $\theta = 2 \;\mathrm{asin}\frac{d}{2r}$, as claimed.
Comment: That did the trick! Thank you!
Answer: Just to give you the formulas @avatar is talking about:
Any point $(x,y)$ on a circle of radius $r$ around the origin satisfies
$$x^2+y^2=r^2$$
And the distance $d$ of two points $(x_i,y_i)$, $i=1,2$ is given by
$$(x_1-x_2)^2+(y_1-y_2)^2=d^2$$
edit:a totally different and maybe more elegant way to do this is to express the angle between A and B as a fuction of r and d using trigononetric fuctions (sorry for being vague, boarding my flight now)
Comment: So we've been trying to solve this using different approaches and this looked the simplest:
$
\begin{cases}x^2_2 + y^2_2 =r^2\\
(x_1-x_2)^2  + (y_1-y_2)^2  = d^2\\\end{cases}
\\
\begin{cases}--------\\
x_1^2 -2x_1x_2 + x_2^2 + y_1^2 -2y_1y_2 + y_2^2  = d^2\\\end{cases}
$

since $x_1^2+y_1^2=r_2^2$ and $x_2^2+y_2^2=r_2^2$

$
\begin{cases}------------\\
-2x_1x_2 -2y_1y_2 + 2r^2  = d^2\\\end{cases}
\\
\begin{cases}x_2 = \sqrt{r^2 - y_2^2}\\
-2x_1\sqrt{r^2 - y_2^2} -2y_1y_2 + 2r^2  = d^2\\\end{cases}
$

but when we kept doing it we've reached a fifth degree polynomial...
Comment: are we missing something? (sorry for the double post but i've reached the maximum amount of chars
Comment: note that in ur last equation everything but $y_2$ is given and can be considered to be a constant. then it is of degree 2
Answer: There are two variables $(a,b)$ the coordinates of B. Since B lies on the circle,it satisfies the equation of the circle. Also,the distance of $B$ from $A$ is $d$.You can apply distance formula to get an equation from this condition.Now you have two variables and two equations from two conditions,you can solve it now yourself.


Having a lot of difficulty understanding encapsulation

Question: I just...am not entirely sure I understand encapsulation. Maybe it might have to do with the fact that I'm still learning programming in a class and haven't made any like..REAL world programs to be used by other people, but I just don't understand what it's trying to accomplish. I understand that its restricting access to some of a class' members and functions. But like..restricting it from who? I've seen several examples where they have a private data member, but they have public get or set methods that allow the data member to be manipulated anyway. So how was anything restricted or hidden?
My book says the following:
"
Encapsulation provides two important advantages:

User code cannot inadvertently corrupt the state of an encapsulated object.
The implementation of an encapsulated class can change over time without requiring changes in user-level code.
"

I guess I'm confused about the words they are using. How, or can someone give me an example, of how user code could possibly corrupt the state of an object?
I know my question is kind of all over the place but so is my mind when it comes to thinking about encapsulation so I'm having a difficulty encapsulating all my thoughts about it (..lol)
Comment: See http://programmers.stackexchange.com/questions/115182/what-defines-an-encapsulation-properly
Comment: Using private vars and get/set functions is so you know for sure that any error in the variables is within your code, if your variables were publicly accessible it may as well be an error on the user of your class's part.
Comment: "...restricting it from who?" - If you design a library, the user of your code could be anyone using this library. Also, in team project the programmers of another team can be users of your team's code interfaces.
Answer: My favorite example of encapsulation is driving a car.
The typical driver knows how to make a car go forward by turning on the ignition, and stepping on the gas pedal. They don't need to know anything about internal engine combustions in order to get to work every morning.
The gas pedal exposes a very simple interface for operating a very complex machine. Meaning, the really complicated internal details are encapsulated from the driver.
Now, in terms of code, say you want to use a Map of some kind, but you don't know how to write generic hash functions for your keys, or how to implement any of the other underlying details.
In Java you can simply use a HashMap, without having to worry about what the standard library is doing underneath. These details are encapsulated from the user.
Comment: +1 I really like the analogy. Also, so with drivers/mechanics tuning and repairing the insides of a car, so with the fact that we sometimes need to go through library implementations to trace bugs and those horrific stuff.
Answer: Let us tackle both points separately.
1. Class invariants
In programming, reasoning is made easier when you have invariants. For example, you may already have heard of loop invariants:
for (size_t i = 0; i < vec.size(); ++i) {
    // something that does not alter i
}

In this loop, 0 <= i < vec.size() is an invariant which guarantees that vec[i] is always a valid expression.
Class can have invariants too, for example if you consider std::string its size() method returns the number of characters in its buffer. Always.
Now, suppose that you write your own string class:
// Invariant: size represents the number of characters in data.
struct String {
    size_t size;
    char* data;
};

It's good to document what you wish was the invariant, but I can perfectly do:
void reset(String& str) {
    delete str.data;
    str.data = 0;
}

and forget to reset str.size, thus violating the invariant.
However, if you tuck away the class members:
// Invariant: size() returns the number of characters accessible via data()
class String {
public:
    size_t size() const { return _size; }
    char const* data() const { return _data; }

    // methods which maintain the invariant
private:
    size_t _size;
    char* _data;
};

now only you can violate the invariant. Thus in case of bug you have less code to audit.
2. Implementation change insulation
The idea behind is that you should be able to switch the internal representation of information without adapting the users of the class. For example:
class Employee {
public:
    std::string const& name() const { return _name; } // Bad

private:
    std::string _name;
}; // class Employee

Now, if I realize that std::string is not an appropriate representation for name (I would need wide characters, for example):
class Employee {
public:
    std::string const& name() const { return _name; } // error!

private:
    std::basic_string<char32_t> _name;
}; // class Employee

I am stuck. I cannot return a std::string const& any longer (I don't have an internal std::string any longer). I could alter the return of name() to make a copy:
std::string Employee::name() const { return encodeUtf8(_name); }

unfortunately it may still break clients:
std::string const& name(Employee const& e) {
    std::string const& n = e.name(); // Bind temporary variable to const&
    return n;                        // Returns reference to local variable!!
}

Whereas if Employee had been designed from the start with std::string name() const we could make the change without issues.
Note: in real-world usage, you have to make external API with insulation in mind, but internal API may perfectly expose data-representation... at the cost of more changes on your plate when a change is made.
Answer: Excellent explanation by @Kepani. I would just like to explain a new statement from http://www.tutorialspoint.com/cplusplus/cpp_data_encapsulation.htm
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse.
So if any outside entity tries to access or change anything in class variables then they unknowingly may harm data contained in it. So in simple terms we basically create a group and limit its usage and access.
Just like car internals can only run a car, your are only asked to drive it and not to go inside it and make the wheels run or use any outside element to move the wheel as they may be out of sync and harm it.
Answer: The point about encapsulation is not so much that "you can't change the private data in any way", but rather that the private data's storage itself is hidden. For example:
class Employee
{
  ...
};

class Company
{
  public:
   std::vector<Employee> employees;
   ...
};

Now, a vector of Employees may very well work for a company with a small number of employees, but if the company keeps growing, it may cause problems because it's slow to search [In REALITY, probably not!]. However, since we have exposed the std::vector<Employee>, we can't alter what type of storage there is inside Company (without risk of breaking something in the rest of the code). If the employees is private, we can change it to any other type that makes sense for the application.
If we instead have:
class Company
{
   private:
     std::vector<Employee> employees;
     ...
};

we can easily change it to:
class Company
{
    private:
      std::map<std::string, Employee> employees;
};

Now, std::map is a "tree", whcih can be searched in log2(n) steps for n elements, where a vector takes (n/2) searches on average - if we have 10000 employes, that's a difference betweeen about 16 steps and 5000 steps to find the right thing. If the company grows to 100000 employes, the vector will take anoter 45000 steps on average, but only another 3 to find the right one in the map.
The whole point is that "We can change the way the data is stored, and have control how it is accessed".
Answer: As an example, suppose we had a very simple string class:
struct String
{
    char * data = nullptr;
    size_t size = 0;

    void resize(size_t new_size) {
        data = realloc(data, new_size);
        size = new_size;
    }
    char & at(size_t i) {
        if (i >= size) throw std::range_error();
        return data[i];
    }
};

We can see that this class has a couple of invariants:

data must point to memory allocated by malloc and friends;
the size member must match the allocated size.

Without encapsulation, it's easy to break the invariants:
String s;
s.size = 42;
s[10] = 'X';        // BOOM! out-of-range access

s.data = "Hello!";
s.resize(3);        // BOOM! tries to reallocate static memory

By making the data members private, we can prevent people from arbitrarily changing them; they can only be changed through the public interface, which we implement carefully to maintain the invariants.
For bonus points, you might consider how to correctly fix the memory leak in my example; but that's somewhat beyond the scope of this question.


For which $q\in\mathbb Q$ is $\sin(\frac\pi2q)$ rational?

Question:
Do there exist rational numbers $q \in (0,1) \cap \mathbb Q$ such that $$\sin\left(\frac{\pi}{2}q\right) \in \mathbb Q\;?$$

Clearly if $q \in \mathbb Z$, yes. But what about the case $0 < q < 1$?
As $\sin(\pi/6) = 1/2$ we have $q = 1/3$ is a solution. Are there any others?
Comment: This is similar to [this question](http://math.stackexchange.com/questions/87756/when-is-sinx-rational). Some of the answers there will bear on this question. In particular, see [Niven's Theorem](http://en.wikipedia.org/wiki/Niven%27s_theorem).
Comment: "Clearly if $q\in\Bbb{Z}$, yes." It is clear because it is a vacuous statement. There are no integers in the open interval $(0,1)$, so there is no $q\in(0,1)\cap\Bbb{Q}$ where $q\in\Bbb{Z}$.
Comment: Yes, I was relaxing the hypothesis in that sentence to make the point that if $q$ is integer then (of course) $\sin(\pi q/2)$ is rational. The intent was to underline the focus of the question to those $q$ in the open interval $(0,1)$.
Answer: The only rationals $r$ such that $\sin(\pi r)$ is rational are those for which $ \sin(\pi r)$ is in $\{-1,-1/2,0,1/2,1\}$.  This is because $2 \sin(\pi r)$ is an algebraic integer, and algebraic integers that are rational are ordinary integers.
Comment: $2 \sin(\pi r) = -i \exp(i\pi r) + i \exp(-i \pi r)$.  $\pm i$ and $\exp(\pm i \pi r)$ are algebraic integers, being roots of unity.  The sum or product of algebraic integers is an algebraic integer.
Comment: Following @robjohn's link above, I've found that this result is called Niven's theorem. I am guessing I should take it that the clue you are giving here is the heart of the proof of Niven. If so, could you elaborate a little more on why $2\sin(\pi r)$ is an algebraic integer?
Answer: $$q=\frac{1}{3}\Rightarrow \sin \left( \frac{\pi}{2} \frac{1}{3}\right) =\frac{1}{2}$$
Comment: Thanks and apologies, I meant to include this one in the question.


Linear algebra: Finding cosine between vectors given inner product space

Question: I've come across a question that wants me to find the cosine of the angle between two vectors within an inner product space. The issue is, the vectors are defined as being $x$ and $x+1$.
The inner product space: $$\langle p , q\rangle = \int_0^1 p(x)q(x) \,dx$$
I assume I use $$\cos(\theta) = \frac{\langle p,q\rangle}{\|p\| \|q\|} $$ but I am unable to find the norms for $p$ and $q$.
I found that $\langle p , q \rangle = 5/6$
Thank you
Answer: For example:
$$||x+1||^2=\int\limits_0^1 (x+1)^2dx=\left.\frac13(x+1)^3\right|_0^1=\frac13(8-1)=\frac73$$
BTW, I get $\;\theta=19.11^\circ\;$
Comment: Thank you for your help. This uses  to get ||p||^2, and from there, you just take the sqrt to find ||p||, right?

Thank you heaps for your help! I'll take another look and see what I can do
Comment: Yes! I figured it out - Thank you so much for your help. I really appreciate it.
Answer: Think about this: what is $\langle p,p\rangle$?
If that doesn't get you on track, consider this: for a normal spatial vector, how does $\vec{x}\cdot\vec{x}$ relate to the norm (a.k.a. magnitude a.k.a. length) of the vector $\vec{x}$?


Using s to estimate $\sigma$ when finding the sample size in confidence interval questions

Question: I am trying to learn sample confidence interval for $\mu$ , in this topic , there is a subtopic which is finding the sample size. I know that if $\sigma$ is given (standard deviation of population) , then $$n= \bigg(\frac{z_{\alpha/2}\sigma}{error}\bigg)^2$$
However , we do not always have $\sigma$ , in this case my book suggest two option such that :

By taking a preliminary sample and using $s$ (standard deviation of the sample) to estimate $\sigma$.

By using $\sigma \sim \frac{\text{Range of population}}{4}$

When i read these options , the latter made sense ,but i could not comprehend how to use the former. What i mean is that how can i use  standard deviation of the sample to estimate standard deviation of population ? If it possible can you explain it with a example ? Thanks in advance..
Comment: Think about this: how can you use the mean within a sample to estimate the mean within the entire population? The principle is the same. See [this answer](https://stats.stackexchange.com/a/11818/28500) and other discussion on that page.
Comment: @EdM I found a information , it says that "if we know
the variance of the population from which we select our sample. Lacking this
information, we could take a preliminary sample of size n ≥ 30 to provide an
estimate of σ. Then, using s as an approximation for σ in given formula, we could
determine approximately how many observations are needed to provide the desired
degree of accuracy." . In here , i accept that if there is a given sample if $n>30$ , then we can use its standard deviation to use in place of $\sigma$. SEE NEXT COMMENT...
Comment: @EdM However , assume that we have only the sample whose size is less than $30$ and has standard deviation $s$ . Then ,will we also use the standard deviation of this sample in place of $\sigma$ again ?
Comment: The problem with a small sample is that the estimate of population variance itself then has a high variance, so your estimate of the variance from the sample might be far from the true value. See [this answer](https://stats.stackexchange.com/a/27980/28500) for the case when the underlying distribution is normal. There is no magical cutoff at a sample size of 30. I don't know that the approximation in the second option is necessarily any better. This is good to understand early on, as it's easy to fall into a trap of estimating sample-size requirements without having a good variance estimate.
Answer: The formula you show is an estimate of how large a sample you need to have a chance of $(1-\alpha)$ to find the sample mean within "error" of the true mean. That depends, as you say, on knowing the actual standard deviation $\sigma$ in the population (or the variance $\sigma^2$).
You can use the sample standard deviation as an estimate of the population standard deviation similarly to how you use the sample mean to estimate the population mean. There are two potential problems, however.
First, the sample standard deviation is a biased estimate of the population standard deviation. It is the square root of an unbiased estimate of the population variance.
Second, the sample standard deviation itself has a wide distribution. For a normal distribution, the variance of the sample variance is:
$$ \frac{2\sigma^4}{n-1},$$
where $\sigma^2$ is the population variance and $n$ is the sample size. There isn't any break at a particular value of $n$; the variance of the sample variance just decreases inversely with $(n-1)$.
To see the relative advantages of the 2 proposed methods for estimating $\sigma$, you can try a simulation. Here's an example in R. I made a population of 1000 normally distributed values having mean of 2 and standard deviation of 1.
set.seed(1234)
normData <- rnorm(1000,mean=2,sd=1)
sd(normData)
# [1] 0.9973377

I then took 1000 samples of size $n=10$ from that population and collected the distribution of the SD estimates based on the 2 methods, sample SD and range/4.
sdDist10 <-NULL
rangeDist10 <- NULL
for(i in 1:1000) {sam <- sample(normData,10,replace=TRUE);
sdDist10<-c(sdDist10,sd(sam));
rangeDist10 <- c(rangeDist10,(max(sam)-min(sam))/4)}

I plotted the distributions of the SD estimates obtained those ways:
plot(density(rangeDist10), col="red", xlab="SD estimate", main="For n = 10", [1]bty="n")
lines(density(sdDist10))
legend("topleft",legend="red, from range\nblack, from SD",bty="n")

As expected with a small sample, the estimates based on the sample SD had a wide distribution but were fairly symmetric about the true value.  The estimates based on the range (in red) tended to be low and with a similarly wide distribution. I don't see that using the second option, based on range, is an improvement at all.
Play with this approach for different values of  sample size $n$. If you repeat the above for 1000 samples of size $n = 100$, the sample SD values have a much narrower distribution  around the peak near SD = 1 while the range-based estimates tend to over-estimate the true SD.
A take-home point is that you can need a surprisingly large sample size just to get a reliable estimate of the variance, an estimate you need to perform power calculations for study design. You can also use this approach to see how frequently your sample mean values at different sample sizes are within a specified "error" of the actual mean.
It's good to learn how to do quick simulations like this. In complex designs, simulations are often the best way to estimate the sample size needed for a study.


A bijection between certain sequences and functions

Question: Let $n$ be a natural number. I let define $S_n$ to be number of all possible final results at a competition where ties are possible. More precisely $S_n$ is the set of all functions $f:[n]\to [n]$ such that if $f$ takes the value $i$ then $\forall j, 1\le j\le i$, it also takes the value $j$. ($S_0=1$). I wish to prove the recurrence $S_n=\sum_{k=1}^n\binom{n}{k}S_{n-k}$.
Now I first choose the $k$ elements mapped to $1$ in $\binom{n}{k}$ ways. Corresponding to the remaining $n-k$ elements I now consider all functions which preserve the criterion. Each such function can be bijectively identified with a sequence of $n-k$ terms so that the elements of the sequence are in $\{2,3\cdots n\}$ and they are all consecutive integers with possible repetitions. I now wish to show that the collection of all such sequences is in bijective correspondence with $S_{n-k}$ to complete the proof. How can I prove this?
Thanks for your time.
Answer: Pick your $k$-element set $K\subseteq[n]$ that is to be sent to $1$. Let $f:[n-k]\to[n-k]$ be arbitrary. There is an order-preserving bijections $\varphi:[n]\setminus K\to[n-k]$, since $|[n]\setminus K|=n-k$. Define
$$\hat f:[n]\to[n]:i\mapsto\begin{cases}
1,&\text{if }i\in K\\
f(\varphi(i))+1,&\text{if }i\in[n]\setminus K\;;
\end{cases}$$
then $\hat f$ has the desired properties, and you need only verify that all result functions that send precisely the set $K$ to $1$ can be obtained uniquely in this way.


Given two angles, exact location of $E$ and $F$ in a square $ABCD$ and diagonal $BD$ intersects $AE$ at $P$. What is the value of $\angle PFC$?

Question:
$ABCD$ is a square. $E$ and $F$ are points on $BC$ and $CD$ such that $\angle EAF$ = 45$^\circ$ and $\angle EAB$ = 15$^\circ$. Diagonal of the square $BD$ intersects $AE$ at the point $P$. Than point $P$ and $C$ are connected. What is the value of $\angle PFC$ in degrees?

This problem appeared in the math-contest of Bangladesh. I couldn't figure it out because I didn't know which segments of the following square should be attached and which new lines should be drawn through for further a easy solution.
I will be very gladful if anyone shows me how to find out $\angle PFC$ or help me learn some better strategy for that or similar problem of mensuration.
Comment: Hint: $\triangle PFC$ is isosceles...
Comment: $PC=PA$ is clear.  $PF=PA$ follows from equal angles $PDA$ and $PDF$ of the concyclic $APFD$.  So answer is $90^\circ-\angle PCB=90^\circ-\angle PAB=75^\circ$.
Comment: Okay. If you please tell me how can I get this, then I will be very pleased.
Answer: Since $$\measuredangle FAP=\measuredangle ADP=45^{\circ},$$ we see that $APFD$ is cyclic,
which says  $FP\perp AE$, which says  $PECF$ is cyclic, which gives $$\measuredangle PFC=\measuredangle AEB=75^{\circ}.$$
Answer: Hint:
$$\angle PAF = \angle EAF = 45^{\circ} = \angle BDC = \angle PDF,$$
so $ADFP$ is cyclic. Thus $PF \perp AE$. Can you go from here?
Comment: Yeah, Obviously. Why not? That was a massive help for me. I wanted to prove that $PFEC$ is a cyclic quadrileteral according to my estimation but I don't know why and what was its reason. You helped me justify my anticipation.


How to rewrite the output of $content inside a pane template?

Question: I am trying to reformat / rewrite the output of pane content inside my panel template.
Here is what I have:
panels-pane--panels-mini--some-name.tpl

Inside this file I have:
print render($content)

I need to break apart the items inside of content. What is the best way to go about doing this?
Answer: Look in your panels module the function template_preprocess_panels_pane() you can use this.
http://www.drupalcontrib.org/api/drupal/contributions%21panels%21panels.module/function/template_preprocess_panels_pane/7
http://www.drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template_preprocess_panels_pane/8


Is it possible to hide lost+found?

Question: Given a partition intended solely for storing music, video and so-on, is it possible to hide the lost+found directory?
Answer: Create a subdirectory in that filesystem and share/symlink that instead of the filesystem root directory.
It's a bad idea to remove the lost+found directory. When recovering, fsck needs an existing multi-sector directory in which to create directory entries for lost files. If there is no lost+found directory, then it has to create one, potentially overwriting data.
Comment: Real bad idea to remove it.  FSCK will recreate, but as said above potentially causing more damage.
Comment: Any sources on that?
Comment: By "sources on that" I assume you mean references? It's not mentioned in any manpages that I can find, but it's mentioned here (thanks, Google): http://aplawrence.com/SCOFAQ/FAQ_scotec1fsck_lostfound.html
Answer: For Gnome2/Mate Nautilus/Caja based desktops, create a file called .hidden in the root folder of the drive.
Edit the contents to read:
lost+found

Nautilus will now hide the lost+found folder if you refresh.  Press 'ctrl-h' to toggle the hidden items visible/invisible.
Comment: @ManuJärvinen What is system folder supposed to mean? As far as the kernel is concerned `lost+found` is an ordinary directory just like any other directory. It is only `fsck` which has a need for this specific directory name. Any other tool treating that name special only does so to match the convention used by `fsck`.
Comment: Too bad this doesn't seem to work for KDE's Dolphin or even Thunar. However, Thunar hides lost+found by default since it's a system folder, it seems
Answer: $ ls --ignore=lost+found

So make that an alias
$ alias ls='ls --ignore=lost+found'

With the updated ls that is part of GNU coreutils 8.15
re: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html
Answer: Nautilus (and Konq?) will interpret a .hidden file in a directory as a list of files to hide. Otherwise, as others have suggested, use XFS or ReiserFS.
Answer: No. But you can delete it (it'll be recreated at the next fsck), or you can use a different file system which doesn't need a lost+found. ext2/3 does.
Comment: Strictly speaking it is only the fsck command, which need the lost+found directory. The file system itself doesn't need it. I couldn't find any mention of the lost+found directory within the file system source code. From the file system's point of view, it is no different from all other directories.
Comment: Yeah, but you could have a script that deletes it after fsck runs. I don't really know what the point of this would be though.
Comment: Really, really bad advice. It is a special directory because http://serverfault.com/a/9909/2101
Answer: At least in Ubuntu just change the owner of the directory to root
sudo chown -R root:root '/media/user/device/lost+found'

that's it.
Comment: works on Thunar, thks
Comment: The best answer
Answer: Lost+Found is where FSCK is going to deposit bits of files that it was able to recover if your file system is damaged. If the directory is currently empty, you are safe to just delete it.
FSCK (I believe) will re-create it if it has anything that needs to be put there.
Not sure why the presence of that directory is problematic for you, though?
Answer: rmdir lost+found

Answer: No. It can't be hidden because under UNIX os's, only files that begin with a period are hidden from a standard view.

Is it possible to hide lost+found?


PAM / LDAP authentication with Ubuntu 10.04

Question: I can't wrap my brain around the new pam.d configuration syntax used in Ubuntu 10.04. How do I setup PAM so that it allows users stored in my LDAP database to login.
I already configured nscd, so id <user> or getent passwd are already listing my LDAP users, but PAM doesn't  work, whether the normal shell login nor su.
Update June, 17th 2010 18:45
LDAP is already working. I can list all accounts by executing getent passwd,
but my PAM configuration is still not working.
The listing below shows my /etc/pam.d/login
#
# The PAM configuration file for the Shadow `login' service
#

# Enforce a minimal delay in case of failure (in microseconds).
# (Replaces the `FAIL_DELAY' setting from login.defs)
# Note that other modules may require another minimal delay. (for example,
# to disable any delay, you should add the nodelay option to pam_unix)
auth       optional   pam_faildelay.so  delay=3000000

# Outputs an issue file prior to each login prompt (Replaces the
# ISSUE_FILE option from login.defs). Uncomment for use
# auth       required   pam_issue.so issue=/etc/issue

# Disallows root logins except on tty's listed in /etc/securetty
# (Replaces the `CONSOLE' setting from login.defs)
# Note that it is included as a "required" module. root will be
# prompted for a password on insecure ttys.
# If you change it to a "requisite" module, make sure this does not leak
# user name information.
auth       required  pam_securetty.so

# Disallows other than root logins when /etc/nologin exists
# (Replaces the `NOLOGINS_FILE' option from login.defs)
auth       requisite  pam_nologin.so

# SELinux needs to be the first session rule. This ensures that any
# lingering context has been cleared. Without out this it is possible
# that a module could execute code in the wrong domain.
# When the module is present, "required" would be sufficient (When SELinux
# is disabled, this returns success.)
session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so close

# This module parses environment configuration file(s)
# and also allows you to use an extended config
# file /etc/security/pam_env.conf.
#
# parsing /etc/environment needs "readenv=1"
session       required   pam_env.so readenv=1
# locale variables are also kept into /etc/default/locale in etch
# reading this file *in addition to /etc/environment* does not hurt
session       required   pam_env.so readenv=1 envfile=/etc/default/locale

# Standard Un*x authentication.
@include common-auth

# This allows certain extra groups to be granted to a user
# based on things like time of day, tty, service, and user.
# Please edit /etc/security/group.conf to fit your needs
# (Replaces the `CONSOLE_GROUPS' option in login.defs)
auth       optional   pam_group.so

# Uncomment and edit /etc/security/time.conf if you need to set
# time restrainst on logins.
# (Replaces the `PORTTIME_CHECKS_ENAB' option from login.defs
# as well as /etc/porttime)
# account    requisite  pam_time.so

# Uncomment and edit /etc/security/access.conf if you need to
# set access limits.
# (Replaces /etc/login.access file)
# account  required       pam_access.so

# Sets up user limits according to /etc/security/limits.conf
# (Replaces the use of /etc/limits in old login)
session    required   pam_limits.so

# Prints the last login info upon succesful login
# (Replaces the `LASTLOG_ENAB' option from login.defs)
session    optional   pam_lastlog.so

# Prints the motd upon succesful login
# (Replaces the `MOTD_FILE' option in login.defs)
session    optional   pam_motd.so

# Prints the status of the user's mailbox upon succesful login
# (Replaces the `MAIL_CHECK_ENAB' option from login.defs).
#
# This also defines the MAIL environment variable
# However, userdel also needs MAIL_DIR and MAIL_FILE variables
# in /etc/login.defs to make sure that removing a user
# also removes the user's mail spool file.
# See comments in /etc/login.defs
session    optional   pam_mail.so standard

# Standard Un*x account and session
@include common-account
@include common-session
@include common-password

# SELinux needs to intervene at login time to ensure that the process
# starts in the proper default security context. Only sessions which are
# intended to run in the user's context should be run after this.
session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so open
# When the module is present, "required" would be sufficient (When SELinux
# is disabled, this returns success.)

The listing below shows my /etc/pam.d/common-auth
#
# /etc/pam.d/common-auth - authentication settings common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of the authentication modules that define
# the central authentication scheme for use on the system
# (e.g., /etc/shadow, LDAP, Kerberos, etc.).  The default is to use the
# traditional Unix authentication mechanisms.
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.

# here are the per-package modules (the "Primary" block)
auth    [success=2 default=ignore]  pam_unix.so nullok_secure
auth    [success=1 default=ignore]  pam_ldap.so use_first_pass
# here's the fallback if no module succeeds
auth    requisite           pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
auth    required            pam_permit.so
# and here are more per-package modules (the "Additional" block)
# end of pam-auth-update config

Comment: Your `common-auth` looks correct. Perhaps the problem is somewhere else? Is there anything in `/var/log/auth.log`? Check some other logs too, such as `syslog`, `messages`, `user.log` and `daemon.log`. Are there any other LDAP-related files you've edited? Did you configure any authentication or access control on the LDAP server?
Answer:
Firstly, you'll need to open up your favourite package manager and install libpam-ldap

Once the packages start being unpacked you'll be hit up for a few questions about:
. IP address/hostname of the LDAP server
. The search base of your LDAP domain     etc...
Now you need to customise PAM to make it use LDAP for authentication:
sudo vi /etc/pam.d/login
you need to add one line above the existing line:

auth    sufficient      pam_ldap.so
      auth    required        pam_unix.so try_first_pass

Or modified the common-auth file
Comment: First of all, thanks, but your suggestion didn't work. Maybe, because I don't know where to insert it exactly. Btw., I updated my question.
Answer: Restore you pam files to the original versions.  Install the libnss-ldap package which will integrate ldap access into pam.  You may also want to install nscd.
Configure your server in /etc/ldap.conf.
Edit /etc/nsswitch.conf adding ldap to the end of the lines for passwd group and shadow.
passwd:         compat ldap
group:          compat ldap
shadow:         compat ldap
Check to see if 'sudo getent shadow' is working for ldap entries.  Check that you can get an authenticated connection using ldap-search from ldap-utils using your /etc/ldap.conf connection data.
Depending on your configuration you will also have to configure ssl values in /etc/ldap.conf.
Comment: I guess I messed up my configuration. I tried again by installing the packages and configuring /etc/nsswitch.conf, and see, it works! Great, thanks a lot.


Install issues via composer

Question: I ran composer global require drush/drush:dev-master. I'm not sure how to  resolvirthis issue as it seems that the package isn't found anymore. Do I have to update somehow?
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - drush/drush dev-master requires codegyre/robo ~1.0.0-beta1 -> satisfiable by codegyre/robo[1.0.0-beta1] but these conflict with your requirements or minimum-stability.

Installation failed, deleting ./composer.json.

Answer: I did a work around without using composer to do the install by doing the following:

make a drush directory in your home folder (~)
git clone https://github.com/drush-ops/drush.git
cd into that directory
./drush --version (it should complain about composer install)
run composer install
./drush --version WORKING!

I'm using ubuntu so initially I did apt-get install drush, but that version is 5. Then I did the following to download the latest into ~/drush
From there I went to my global run folder: /usr/bin and renamed the old drush to drush_old and then did a ln -s ~/drush/drush drush now its on the latest drush!
Answer: The codegyre/robo project has moved to consolidation/Robo, so Drush needs to be updated.
See also: drush/drush dev-master requires codegyre/robo ~1.0.0-beta1.

I've merged a PR into the Drush master branch that fixes the problems Drush was having with Robo. It is still complicated to install the master branch of Drush with Composer. This will get better after the stable release of Robo 1.0.0, or after I implement a fix for this issue. Until then, I recommend against installing Drush master via composer require. Either install Drush 8.x, or, if you need the master branch, use git clone followed by composer install.
Comment: Just did a **composer global require codegyre/robo:~1.0.0-beta1** and now I get an issue with symfony: http://prnt.sc/c3nytf ---- I'm not sure how to go about resolving that now. I then went to your link and as you said just use stable drush 8 and now I'm getting this: http://prntscr.com/c3o8tc --- I dont understand why its so complicated to install drush. It installed fine a few months back and now I'm getting all these dependency problems. thanks Greg!
Comment: In your second screenshot, the problem is that you have not placed Drush in your $PATH. Note the difference between `composer require` (run from a composer-managed Drupal project) and `composer global require` (to install a global Drush). We do not recommend `composer global require` when installing Drush.  If you'd like a global Drush, please see and use https://github.com/consolidation-org/cgr
Comment: Tried installing your cgr... getting a "nothing to install or update" ---> http://prntscr.com/c3t3r3 .... I'm not sure what I'm doing wrong or what am I missing to make this seem so difficult to install.
Comment: i just did a **sudo apt-get install drush** and its working, but its drush version 5. =(
Comment: nvm i got a work around by doing a git clone of your repo. I'm curious to why not suggest a git clone of your repo and then just run it off of that? it just seems so much easier than having to deal with dependencies when doing the install via composer directly.

Install issues via composer


Bloquear ataque javascript e sql-injection na mesma string

Question: Estou a receber dados de um formulário no php via get.
Estou a tratar a informação da seguinte maneira:
$search = mysql_real_escape_string(htmlspecialchars($_GET["t"], ENT_QUOTES, 'UTF-8'));

Com isso pretendo bloquear ataques por javascript e sql-injection.
As dúvidas são:

É a melhor forma de bloquear esses dois tipos de ataques?
htmlspecialchars poderia anular de alguma forma a eficácia da função mysql_real_escape_string?

Já li diversos tópicos sobre esses assuntos, mas cada um diz uma coisa e nem sempre é possível verificar se a informação é confiável ou não.
Comment: http://xkcd.com/327/
Comment: [Sobre sql injection](http://pt.stackoverflow.com/questions/3864/como-prevenir-injecao-de-codigo-sql-no-meu-codigo-php) e [xss](http://pt.stackoverflow.com/questions/10921/ataques-xss-como-ocorre)
Comment: Possível duplicata dessa: http://pt.stackoverflow.com/questions/3864/como-prevenir-injecao-de-codigo-sql-no-meu-codigo-php
Comment: @perdeu a pergunta é diferente, coloquei 2 perguntas no fim que não são respondidas no tópico mencionado.
Comment: @Bacco a pergunta é diferente, coloquei 2 perguntas no fim que não são respondidas no tópico mencionado.
Answer: PDO ou mysqli são melhores para verificação disso. Confira o artigo Evite SQL Injection usando Prepared Statements no PHP.
Outro fator é que mysql_ está depreciado nas versões mais novas do PHP.
Muito importante é na recuperação, em vez de utilizar $_GET ou $_POST, utilize filter_input().
Comment: Bom @Filipe, a segunda automaticamente foi respondida, porque, o uso mysql_real_escape_string seria já inapropriado pelo fator Deprecate do Mysql_ como já tinha respondido no primeiro, isso é um fator de segurança. Agora, é boa prática utilizar a rotina desenvolvida para isso que seria somente mysql_real_escape_string ou mysql_espace_string, eu sempre utilizei assim e nunca tive problema, apesar que hoje utilizo PDO com prepare e o mesmo faz o trabalho de proteção. Um outra coisa seria utilizar **filter_input** em vez de $_GET e $_POST eu edite o post e lá tem o link por favor leia o assunto
Comment: Obrigado pelo seu tempo, fiquei esclarecido.
Comment: Obrigado pelos links, mas coloquei 2 perguntas e só a primeira foi respondida, sabe alguma coisa sobre a segunda? Obrigado.
Answer: Proteger contra XSS e SQL injection ao mesmo tempo pode ser uma tarefa bem complicada e potencialmente com muitos pega ratões que só alguém com perícia em DOM e em SQL pode ter ideia do risco. Contra SQLi, a documentação é farta, porém pensem as seguintes situações aonde javascript pode ser executado:
Propriedades como onload, onclick, onblur (...) permitem executar javascript

URLs podem executar javascript com prefixo "javascript:"

Ola Mundo

Recomendo leitura do documento https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet. Existem centenas de modos de, mesmo ao usar um filtro contra SQLi, salvar no banco de dados uma string que será um problema de XSS quando for visualizada.
O que fazer?
O modo mais simples de ter certeza que evita SQLi e XSS ao mesmo tempo é, além de usar funções nativas e bem conhecidas contra SQLi, e fazer um filtro agressivo. Se um campo somente aceita inteiro, remover tudo que não for número. Se são letras e números, filtrar para apenas isso. E, mais importante, evitar aceitar HTML numa entrada do usuário.
Se realmente tiver que aceitar HTML, deverá ou usar uma biblioteca pronta que remova todas as referências a Javascript do código, ou então fazer uma lista branca de que tags são permitidas e quais propriedades de tags são permitidas, o que não é trivial.