Meu insert não cadastra os dados no mysql

Question: Galera, estou tentando inserir alguns dados no meu bd, eu já fiz essa ação em outros sistemas e sempre deu certo, porém dessa vez não está dando, ele não mostra nenhuma mensagem de erro, ele só não inclui no banco, tentei fazer o insert de outras maneiras porém não funcionou (o código de baixo é o da última tentativa que fiz), dei um echo no sql e ele está certo, ele simplesmente só não adiciona os cadastros no banco, os nomes estão todos corretos, teriam como ajudar? obrigado desde já.
<?php
    include_once "conexao.php";
    //include_once "defines.php";
    //require_once('classes/BD.class.php');
    //BD::conn();

    if(isset($_POST['prox'])){
        $nome = 'Giovani';
        $data = strip_tags(trim(filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING)));
        $sala = '1';
        $computador = 's';
        $projetor = 's';
        $som = 's';
        $microfone = 'n';

        if (empty($data)) {
            echo '
* Atenção, para prosseguir é preciso selecionar uma data. *
';
            }else{
                    $sql = "INSERT INTO `agendamento` (`nome`, `data`, `sala`, `computador`, `projetor`, `som`, `microfone`) VALUES ('$nome', '$data', '$sala', '$computador', '$projetor', '$som', '$microfone');";
                    $qur = mysqli_query($link, $sql);
                    echo $sql;
                }
            }
?>

Comment: Desculpa. Bom, você sabe a versão anterior que voce usava nos bancos e a versão atual ?
Comment: Leia sobre a função [`mysqli_error`](http://php.net/manual/pt_BR/mysqli.error.php)
Comment: No código postado não há erros, reproduzi no meu servidor e funcionou direito. Coloque na pergunta os outros códigos envolvidos na questão. ou seja, conexao.php,  HTML.
Comment: tenho esse código de conexão:
Comment: A versão do banco é a mesma que usava antes
Comment: usei o mysqli_error e ele retornou essa menssagem: incorrect date value: '30/01/2018' for column 'data' at row 1
Answer: Consegui resolver o problema, no meu código estou usando o datepicker, e ele formata a data para o padrão br e meu mysql só tava aceitando o padrão en, já fiz as adaptações e está tudo certo agora.


Como cancelar a quebra de linha do ?

Question: Estou aninhando vários componentes <Text> em seguida, o problema é que no final de cada <Text> o React quebra uma linha.
Sei que se eu fizer dessa forma:
<Text>
  <Text>Oi</Text>
  <Text>Oi</Text>
  <Text>Oi</Text>
</Text>

Ele irá quebrar apenas no final, porém necessito realmente cancelar essa quebra de linha de alguma forma, pois durante meu texto haverá figuras no meio e outros componentes, e esta quebra de linha realmente está atrapalhando toda a formatação. Existe algum props ou algo que posso usar para cancelar a quebra de linha automática?
Comment: Tem como você dar mais informações da continuação do seu código? da parte que você diz ` e esta quebra de linha realmente está atrapalhando toda a formatação`, talvez seja algum outro problema e/ou pode ser resolvido de outra maneira.
Comment: Referente a cancelar a quebra de linha, dei uma pesquisada e não encontrei alguma maneira ou propriedade do text que faça isso.
Answer: Utilizando flexbox:
<View style={{flex:1, flexDirection:'row'}}>
  <Text>abc</Text>
  <Text>123</Text>
</View>

Como cancelar a quebra de linha do ?


Deprecated: mysql_pconnect

Question: Can anybody help me to fix this error? I try with some solutions here but it appear another error in the index.php page. I asked the hosting company to downgrade the version but they don't accept.

Deprecated: mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home2/mohamed/public_html/portal/includes/DBclass.php on line 7

class mysqlQueryClass {
    var $result,$resultNoRows;

    function dbConnect(){
        $dbConnect=mysql_pconnect(_DATA_BASE_HOST_, _DATA_BASE_USER_, _DATA_BASE_BASSWORD_)
        or die(mysql_error());
        mysql_select_db(_DATA_BASE_NAME_)
        or die(mysql_error());
        return $dbConnect;

Thanks in advance
Comment: Don't use `mysql_*` functions. Look into `mysqli` or `PDO` instead. Downgrade PHP to an old unsupported version is a bad idea.
Comment: Did you change the name of that class? You need to do a proper refactoring of your code, not just replace `mysql` to `mysqli`.
Comment: If you don't want use mysqli or PDO, why don't you ignore the deprecate message?
Comment: This is not an error message, this is just a notice.
Comment: _"I try with some solutions here but it appear another error in the index.php page."_ What was the solution you tried and what was the other error message?
Comment: replaced all mysql to mysqli  only replace in the same file DBclass.php
Comment: *"replaced all mysql to mysqli only replace in the same file DBclass.php"* - if you're still including `mysql_` mixed in with `mysqli_` somewhere, those different mysql api's do not intermix. If you are using `mysqli_` somewhere, make sure the syntax is correct and are passing db connection to functions that require it.
Comment: i replaced in DBclass.php all mysql to mysqli  all now but appear now this error   ( Fatal error: Class 'mysqlQueryClass' not found in /home2/mohamed/public_html/portal/index.php on line 11   )   i must change all mysql to mysqli in index.php also ??
Comment: yes only replaced not change anything else i dont know how to change the class
Answer: Upgrade to mysqli or suppress E_DEPRECATED messages:
error_reporting(E_ALL ^ E_DEPRECATED);

Comment: where i pot this code sit   error_reporting(E_ALL ^ E_DEPRECATED);
Comment: After `<?php`. Or, just change your php.ini file with that.
Comment: You can also do it in `.htaccess`: `php_value error_reporting `. Where `` is the value of `E_ALL ^ E_DEPRECATED`.
Comment: not fixed i dont know what can i do . if i can hide this message what can i do sorry sir

Deprecated: mysql_pconnect


Can run pyspark.cmd but not pyspark from command prompt

Question: I am trying to get pyspark setup for windows.  I have java, python, Hadoop, and spark all setup and environmental variables I believe are setup as I've been instructed elsewhere.  In fact, I am able to run this from the command prompt:
pyspark.cmd
And it will load up the pyspark interpreter.  However, I should be able to run pyspark unqualified (without the .cmd), and python importing won't work otherwise.  It does not matter whether I navigate directly to spark\bin or not, because I do have spark\bin added to the PATH already.
.cmd is listed in my PATHEXT variable, so I don't get why the pyspark command by itself doesn't work.
Thanks for any help.
Answer: While I still don't know exactly why, I think the issue somehow stemmed out of how I unzipped the spark tar file.  Within the spark\bin folder, I was unable to run any .cmd programs without the .cmd extension included.  But I could do that in basically any other folder.  I redid the unzip and the problem no longer existed.


Cannot access includeAndroidResource It is private in UnitTestOptions

Question: I was trying Kotlin Gradle Script and Android Testing.
When I try to configure android resource for Testing I get the following error :

Cannot access includeAndroidResource It is private in UnitTestOptions.

What is the proper way to enable using android Resource in Android Unit testing?
Answer: After posting this question, I went back to Android Studio and tried to see what's there for autocomplete.  I pressed Control+Space just after testOptions.unitTests. and boom, there was the option called isIncludeAndroidResources which was kotlin getter in TestOptions class for
private includeAndroidResource

which I then set to true.
Solution :
 testOptions.unitTests.isIncludeAndroidResources = true

Lesson: Try to write a question to explain the problem, sometimes answer is inside your own head.


Número de requisições simultâneas que um servidor PHP suporta

Question: Vamos supor que tenho um servidor com um processador i7 com 4 núcleos/8 threads.
Em uma arquitetura multi-thread, assumindo que se crie uma thread por requisição, apenas será permitido 8 requisições simultâneas, uma vez que o processador possui 8 threads?
Se os servidores PHP são multi-thread, como conseguem responder a milhares de conexões simultâneas?
Comment: Creio que com simultâneas você quer dizer: "clientes acessando ao mesmo tempo". Teoricamente não há limitação, digo, a limitação é seu equipamento. Talvez tenha algum atraso no cliente (os browsers fazem várias tentativas antes de desistir), mas se seu servidor estiver bem configurado consegue atender 8000+ clientes simultâneos.
Comment: Como isso em tempo de depuração exigiria muitas máquinas para se fazer um teste realístico, não se faz isso em ambiente de desenvolvimento, Para se ter uma ideia da real capacidade do servidor terá que colocá-lo online e monitorar seus status. Claro que um desktop comum não vai apresentar o mesmo desempenho de um servidor com 4 Xeon, 128 GB de memória. Mesmo que tenha muitos processadores, há um gargalo na rede (um roteador, um NIC).
Comment: Na prática se precisa atender muitíssimos clientes terá que fazer algum tipo de balanceamento de carga com um roteador inteligente que distribui as conexões por anycast com parâmetro de distância de carga.
Answer: Não fazem. Simultâneo só a quantidade de processadores existentes. Existe uma ilusão de simultaneidade, como ocorre no seu computador agora. Tem centenas ou milhares de processos rodando e parece que tudo está simultâneo, mas não está. Vai havendo troca de execução.
O sistema operacional vai agendando uma thread de cada vez em cada processador existente. Como a troca ocorre muito rápido parece superficialmente que estão executando simultaneamente, mas se fizer um teste básico de tempo verá que não é bem assim.
Estamos falando de processador. Acontece que grande parte das tarefas envolvem entrada e saída, então enquanto está lendo ou escrevendo dados externamente ao processador este fica ocioso então ter várias threads, bem mais que estas 8 pode ser útil já que enquanto uma thread espera o recurso externo responder outra que não está dependendo de recurso externo pode executar, o que ajuda dar a ilusão de simultaneidade.
Na verdade hoje é mais comum aplicações trabalharem assincronamente e não depender tanto assim de threads explícitas para compensar o uso de acessos externos.
De qualquer forma tenho minhas dúvidas se um único servidor consegue atender milhares de requisições "simultâneas" com PHP.
O Node limita à quantidade virtual de CPUs porque ele trabalha assincronamente, não tem porque usar threads em excesso porque o processador é acionado conforme a necessidade, não precisa haver concorrência de recursos de CPU. Ele enfileira as requisições em excesso já que não tem como atender mais que a capacidade do hardware, assim economiza com o gerenciamento e por isso escala muito melhor, fora o fato que o aproveitamento não fica tanto na "sorte" do momento.
O Node ficou conhecido por fazer isto, mas todas tecnologias fazem isto hoje, em geral usam a libuv. Em geral as pessoas não entendem muito do que estão fazendo, elas leem algo e acham que é aquilo que está escrito sem questionar, sem entender o que está ocorrendo ali.
Leia É sempre garantido que uma aplicação com múltiplas threads rode mais rápido que usando uma única thread? para entender melhor.
Coloquei no GitHub para referência futura.
Comment: Apenas adicionando um outro ponto que vale a pena esclarecer. As plataformas que processam milhões ou bilhões de requests não tem apenas um web server, geralmente elas tem N web servers e N load balancers na frente.
Comment: Obrigado. OK, percebi que um processador só pode processar uma thread de cada vez, porque então dizem que o processador possui 8 threads? Então uma arquitetura multi-thread, tal como a utilizada por alguns servidores PHP, essas threads não são as threads do processador, tal como o Júlio Neto disse na resposta dele?
Comment: Existe uma diferença de definição. Existe 1 chip com 4 processadores independentes dentro dele e cada um com capacidade de executar duas linhas de processamentos separadas cada, daí dá a **capacidade de 8 *threads*** realmente simultâneas, todas as outras se interpolarão. Em geral as pessoas usam terminologias mais ou menos certas. *thread* é *thread* não existe *thread* de baixo ou alto nível. *Thread* é um conceito do sistema operacional entregue para as aplicações. Nos *links* explica tudo isto.
Answer: Aplicações não estão limitadas às threads e aos cores dos processadores. Na verdade apenas o sistema operacional tem acesso à essas threads de baixo nível. E os sistemas normalmente possuem API's para que as aplicações possam criar um número virtualmente ilimitado de threads, dividindo o tempo de CPU entre elas.
Comment: @ThiagoLunardi Não necessariamente. Veja como exemplo uma aplicação PHP bem feitinha [como a do guerrilamail](https://github.com/TwixtedChaox/Guerrilla-SMTPd), é um loop só, que atende muitas requisições TCP simultaneas, assincronamente. É uma state machine que gerencia vários sockets, bem robusta por sinal. Assincronismo é algo relativamente simples de se obter com sockets, seja em que linguagem for (independente de ser interpretada).
Comment: Mas isso se tratando de servidores PHP, correto? Estou a estudar NodeJS e pareceu-me que está limitado pelo número de threads do processador, pelo menos fiquei com essa ideia.
Comment: Isso é algo específico do nodejs. Foi uma escolha do projeto o nodejs ser single thread. Assim realmente ele está limitado às threads de baixo nível da máquina. Mas nada impede q exista uma API para o node q crie threads de alto nível como servers de outras linguagens fazem.
Comment: Vale lembrar que, uma aplicação PHP, por ser interpretada, cria-se uma thread da aplicação por requisição. Uma aplicação Node.js é instanciada uma thread que recebe e trata todas as requisições, e para cada requisição, uma sub thread é criada e recebe injeção de servicos já instanciados.


Check if there is a difference between two rows

Question: I have the following table:
column_a column_b column_c column_d column_date
1        test_1   test_1   type_1   11:00
2        test_2   test_2   type_2   11:01
3        test_3   test_6   type_2   11:02
4        test_4   test_4   type_3   11:03
5        test_2   test_6   type_2   11:04
6        test_1   test_2   type_1   11:05

I have to check which row has another value in column_b and column_c filtered by the column_d (type). I must analyze with my sql script only the first two rows ordered by column_date for each type.
If there is a difference between the two rows in one of the columns (column_b, column_c or column_d), I have to print out the value of the first row (otherwise null).
In example above I expect the following result:
column_a column_b column_c column_d column_date
5        test_2   null     type_2   11:04
6        null     test_2   type_1   11:05

I can use T-SQL of the MS SQL Server 2008.
Answer: It is not clear for me what datatype you use for column_date column, but let us assume that it is time one.
 DECLARE @Table TABLE (
        column_a    INT          ,
        column_b    VARCHAR (128),
        column_c    VARCHAR (128),
        column_d    VARCHAR (128),
        column_date [time]         );

    INSERT  INTO @Table
    VALUES
    ('1', 'test_1', 'test_1', 'type_1', '11:00'),
    ('2', 'test_2', 'test_2', 'type_2', '11:01'),
    ('3', 'test_3', 'test_6', 'type_2', '11:02'),
    ('4', 'test_4', 'test_4', 'type_3', '11:03'),
    ('5', 'test_2', 'test_6', 'type_2', '11:04'),
    ('6', 'test_1', 'test_2', 'type_1', '11:05');

    WITH     C
    AS       (SELECT *,
                     ROW_NUMBER() OVER (PARTITION BY column_d ORDER BY column_date DESC) AS RN
              FROM   @Table),
             ToCompare
    AS       (SELECT *
              FROM   c
              WHERE  Rn < 3
                     AND EXISTS (SELECT *
                                 FROM   c AS C2
                                 WHERE  C.column_d = C2.column_d
                                        AND Rn = 2))
    SELECT   T.column_a,
             NULLIF (T.column_b, T2.column_b) AS [column_b],
             NULLIF (T.column_c, T2.column_c) AS [column_c],
             T.column_d,
             T.column_date
    FROM     ToCompare AS T
             INNER JOIN
             ToCompare AS T2
             ON T.column_d = T2.column_d
    WHERE    T.Rn = 1
             AND T2.RN = 2
    ORDER BY T.column_a;


How to catch event on a parent div?

Question: I would like to ask:

How to make the group displays OVER the divs a and b?
I want to catch event mousedown on group even if a user click on a div a or b.

Basically the group should visually cover the two other divs, so when I click inside the are covered by the group, only group div should detect mousedown.
Notes: I cannot change HTML structure.

document.getElementById('group').addEventListener('click', function(event) {
  event.stopPropagation();
  alert('click on: ' + event.target.id);
});
#group {
  position: absolute;
  width: 250px;
  height: 250px;
  background-color: yellow;
  z-index: 2;
  opacity: 0.5;
}

#a {
  position: absolute;
  left: 80px;
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: blue;
  z-index: 0;
}

#b {
  position: absolute;
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: blue;
  z-index: 0;
}

A

B

Comment: I'm unsure what you are asking. If you click on A or B, your event bubbles up (all JavaScript events bubble up). You're saying if you have other elements inside the group you want to detect the click on those as well? Have you tried it and it doesn't work?
Comment: explain your problem a little more
Comment: what if you discard any event click if id is 'group' ?
`if(event.target.id !== 'group') { alert('click on: ' + event.target.id) }`
Comment: Unclear Question :(
Comment: I need to, when i click in the yellow area (the group) always catch the group event. Thanks.
Answer:
Use opacity 0 for the children.
Use event.currentTarget instead of event.target.

With this config children are actually above groups, but are not visible and events are caught by groups elem, not children.

document.getElementById('group').addEventListener('click', function(event) {
  event.stopPropagation();
  alert('click on: ' + event.currentTarget.id);
});
#group {
  position: relative;
  width: 250px;
  height: 250px;
  background-color: yellow;
  z-index: 2;
  opacity: 0.5;
}

#a {
  position: relative;
  left: 80px;
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: blue;
  z-index: 0;
  opacity: 0
}

#b {
  position: relative;
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: blue;
  z-index: 0;
  opacity: 0;
}

A

B

How to catch event on a parent div?


How to show webform as block

Question: In drupal 7 we used to attach a webform to nodes and then we could render them as a block, nowadays in drupal 8 Webform is a dependent entity and is designed and developed on its own. now my question is :

I've created a webform and now I want to place it in a block so user can simply fill it up in front page, How can I show a webform as a Block?
Comment: By default, Webform block will be available in the block layout, once you created the webform, Just place the webform block in the any region. and then configure it and choose the particular webform which you created
Answer: Special thanks to Peacog Web Development for their great tutorial .Here is the tip:

Rather than Drupal 7, Different Block types can be created by admin

so the solution is simple :

Create a new block type using : admin/structure/block/block-content/types
Add a Reference of type Webform to custom block type
remove body if it's inappropriate
modify custom block Manage Display so the form would be rendered as webform
your new Block type is ready

now to add any new webform as block you, you will need to add new block of type Custom Block and refer to your webform, and that's done.
Comment: logeshvaran/eigentor are correct, there is no need to create a custom block type.
Comment: Using this method allowed me to embed this into a node using Entity Embed, which I couldn't do otherwise.
Comment: Downvoting because this answer "reinvents the wheel", duplicating functionality that comes with the Webform module, which contains the `WebformBlock` class.
Answer: logeshvaran is correct: Webform for Drupal 8 already provides a block that can reference a webform.
So no need to create a custom block type.
Comment: Make sure to search for "Webform" when placing the blocks, and then choose the Webform name in the dialog box provided. I've been searching for the name of the webform, that's why I couldn't find the block to place.
Comment: Thank you @Randell!  To expound on his comment.  The Block name is "Webform" and the Category is "Webform".  After you select that block you will be able to choose which webform you want.
Answer: From Drupal 8 admin

Create your webform
Structure => Block Layout => click "Place Block" under your preferred region
Find Webform then => Place Block => under Webform type your webform title and it will find it
Save Block

You are all set
Comment: Thanks @hzak for this straight-forward and step by step answer! Very useful, and quick to follow.
Answer: You can embed a webform programmatically:
<code>$webform = $this->entityTypeManager->getStorage('webform')->load(self::WEBFORM_ID);
$build['content'][] = [
  '#type' => 'webform',
  '#webform' => $webform,
];
</code>

How to show webform as block


admissibility under weighted error loss implies admissibility under square error loss

Question: Show that admissibility of a decision rule under weighted square error loss implies it's admissibility under square error loss.
Weighted Square error loss = $\frac {(d(x) - \theta)^2}{\theta*(1-\theta)}$
Square error loss = $(d(x) - \theta)^2$
I am not sure how to start.
Comment: Consider how the weighting changes the risk functions.  (You will need to assume $0\lt\theta\lt 1$.)
Answer: The general definition of admissibility is as follows:

An estimator $\delta_0$ is inadmissible for the risk function $R(\cdot,\cdot)$ if there exists at least one
  other estimator $\delta_1$ such that$$\forall\theta\quad
  R(\theta,\delta_1)\le R(\theta,\delta_0)$$with strict inequality for
  at least one $\theta$. It is admissible otherwise.

If an estimator $\delta_0$ is not admissible under squared error loss, it thus means there exists at least another estimator $\delta_1$ such that
$$\forall\theta\quad\mathbb{E}_\theta[(\delta_1(X)-\theta)^2]{\le}\mathbb{E}_\theta[(\delta_0(X)-\theta)^2]$$ with strict inequality for at least one $\theta$. Dividing both sides of the inequality by $\theta(1-\theta)$implies$$\forall\theta\quad\frac{\mathbb{E}_\theta[(\delta_1(X)-\theta)^2]}{\theta(1-\theta)}{\le}\frac{\mathbb{E}_\theta[(\delta_0(X)-\theta)^2]}{\theta(1-\theta)}$$ with strict inequality for at least one $\theta$. Hence inadmissibility for the weighted loss.


JS Resize function for div containing a a slideview slideshow and set as a page background

Question: This is for a drpal 7 install.
Is there a way to apply the same function they discuss in this thread
https://stackoverflow.com/questions/10373349/height-and-width-of-background-picture-adapt-to-each-screen-size
to a whole div instead of a single image? For example, I have a drupal 7 install. I'm using skeleton theme. I have been requested by the client to have a full screen images slider as a the background in the homepage. I have given the images a 1680px Image style and calling the block from a custom template file for the front-page with $ block = module_invoke. That's aright but, it obviously doesn't adjust to screen res. If I give the div one of the skeleton's css classes, the whole layout gets messed up.
I'm trying to find an alternative via custom js.
Is that possible to achieve the same behaviour as in the demo in the link, for the slideview block?
Demo- http://so.devilmaycode.it/height-and-width-of-background-picture-adapt-to-each-screen-size/
If so, please indicate how to add the js to the code, where and how. Thank you!
Comment: Have you tried this in css @media screen and (max-width:800px){.....................} add this css in bottom and write css for different resolutions, hope it helps you!
Comment: THank you for the tip. I'll try it and get back to you. Although if you read above, I mentioned adding Skeleton classes that precisely do that, without success. Perhaps writing my own works. Will let you know.
Comment: Thank you Bala, but the css @media did not do what i wanted. Also for some reason it's not resizing. Once it loads with the browser window at a certain size, it stays like that...I'll try with a different question
Answer: Found two options: cycle2 for which the project is still in development stage:
http://drupal.org/sandbox/BenYoung/1832338
(and did not work when following the installation guidelines, since I never got the Cycle2 option in the dropdown and needs jquery 1.7 which apparently causes a lot of trouble)
And one that is actually fully functional
Flexi Slider here http://drupal.org/project/flexslider , for which I found also this great tutorial here http://coldfrontlabs.ca/blog/creating-responsive-image-slider-galleries-adaptive-images-drupal-7.
Strange that they're so well hidden when adaptive design and full width sliders are so requested now...
Now it works as I wished for it to be, except for one thing I will ask a different question for.


Difference between Url.Action and Html.RenderActionLink and Html.RenderAction

Question: Whats the difference between Url.Action and Html.RenderActionLink in asp.net mvc?
Answer: the one that starts with Url only gives you the URL. the Html.RenderActionLink renders the actual HTML for a link


Python Selenium - Select value from drop down menu

Question: I want to select a value from a drop down menu that has several menus inside it

I use the following code:
# CLICK ARROW
driver.find_element(By.CSS_SELECTOR, '#WIN_7_1000000217 > a:nth-child(3)').click()
# 1ST MENU
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.MenuOuter:nth-child(7) > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(6)')))
menu_1 = driver.find_element(By.CSS_SELECTOR, 'div.MenuOuter:nth-child(7) > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(6)')
actions.move_to_element(menu_1).click().perform()
# 2ND MENU
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.MenuOuter:nth-child(11) > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1)')))
menu_2 = driver.find_element(By.CSS_SELECTOR, 'div.MenuOuter:nth-child(9) > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1)')
actions.move_to_element(menu_2).click().perform()
# 3RD MENU
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'tr.MenuTableRow:nth-child(35)')))
menu_3 = driver.find_element(By.CSS_SELECTOR, 'tr.MenuTableRow:nth-child(35)')
actions.move_to_element(menu_3).click().perform()

However I am not able to select the second menu, its CSS_SELECTOR is:

div.MenuOuter:nth-child(9) > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1)

Sometimes it works this way but the problem is that CSS_SELECTOR changes every time the number of the first nth-child, sometimes it's 9, 11 or 12... Is there a way to solve this and locate the element I want?
Html code for the second menu visible in the image:

            IT Support

Html code for ESI - Espirito Santo Informatica and IBM Outsourcing:

                ESI - Espirito Santo Informatica

                IBM Outsourcing

Comment: Need to see HTML to give you proper solution
Comment: Is URL public ?
Comment: Can you do it with text shown in the menu ? Like Select `IBM Outsourcing` based on text... something like `//div[contains(text(), 'IBM Outsourcing')]` - this is just a typical xpath
Comment: Nope, sorry :((
Comment: I added the html code from the second menu visible in the image
Answer: Why not xpath ?
//td[contains(text() , 'IT Support')]

something like this :
# 2ND MENU
actions.move_to_element(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[contains(text() , 'IT Support')]")))).click().perform()

Comment: What is the error when it did not work ? and Are you doing the same with menu 1 and 3 ?
Comment: How are you selecting the Menu 1 ? after click on arrow
Comment: You need to change this line `div.MenuOuter:nth-child(7) > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(6)` write xpath or a reliable css
Comment: Can you share HTML for IBM Outsourcing also ?
Comment: let me have a look, I will get back to you
Comment: Did you try to replace the code for Menu 1 like this : `//td[contains(text(), 'IBM Outsourcing')]`  and use it like this `actions.move_to_element(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[contains(text(), 'IBM Outsourcing')]")))).click().perform()` - Probably you do not even have to click there, Is it just hover ?
Comment: and Selenium is not that much unstable, it could be locator or may be even web application
Comment: How do you interact with Menu 1  when you click on down arrow ? Is it like you just have to hover to `IBM Outsourcing` and then you second menu is visible or you have to click manually on `IBM Outsourcing` and then second menu is visible
Comment: then remove `.click` but keep `.perform()`
Comment: Looks like this one is working!! I will continue testing, but I don't think there is a problem
Comment: Sure, let me know if there is. or May be you can create new ticket as well in future, that will have bit more audience
Comment: You have to determine in Menu 2 do you really have to click or hover manually ?
Comment: and still it's inconsistent  ?
Comment: Probably try some hardcoded delays : `sleep(2)` - Is application under development ?
Comment: We are hovering so we need move_to_element for sure.. then we should  use Explicit wait rest is all upto locators which is still okay. Not sure why it's not consistent.
Comment: yes it could be from application, Is there a way to restart the backend component and test ?
Comment: try to show this inconsistency to your lead or  manager, there's nothing much we can do
Comment: Actually, it worked the first 3 times and then it stopped working... ://
Comment: I added 60 to the Wait and it returns TimeOutException... No, because it's menu 2 that's causing the problem so far
Comment: Yes, I'm selecting menu 1 which makes menu 2 visible
Comment: I replace the 3 lines from my code in the menu 2 section by the code you gave me
Comment: The way I interact with menu 1 works, the CSS_SELECTOR reference never changes opposite of menu 2
Comment: Thank you very much for your support and availability! But this is confusing me because I don't understand what's going on, I didn't change anything and it worked again... Is the use of selenium really that unstable?
Comment: I'm going to try replacing the code for menu 1, but I remove the .click and the .perform?
Comment: I just have to hover if it's me doing it
Comment: No joke, but it works 1 time in 2... When it blocks it's always in menu 2, and it returns TimeoutException
Comment: Manually, I just have to hover. I also took off the .click()
Comment: Unfortunately, yes
Comment: I add time.sleep(20) between each line, didn't solve... I will logout/login every time I get the problem, it's the only solution I see
Comment: As you said, it's possible that the problem comes from the web application
Comment: I'm not the one running the application, it's actually the help desk used between the client and my company


Solr 5 incompatible schema.xml

Question: An error kept showing after installing Search API for solr and after creating a server on drupal. (Solr 5.x)
You are using an incompatible schema.xml configuration file. Please follow the instructions in the handbook for setting up Solr.
Already copied alll configuration files from drupal module into:
/opt/solr/server/solr/my-core/conf
what else to check?
Comment: What OS? Solr on Centos uses `/var/solr/data/[core]` by default.
Comment: Am using Centos 7. So i have to override whats in /var/solr/data/[core] with  drupal config file!?
Answer: On Centos systems Solr assumes your cores will be stored in /var/solr/data/[core-name].
So if your core is named my-core, Solr might already have created the folder /var/solr/data/my-core for you. Simply place the conf directory in that folder, overwriting anything that might already be in conf.
No need to touch any of the other files.
Comment: Great, if you click the check-icon next to question, it will be marked as solved :)
Comment: I have the same error on ubuntu,how can I fix that?
Comment: Read the solr documentation for your os. Learn where it stores the data. I knew this becasue I use centos myself.

Solr 5 incompatible schema.xml


Solving a partial linear differential equation (wave equation) with higher order terms.

Question: I know that the solutions of linear differential equations can be added with any scalar coefficients and it is quite easy to prove too. What I am not able to understand is if we have an equation as follows:-
$$\frac{du}{dt} + a\frac{du}{dx} = \mu_2\frac{d^2u}{dx^2} + \mu_3\frac{d^3u}{dx^3} + \mu_4\frac{d^4u}{dx^4} + ...$$
Can we individually solve the equation for$$\frac{du}{dt} + a\frac{du}{dx} = \mu_2\frac{d^2u}{dx^2}$$ and $$\frac{du}{dt} + a\frac{du}{dx} = \mu_3\frac{d^3u}{dx^3}$$ and so on and simply add the solutions due to each of these.
I have encountered this situation while solving discretised wave equation but I feel that splitting the RHS might change the solution completely. Kindly tell me whether the approach is correct or not? If yes, then why and if no, then also why?
Answer: No, you can't. If $u$ solves the first equation and $v$ the second, then
$$
\frac{\partial}{\partial t}(u+v)+a\,\frac{\partial}{\partial x}(u+v)=\mu_2\,\frac{\partial^2u}{\partial x^2}+\mu_3\,\frac{\partial^3v}{\partial x^3},
$$
and there is no reason to expect that the right hand side equals
$$
\mu_2\,\frac{\partial^2(u+v)}{\partial x^2}+\mu_3\,\frac{\partial^3(u+v)}{\partial x^3}.
$$
Answer: You can use the separation of variables: $u(x,t)=f(x)g(t)$
$$a\frac{f'}{f}-\mu_2\frac{f''}{f}-\mu_3\frac{f'''}{f}-\mu_4\frac{f''''}{f} = -\frac{g'}{g} = \lambda$$
$g(t)=e^{-\lambda t}$
The roots of the equation $\quad \mu_4r^4+\mu_3r^3+\mu_2r^2-ar+\lambda =0\quad$ which are functions of $\lambda$ are: $\quad r_1(\lambda)\:,\: r_2(\lambda)\:,\: r_3(\lambda)\:,\: r_4(\lambda)$
$$f(x)g(t)=e^{-\lambda t} \left( c_1(\lambda)x^{r_1(\lambda)x} + c_2(\lambda)x^{r_2(\lambda)x} + c_3(\lambda)x^{r_3(\lambda)x} + c_4(\lambda)x^{r_4(\lambda)x} \right)$$
where $\quad c_1(\lambda)\:,\:c_2(\lambda)\:,\:c_3(\lambda)\:,\:c_4(\lambda)\quad$ are any functions of $\lambda$, at least four times derivable.
Solution on discret form :
$$u(x,t)=\sum_{\text{any }\lambda}e^{-\lambda t} \left( c_1(\lambda)x^{r_1(\lambda)x} + c_2(\lambda)x^{r_2(\lambda)x} + c_3(\lambda)x^{r_3(\lambda)x} + c_4(\lambda)x^{r_4(\lambda)x} \right)$$
Solution on integral form :
$$u(x,t)=\int e^{-\lambda t} \left( c_1(\lambda)x^{r_1(\lambda)x} + c_2(\lambda)x^{r_2(\lambda)x} + c_3(\lambda)x^{r_3(\lambda)x} + c_4(\lambda)x^{r_4(\lambda)x} \right)d\lambda$$
For complex $\lambda$ and/or if they are complex roots among $\quad r_1(\lambda)\:,\: r_2(\lambda)\:,\: r_3(\lambda)\:,\: r_4(\lambda)$ there will be sinusoidal terms among the terms constituing the general solution.


Twitter Bootstrap - Responsive affix

Question: I'm using Twitter Bootstrap and I have the following:

            <form>

            </form>

Bootstrap is correctly applying the affix effect on
 and it stays still when I scroll down the page. However, once I resize the page to mobile dimensions and bootstrap responsive effects take place (navbar collapsing/objects aligning nicely under each other), the affixed
 is now on top of other elements of the page and it gets messy. This is happening because .affix has position: fixed which explains it pretty well.
Now I went to Bootstrap's website and resized the page to mobile dimensions, the affixed element (
 in their case) starts flowing nicely with the page, taking its natural place without going on top of other elements. I have also noticed that once that happens, the class is changed from affix to affix-top.
I'm not sure if this is their customization or if it's part of the framework, because the framework is apparently not behaving the same way. Can anyone elaborate on this? I need to have the same behavior on my
 where if the page gets resized to mobile dimensions the affixed element takes its natural place.
Edit: My observation is a bit flawed. I noticed that the element on their page initially has affix-top and once I scroll below data-top-offset it changes to affix. It still doesn't explain why my
 won't render like their
 when resized.
Comment: Interesting question, I'm having similar problems myself. In my case, the affixed sidebar gets wider and overlaps the content. I think generally there is a lack of documentation of this new feature.
Comment: @markus-tharkun I think my answer may address your issue as well (`width: auto;`).
Answer: Bootstrap uses an extra CSS file for their docs that overrides the default behavior of some elements.
Specifically, on line 917, they change the position of the affixed sidebar (as part of a media query for <767px width) to static:
.bs-docs-sidenav.affix {
  position: static;
  width: auto;
  top: 0;
}

They have several additional custom styles applied to the affixed sidebar; you can view them by using Chrome Web Inspector/Firebug on a phone-sized window.
Comment: I'm wondering why bootstrap doesn't apply the necessary changes, if the affix only works with them. Maybe they're too context dependent.
Comment: @Sara You shouldn't check in the issue tracker since it isn't an issue. It is the intended and documented behavior. "The affix plugin toggles between three classes, each representing a particular state: .affix, .affix-top, and .affix-bottom. You must provide the styles for these classes yourself (independent of this plugin) to handle the actual positions." http://getbootstrap.com/javascript/#affix-usage (However this post was back in 2012 so maybe the documentation has been updated)
Comment: I agree, it likely is too context dependent. I was unable to find any discussion on the subject on their [issue tracker](https://github.com/twitter/bootstrap/issues).
Answer: HTML Don't affix the span3 (or span4 etc) DIV but a child of it; in my case I affixed #sidebar. Also you don't have to add .affix class or data-offset-top="XXX" to this div. The following Javascript will do the trick.

some content

CSS (the below code doesn't exist on bootstrap.css, I copied it from http://twitter.github.io/bootstrap/assets/css/docs.css)
.affix-bottom {
    position: absolute;
    top: auto;
    bottom: 400px;
}

Javacript the following js will change class of #sidebar from .affix to .affix-bottom according to how much page is scrolled
   $('#sidebar').affix({
      offset: {
        bottom: 450
      }
   });

Indeed on small resolutions #sidebar will overlap other elements. To solve this use bootstrap's media queries http://twitter.github.io/bootstrap/scaffolding.html#responsive
As Sara previously pointed out, you can use something like..
@media(max-width:767px){
   .affix {
     position: static;
     width: auto;
     top: 0;
    }
}

..so that you make the #sidebar behave.
Hope this helps somebody!
Answer: I had the same issue, and my solution was to remove the affix behavior for smaller screen sizes. For example, to remove it for sizes below 1199 pixels:
#map {

  @media (min-width: 1199px) {
    &.affix-top {
    }

    &.affix {
      position: fixed;
      top: 20px;
      bottom: 100px;
    }

    &.affix-bottom {
    }
  }
}

Twitter Bootstrap - Responsive affix


Fazer uma contagem no banco Postgresql

Question: Bom dia .
Queria fazer um select em meu banco e retornasse a quantidade de cadastrados .
Exemplo:
tb_cliente;
coluna: dt_cadastro;
na coluna dt_cadastro tenho isso:
2000-01-20
2001-10-05
1990-11-09
1990-07-16
1990-08-10

Eu queria fazer um select assim:
SELECT dt_cadastro, count(dt_cadastro)
FROM tb_cliente
WHERE dt_cadastro < 2000
GROUP BY dt_cadastro

Ou seja, quero saber quantos são menores que 2000 e não estou conseguindo.
Seguindo a sugestão do @Motta, usei isso:
SELECT dt_cadastro , count(dt_cadastro )
FROM tb_cliente
WHERE  Extract(year from dt_cadastro ) = Extract(year from '1990-12-31'::DATE)
GROUP BY dt_nasc

Só que o resultado foi:
"1990-01-01";1
"1990-08-02";1
"1990-08-08";1

Eu precisava que aparecesse o valor 3, é possível?
Comment: WHERE extract(year from dt_cadastro) < 2000    https://www.postgresql.org/docs/9.6/static/functions-datetime.html
Comment: @Motta vou editar minha pergunta acrescentado sua sugestão.
Comment: Tenta assim `SELECT count(dt_cadastro )
FROM tb_cliente
WHERE  Extract(year from dt_cadastro ) = Extract(year from '1990-12-31'::DATE)
GROUP BY dt_nasc`
Comment: @R.Santos não deu... apareceu 1
1
1
Comment: Altera o group by para `Group by dt_cadastro` vê o que da
Comment: @Vilma Deu certo?
Comment: @R.Santos tb não. Consegui usando isso: SELECT COUNT(*) FROM tb_cliente WHERE EXTRACT(YEAR FROM dt_cadastro) = 1980;    Agora vou ver como usar isso com o criteria do Hibernate.
Comment: @Vilma Tenta assim então `select count(*) from tb_cliente where dt_cadastro < '1999-12-31'` Testei aqui no meu banco de dados e deu certinho, se der certo só avisa
Comment: @R.Santos, não deu. Estou usando, como disse anteriormente esse: SELECT COUNT(*) FROM tb_cliente WHERE EXTRACT(YEAR FROM dt_cadastro) = 1980;  e está funcionando do jeito que quero. Vou apenas converter isso para o criteria do hibernate.
Comment: Estranho, no meu banco de dados PostgreSQL deu certo, trazendo apenas o valor de `Count`, mas se deu certo assim melhor
Answer: A solução na sua pergunta está correta, porém no SELECT você deve colocar somente as opções que você quer "ver", veja o SQL abaixo se é o que você realmente precisa:
SELECT COUNT(dt_cadastro) -- no select vai somente a informação que você quer ver
  FROM tb_cliente
 WHERE EXTRACT(YEAR FROM dt_cadastro) = EXTRACT(YEAR FROM '1990-12-31'::DATE)
 GROUP BY dt_nasc

Answer: Solução encontrada:

SELECT COUNT(*) FROM tb_cliente WHERE EXTRACT(YEAR FROM dt_cadastro) =
  1980;

Fazer uma contagem no banco Postgresql


How to convert date from one format to another golang

Question: I am converting a date into unix timestamp and fetching the date using split as follows
tm := time.Unix(1470009600, 0).UTC()
dateString := strings.Split(tm.String(), " ")

The output of dateString is 2016-07-15 i.e. YYYY-MM-DD format. How can I convert this into DD-MMM-YY format? eg: 15-Jul-16?
Answer: Use Format method with the appropriate format:
fmt.Println(tm.Format("02-Jan-06")) // Prints "01-Aug-16".

Playground: https://play.golang.org/p/uYDYzPwnbJ.


Como executar mais rápido um código que calcula a quantidade de dígitos do fatorial de um número?

Question: O código deve imprimir quantos dígitos tem o fatorial de N.
Estou tentando realizar um desafio simples de fatorial no site URI e quando submeto o código a resposta é sempre "Time limit exceeded", o limite é 1.00s e está dando 2.00s. Já pesquisei sobre o problema e tentei modificar o código para ficar mais rápido, porém o erro se repete. Segue os códigos que submeti:
N = int(input())
for i in range(1, N):
  N = (i * N)
print(len(str(N)))

Este também:
import math
N = input()
print(len(str(math.factorial(int(N)))))

Tentei usar o stdout.write mas deu "Presentation Error" apesar de ter executado também em 2.00s
import math
from sys import stdin, stdout
N = int(input())
for i in range(1, N):
  N = N * i
  stdout.flush()
N = len(str(N))
stdout.write(str(N))

import math
from sys import stdin, stdout
N = int(input())
for i in range(1, N):
  N = N * i
  stdout.flush()
N = len(str(math.factorial(N)))
stdout.write(str(N))

Gostaria de dicas de qual caminho seguir para melhor o tempo de execução e por que estas não deram certo.
Comment: Você mencionou o tempo gasto, mas não mencionou para qual valor de `N` esse tempo foi calculado. Quais os valores de `N` que você usou nos seus testes ?
Comment: @Lacobus Esse é um desafio do URI. Normalmente, o URI faz testes com um monte de entradas diferentes, e muitas delas são secretas para evitar que os algoritmos sejam desenvolvidos de forma a tentar burlá-las. Muitas das entradas que tipicamente explodem algoritmos feitos por iniciantes são coisas monstruosas e/ou números astronômicos.
Comment: Eu editei a pergunta, os casos de testes são para 0 < N <= 10^8
Comment: Vey, pergunta veya e n deve precisar mais, mas `n! = Gamma(n+1)` e `Digits(i) = floor(log10(i))+1 = floor(log10(exp(1))*ln(i))+1 ~ floor(0.43429448190325182765*ln(i))+1`, portanto `Digits(n!) ~ floor(0.43429448190325182765*ln( Gamma(n+1) ))+1`. Função em python que calcula `ln(Gamma())` é `scipy.special.gammaln`.
Comment: Ou seja, simplesmente da import de `math` e `scipy.special` e usa a expressão `math.floor( 1+0.43429448190325182765*scipy.special.gammaln(N+1) )` ou mesmo (pra não precisar calcular a constante) `math.floor( 1+math.log10( math.exp(1) )*scipy.special.gammaln(N+1) )`. É cálculo bem rápido.
Answer: O problema é que o fatorial cresce muito rápido, e em pouco tempo você estará multiplicando números enormes, o que é bem demorado. Só para ter uma ideia, o fatorial de 108 (que é o limite máximo que você indicou) é um número com mais de 750 milhões de dígitos. Manipular números dessa grandeza não tem como ser rápido...
Então uma alternativa é calcular a quantidade de dígitos do fatorial, mas sem precisar calcular o valor do fatorial.
Uma forma de obter a quantidade de dígitos de um número é calcular o logaritmo na base 10, arredondar para baixo e somar 1.
Outro detalhe é que o log10(a * b) é igual a log10(a) + log10(b).
E como o fatorial de N é a multiplicação de todos os números inteiros entre 1 e N, podemos calcular o log10(N!) somando os logs de todos os números entre 1 e N. Ou seja:

log10(N!) é o mesmo que log10(1 * 2 * 3 * ... * N)
que por sua vez é o mesmo que log10(1) + log10(2) + log10(3) + ... + log10(N)

Então basta somar os logs de todos os números de 1 a N, arredondar para baixo e somar 1, para obter a quantidade de dígitos de N! (sem precisar calcular o valor do fatorial).
Ficaria assim:
from math import floor, log10

n = int(input())

res = 0
for i in range(1, n + 1):
  res += log10(i)

print(floor(res) + 1)

Ou ainda:
print(floor(sum(map(log10, range(1, n + 1)))) + 1)

Não testei no URI online, mas fiz um pequeno teste no qual as duas opções acima se mostraram bem mais rápidas que calcular o fatorial:
from math import floor, log10, factorial
from timeit import repeat

def log(n):
  res = 0
  for i in range(1, n + 1):
    res += log10(i)

  return floor(res) + 1

def log2(n):
  return floor(sum(map(log10, range(1, n + 1)))) + 1

def fact(n):
  return floor(log10(factorial(n))) + 1

n = 200000
x = 1
r = 3
print (repeat ('log(n)', repeat=r, number=x, globals=globals()))
print (repeat ('log2(n)', repeat=r, number=x, globals=globals()))
print (repeat ('fact(n)', repeat=r, number=x, globals=globals()))

E quanto maior o N, maior a diferença entre as abordagens.
E faz sentido. Ao calcular o fatorial, você está multiplicando números cada vez maiores, enquanto que no método dos logaritmos estamos somando números pequenos (tudo bem que temos que calcular o logaritmo de todos os números, mas ainda sim compensa e é mais rápido).
Comment: Se eu não tivesse lido a sua resposta eu teria respondido errado. Obrigado.
Answer: Você pode usar a fórmula de Kamenetsky para se calcular a quantidade de digitos contidos no fatorial de N, veja só:
def kamenetsky(n):
    if n < 0:
        return 0
    if n <= 1:
        return 1
    x = (n * log10(n / e)) + (log10(2 * pi * n) / 2.0)
    return floor(x) + 1

Para efeito de comparação dos algoritmos testados, sugiro a implementação de uma função capaz de mensurar o tempo de processamento gasto por cada um deles:
from timeit import default_timer

def teste( func, n, cont=1000 ):
    inicio = default_timer()
    for i in range(cont):
        func(n)
    fim = default_timer()
    total = fim - inicio
    return (total / cont) * (10**6) # Tempo em microsegundos

Testando:
from math import log10, floor, factorial, pi, e
from timeit import default_timer

def teste( func, n, cont=1000 ):
    inicio = default_timer()
    for i in range(cont):
        func(n)
    fim = default_timer()
    total = fim - inicio
    return (total / cont) * (10**6)

def f1(n):
    for i in range(1, n):
        n = i * n
    return len(str(n))

def f2(n):
    n = factorial(n)
    return len(str(n))

def f3(n):
    if n < 0:
        return 0
    if n <= 1:
        return 1
    x = (n * log10(n / e) + log10(2 * pi * n) / 2.0)
    return floor(x) + 1

N = 100
print('f1(): {:.3f} uS'.format(teste(f1, N)))
print('f2(): {:.3f} uS'.format(teste(f2, N)))
print('f3(): {:.3f} uS'.format(teste(f3, N)))

Saída:
f1(): 7.629 uS
f2(): 1.796 uS
f3(): 0.678 uS

Answer: Esta questão se refere ao problema de número "3096", cujo título é "overflow", disponibilizado por URI Online Judge (maratona online de programação).
Veja aqui a íntegra do enunciado.
A questão enfatiza que, em muitos casos onde é necessário calcular o fatorial de um número, cujo resultado possui um número muito grande de algarismos, possivelmente pode resultar em um overflow.
Observe que a questão diz que o programa deve suportar valores N, tais que,  1<= N <= 10^8, isto é, deve suportar valores entre 1 e 100000000. Agora, imagine o quanto de recursos computacionais um programa usaria se tivesse de calcular o fatorial de 100000000?
Pra começar, o número total de dígitos de 100000000! é 756570557. Para melhorar a legibilidade podemos dividir em milhares e deixa-lo da seguinte forma 756.570.557,ou seja, o número total de dígitos resultante do fatorial de 100.000.000 é setecentos e cinquenta e seis milhões, quinhentos e setenta mil, quinhentos e cinquenta e sete.
Como é muito demorado se obter o valor correto para fatoriais de grandes valores, o problema nos pede para calcular apenas o número de dígitos do possível fatorial.
Na matemática, podemos sim, calcular o número de dígitos do resultado do fatorial sem mesmo ter calculado o fatorial desse número. Para isso basta utilizar a fórmula de Kamenetsky.
Para implementarmos esta fórmula corretamente na questão do Uri, com todas as restrições que nos é enfatizada, devemos escrever o seguinte código...
from math import log10, e, pi, floor

n = int(input())

num_digitos = floor((n * log10(n / e)) + (log10(2 * pi * n) / 2.0)) + 1
print('{}'.format(num_digitos))

Veja aqui o funcionamento do algoritmo.
Observe que, quando executamos este programa, a tela do console fica limpa, aguardando a digitação do valor de N. Após digitarmos o valor de N e, em seguida, pressionarmos Enter, o programa conclui a tarefa.
Este código já foi testado, submetido e devidamente aprovado, na maratona que me referir no início do poste, sob linguagem de programação Python 3.
Só para constar, este programa levou apenas 0.028 s para ser executado no site URI.
Answer: Você pode computar o fatorial de um número usando a Função Gamma de Ramanujan que é semelhante ao Gamma de Stirling, porém é mais precisa:

Função Gamma ou Γ é a extensão da função factorial para o conjunto dos números reais e complexos. A função Gamma é definida para todos os complexos exceto os inteiros negativos.
Como o domínio estabelecido pelo AP [0, 10⁸⁰] é de extensão maior que sys.float_info.max usei a biblioteca Mpmath que é uma biblioteca Python para aritmética de ponto flutuante de precisão arbitrária.
A implementação para computar o a quantidade de dígitos de um fatorial fica assim:
#No comentário foi definido o domínio [0, 10 ^ 80] então usei mpmath
from mpmath import log10, pi, e, sqrt

def gamma(x):
  return int(log10(sqrt(pi)*(x/e)**x * (((8*x + 4)*x + 1)*x + 1/30.)**(1./6.))) + 1

Teste no Repl.it: https://repl.it/repls/RelievedJaggedLogins
Answer: Manda a pergunta se esse código não lhe ajudar.
num = int(input('Numero: '))
for i in range(1, num):
  num = i * num
#Mostrando o fatorial do numero digitado
print(num)
#Essa varivel converte o valor int para string
converte = str(num)
#Aqui ele mostra o tamanho da string
print(len(converte))

Comment: É o primeiro que testei, só que com nomes de variáveis diferentes.


How to tell rsync do not check permissions

Question: I have two directories with same PHP application in every of them. I want to execute rsync -rvz from one, source directory to another, destination, so rsync will copy changed files only. Problem is that files in the source directory has 755 permissions, by mistake. Permissions in destination are fine.
How can I tell to rsync ignore permission checkings and check by size only?
Thanks.
Answer: If you supply the -a flag -p is automatically included. If you specify --no-p all of the other options from -a remain intact.
Answer: As long as you don't supply the -p flag permissions shouldn't be changed. If you're still not getting the permissions you expect make sure perms is off and use --chmod=ugo=rwX
For reference:
http://linux.die.net/man/1/rsync
 -r, --recursive             recurse into directories
 -v, --verbose               increase verbosity
 -z, --compress              compress file data during the transfer
 -n, --dry-run               perform a trial run with no changes made

 -p, --perms                 preserve permissions
 -E, --executability         preserve executability
     --chmod=CHMOD           affect file and/or directory permissions

-p, --perms This option causes the receiving rsync to set the destination permissions to be the same as the source permissions. (See
  also the --chmod option for a way to modify what rsync considers to be
  the source permissions.)

The man page goes on to say:

In summary: to give destination files (both old and new) the source
  permissions, use --perms. To give new files the destination-default
  permissions (while leaving existing files unchanged), make sure that
  the --perms option is off and use --chmod=ugo=rwX (which ensures that
  all non-masked bits get enabled).

Side-note: If possible it might make more sense for your developer to be pushing their changes back into the repo, and have all servers use a code repo, rather then use rsync to ship files form one server to the other.
Comment: The first sentence in bold is not quite right (or at least it is confusing) because the typically recommended flag -a implies -p, as stated by the other answers
Answer: Most options can be turned off by simply adding the --no- prefix to those options.
Example:
rsync -avz --no-perms --no-owner --no-group /local-dir/ my-server:/remote-dir/

This will disable syncing permissions, ownership, and groups.
Comment: -a is just a set of -rlptgoD; disabling permissions, groups, ownership, plus we don't care about symlinks and devices most of the time, leaves us with just -rt
Comment: @dimavs You are correct. The point however is that sometimes I don't want to go finding out exactly what a flag such as `-a` means on my exact platform (especially when appropriate man pages for that platform is scarce [think Android, home printer, or router]). Maybe I just want sane defaults for that platform with some specific option removed.
Answer: I may be mistaken but without the -p it shouldnt change the permissions. (also -a which is archive would preserve it, but you're not using that either obviously)
Comment: yes, I think so too. But when I execute rsync with "-n" option I see so many files. I concrete: copy of application is from one of developers. I want to sync his code with a state of repo. So I think to rsync only changed files is the best way. After this I'll add them into git. That's why i'm surprised to watch some images and skins. Okay, thanks.


Conditional Probability Problem, Probability of Pulling A Club after Red Card

Question: I am currently learning about conditional probability from "The Book of R" by Tilman Davies and I'm having trouble understanding a conditional probability problem. The problem is as follows:
You randomly draw a card, and after replacing it, you draw another. Let A be the event that the card is a club; let B be the event that the card is red. What is Pr(A|B)? That is, what is the probability the second card is a club, given the first one was a red card? Are the two events independent?
This assumes your standard 52 card deck. I understand that Pr(B) = 26/52, however where I get stuck is when the question asks about clubs which are black and not red. This means that it is impossible to pull a club out of the new sample space (now 26) because clubs are black and not red. The answer key to the book says the final value is 13/52 but I have absolutely no idea how that conclusion was reached. I have always struggled with understanding probability so any help anyone could provide I would greatly appreciate.
Comment: What makes you think the sample space has been reduced to only red cards?
Comment: I thought that was what was the word "given" always implied in a conditional probability word problem, or that's how I interpreted it at least.
Comment: As Glen_b pointed out, there is some poor wording in the second sentence of the problem, which I missed at first and might have thrown you off. However, it seems that A is meant to be the event "The first card drawn is a club" while B is the event "The second card drawn is red". So yes, you are _given_ the fact that A occurred (i.e. the first card was indeed a club), but since this first card was put back in the deck, this tells you nothing about the probability of the second card being red.
Comment: Here's my question. Since we know the first event occurred, shouldn't it limit the overall sample space size to the number of possible outcomes for that first event (in this case 26 for red cards)?  That's how I interpreted and obviously I'm wrong but to be honest I have no idea *why* I'm wrong. And why would the sample space be reduced when lets just say we were asking for black cards for the club suit and not red? This is beyond confusing and why I've always had problems with probability. It's not that I hate it, it just sometimes makes no sense at all.
Comment: Here is a thought experiment for you.  Suppose that instead of replacing the first card in the deck and drawing again, you were to take a different (shuffled) deck and draw the second card from it.  (1) Intuitively, wouldn't you consider separate draws from separate decks to be statistically independent? Could you demonstrate that they are independent?  (2) How, if at all, would using a second deck change the probabilities in the question?
Answer: Wow, that's poor notation$^\dagger$ they have in the question; it doesn't distinguish which draw the events apply to properly.
Before you draw any cards you have 26 red cards, 13 clubs (and 13 spades). After the first draw is red, they say you replace it (presumably shuffling again), so you still have 26 red cards, 13 clubs and 13 spades. At the second draw there are 52 cards, of which 13 are clubs; the chance of drawing a club is $\frac{13}{52}$. (Since the first-drawn card was replaced it changes nothing; you're exactly in the situation you started with)
$\dagger$ A better notation would be: Let $R_i$ be the event "a red card was drawn at the $i$th card draw" and let $C_i$ be the event "a club was drawn at the $i$th card draw; then the problem is "What is $P(C_2|R_1)$?" which is useful to distinguish from various other possible questions. Ambiguous notation is a recipe for confusion.

In reply to comment:
The actual sample space for two draws is the $52\times 52$-element set consisting of all possible pairs of cards from $(A♡,A♡)$ to $(K♠,K♠)$. When you draw a red card on the first draw, you restrict attention to the $26\times 52$ set that has only red cards on the first draw.
Given that, the events with a club on the second draw are the $26 \times 13$ cases that have a red on the first draw and a club on the second draw, and the conditional probability is $\frac{26\times 13}{26\times 52}$. Note that the first draw simply cancels out of numerator and denominator, because the two draws are independent; you can simply ignore it, because it contributes no information.
[Notation that ignores that there are two draws encourages you to make the error of thinking the sample space only has 52 elements.]
Comment: Ok, I still really don't understand. From how I learned conditional probability when an event is _given_ to occur I though this limited the number of samples you have. I understand that overall the card being put back brings the total sample space S size back to 52, but wouldn't the final probability be 13/26 due to the fact that red occurred and that sub-sample space has 26 possible outcomes? This is why I've always had trouble with probability because these explanations are about as conceptually clear as mud to be honest.
Comment: See the edit at the end of my answer.
Comment: This explanation helps out a lot! How I figured it out is that since the first draw is a red it doesn't "limit the outcome choices" of the second event if that makes any intuitive sense. It also appears that I wasn't computing the sample space size properly since I assume the whole sample space was 52 and not 52 X 52 representing the pairs of draws. Now it makes sense why you said the notation was confusing because I wouldn't have guessed that. Thanks again for the help and this points me in the right direction.
Comment: Also I assume that your calculation is based on the conditional probability formula?
Comment: I'm not sure which conditional probability formula you mean. Are you referring to $P(A|B) = \frac{P(AB)}{P(B)}$? My initial answer is based on reasoning about independence and then applying elementary counting arguments. The discussion about the 52 x 52 sample space at the end can be seen as applying that formula.
Answer:
You randomly draw a card, and after replacing it, you draw another.
  Let A be the event that the card is a club; let B be the event that
  the card is red. What is Pr(A|B)? That is, what is the probability the
  second card is a club, given the first one was a red card? Are the two
  events independent?

Let's interpret this paragraph for you. I believe the problem you are having is one of English. Specifically, the word given is not quite what you think it is. You ought to interpret the word given to only mean that if I tell you that A has happened, now what are the chances that B will happen.

You have a deck of 52 cards
You pull one out, it is a red card, you put it back in. (the text specifically says, "and after replacing it")
You pull out a new card (from the same 52 card deck)
What are the odds this new card is a club?

In some cases, the first activity might limit the sample size for the second event. In this particular case, it does not.


Redraw fragment after screen rotation with different layout

Question: I am implementing the registration/login part of an application and I am trying to implement it in one activity by using different fragments for login and signup.
I have two different layouts for portrait and landscape mode, which are basically a vertical layout for the portrait one and a horizontal layout for landscape, both with a logo and a FrameLayout containing the fragment (let's consider ony the login one).
The fragment is inflated by an xml resource file and inserted programmatically in the activity onCreate() method in this way:
fragmentManager = this.getFragmentManager();
ViewGroup root = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
LinearLayout linearLayout = (LinearLayout) root.getChildAt(0);
frameLayout = (FrameLayout) linearLayout.getChildAt(1);
loginFragment = (LoginFragment) fragmentManager.findFragmentByTag("loginFragment");

if (loginFragment == null) {
    // If fragment wasn't saved, create new one
    Log.d("DEBUG", "Fragment is null");
    loginFragment = new LoginFragment();
}
else
    Log.d("DEBUG", "Fragment is not null");

FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(frameLayout.getId(), loginFragment, "loginFragment");
transaction.commit();

Everything works fine until I rotate the screen, then I get the following:

java.lang.IllegalStateException: Can't change container ID of fragment
  LoginFragment{19d136ec #0 id=0x7f090040 loginFragment}: was 2131296320
  now 2131296322

I tried to place fragmentManager.executePendingTransactions(); after the commits, but still the same problem. I really don't know what more to try, hope to get some hints.
EDIT: Here are the layout files
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_gravity="center_horizontal"
    android:src="@drawable/jobsharklogo"
    android:layout_weight="1" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/frameLayout"
    android:layout_weight="1" />

</LinearLayout>

and
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:layout_gravity="center_vertical"
    android:src="@drawable/jobsharklogo" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frameLayout2"
    android:layout_weight="1" />

</LinearLayout>

And LoginFragment code:
public class LoginFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnLoginFragmentInteractionListener mListener;

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment LoginFragment.
 */
// TODO: Rename and change types and number of parameters
public static LoginFragment newInstance(String param1, String param2) {
    LoginFragment fragment = new LoginFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

public LoginFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_login, container, false);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
    params.gravity = Gravity.CENTER;
    view.setLayoutParams(params);
    Button loginButton = (Button) view.findViewById(R.id.loginButton);
    Button signupButton = (Button) view.findViewById(R.id.signupButton);
    loginButton.setOnClickListener(this);
    signupButton.setOnClickListener(this);
    return view;
}

public void onClick(View button) {
    if (mListener != null) {
        mListener.onLoginFragmentInteraction(button.getId());
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnLoginFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 *

 * See the Android Training lesson Communicating with Other Fragments for more information.
 */
public interface OnLoginFragmentInteractionListener {

    public void onLoginFragmentInteraction(int id);
}

}
Answer: The trouble is probably that you're trying to replace a fragment you added via XML.
See: IllegalStateException when replacing a Fragment for the discussion.
Edit 2:
I use landscape mode also, and am able to rotate this and change layout.
Ok, I implemented your code (with what I could figure out from your code). I only changed the way I located the elements by using findViewBy().
In the activity:
public class LoginActivity extends Activity implements LoginFragment.OnLoginFragmentInteractionListener {

private FragmentManager fragmentManager;
private FrameLayout frameLayout;
private LoginFragment loginFragment;

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

    fragmentManager = this.getFragmentManager();
    ViewGroup root = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
    frameLayout = (FrameLayout) root.findViewById(R.id.frameLayout);
    loginFragment = (LoginFragment) fragmentManager.findFragmentByTag("loginFragment");

    if (loginFragment == null) {
        // If fragment wasn't saved, create new one
        Log.d("DEBUG", "Fragment is null");
        loginFragment = new LoginFragment().newInstance("param1", "param2");
    }
    else
        Log.d("DEBUG", "Fragment is not null");

    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(frameLayout.getId(), loginFragment, "loginFragment");
    transaction.commit();
}

@Override
public void onLoginFragmentInteraction(int id) {
    Log.e("DEBuG", "id: "+id);
}

}
where main.xml is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:orientation="vertical"
          android:id="@+id/linear"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:paddingLeft="@dimen/activity_horizontal_margin"
          android:paddingRight="@dimen/activity_horizontal_margin"
          android:paddingTop="@dimen/activity_vertical_margin"
          android:paddingBottom="@dimen/activity_vertical_margin"
          tools:context=".MainActivity"
          android:background="#f0498a">

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/frameLayout"
        android:layout_weight="1" />

Clicking on the buttons in any of the rotation modes, I got:
E/DEBuG﹕ id: 2131296322
E/DEBuG﹕ id: 2131296321

The xml I used for landscape mode (put in layout-land
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:orientation="horizontal"
          android:id="@+id/linear"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:paddingLeft="@dimen/activity_horizontal_margin"
          android:paddingRight="@dimen/activity_horizontal_margin"
          android:paddingTop="@dimen/activity_vertical_margin"
          android:paddingBottom="@dimen/activity_vertical_margin"
          tools:context=".MainActivity"
          android:background="@color/material_blue_grey_900">

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frameLayout"
        android:layout_weight="1" />

<Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="login"/>

<Button
        android:id="@+id/signupButton"
        android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="sing in"/>

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView2"
        android:layout_gravity="center_vertical"
        android:src="@drawable/jobsharklogo" />

and portrait mode (just in layout folder)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:orientation="vertical"
          android:id="@+id/linear"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:paddingLeft="@dimen/activity_horizontal_margin"
          android:paddingRight="@dimen/activity_horizontal_margin"
          android:paddingTop="@dimen/activity_vertical_margin"
          android:paddingBottom="@dimen/activity_vertical_margin"
          tools:context=".MainActivity"
          android:background="#f0498a">

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/frameLayout"
        android:layout_weight="1" />

<Button
    android:id="@+id/loginButton"
    android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="login"/>

<Button
        android:id="@+id/signupButton"
        android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="sing in"/>

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/jobsharklogo"
        android:layout_weight="1" />

Comment: The fragment is added via code (the last three lines I posted in my question), only the fragment layout is inflated from XML.
Comment: Ok, might need to see your LoginFragment code. Have you also added an empty default constructor in LoginFragment?
Comment: Updated the question with XML layouts and LoginFragment
Comment: Rotating with only portait layout worked for me too, the problem is when you use a different layout for landscape mode.
Comment: I actually used a different layout when rotating - but I have updated with complete code (except LoginFragment).
Comment: By using the Id it actually works... I think I had tried this too, but I had some problems, but now it's working fine, well, that's the important thing. Thank you for your time :)


Data is not showing in table view

Question: I am new to iOS, and started with some tutorials. But when I try to display the content in tableview, it's not showing. I did all like they did in that tutorial. But still I was not able to display my contetnt in my table view.
Here my tutoial link : My link
Here my code :
import UIKit
import Alamofire

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    var nameArray = [AnyObject]()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        Alamofire.request("http://thecodeeasy.com/test/swiftjson.json").responseJSON { response in

            let result = response.result
            if let dict = result.value as? Dictionary<String,AnyObject>{
                if let mainDict = dict["actors"] {
                    self.nameArray = mainDict as! [AnyObject]
                   self.tableView.reloadData()
                }

            }

             }
    }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return nameArray.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as? CustomTableViewCell

        let title = nameArray[indexPath.row]["title"]
        cell?.ContentName.text = title as? String
        return cell!
    }

}

Comment: is it in swift 3.0 ?
Comment: YES ...........
Comment: Write Alamofire.request("http://thecodeeasy.com/test/swiftjson.json")
into viewdidappear instead of viewdidload
Comment: @sinha
 your need to enable NSAllowsArbitraryLoads into plist file. I just implement your API into a fresh project and find this issue.
Please check Answer section for Demo project and details.
Answer: There are three possibilities that you are not getting data.
First, your app datasource is not set properly.
Please check image for that

Second, Paste your API code into viewDidAppear and check if it's working or not
============= Important ============
Third, is check your info.plist contain following code.
Because whenever you are making the internet call you should have this code into your info.plist file.
Right click on info.plist and open as source code
paste the following code
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Try to run the app.
Let me know if its working for you.
Please check the link for code  click here
Thank you
Abhishek Sharma
Answer: Try this in top of the viewDidLoad
self.tableView.delegate = self
self.tableView.dataSource = self

Answer: As I can see you are using a tableview inside a view controller. You should set delegate and data source of this tableview to self.
Write these 2 lines in your view controller:
self.tableView.delegate = self
self.tableView.datasource = self

You can do that with XIB too.
If you have already done that or that Doesn't work, then try printing your self.nameArray and check if have expected data.

Data is not showing in table view


Hamburgers and sidebarEffects Collision

Question: I've tried countless things on this one piece of code that doesn't seem to want to work. I combine the following CSS and JavaScript libraries in my project:
Materialize; Normalize; Icons; Component; Hamburgers CSS; Modernizr (custom); jQuery; Classie.js; sidebarEffects.js; and SweetAlert.
Here is my code snippet I am running into problems with:

    <button class="hamburger hamburger--collapse" type="button" onclick="this.toggleClass('is-active);"></button>

        <button data-effect="st-effect-11" class="hamburger">

        </button>

The problem is that whenever you click the button (hamburger icon), the menu shows up, though the icon doesn't transition to the appropriate "is-active" icon and/or class! I actually tested it, and even with the "is-active" class put in place, the icon still doesn't change.
The "sideMenu" class that is active, this is the CSS code to it:
div.sideMenu {
    margin-top: 5%;
    width: 15%;
    height: 10%;
    position: fixed;
    margin-left: 5%;
}

Please help, and thanks so much in advance!
Comment: Can you provide a link to this in it's entirety?
Comment: Sure, https://lab.blackvikingpro.com/dev/webapps/cryptobean/
Answer: You have the following going on:
<button class="hamburger hamburger--collapse" type="button" onclick="this.toggleClass('is-active);"></button>

    <button data-effect="st-effect-11" class="hamburger">

    </button>

Which should be:

    <button data-effect="st-effect-11" class="hamburger hamburger--collapse" type="button">

     </button>

This will get the hamburger to convert to the is-active state correctly however when you click out of the animated state, it won't reset the hamburger (because you're restoring the non-animated state by clicking anywhere, not the hamburger). You'll need to look at that event and determine the callback function that restores the content out of that animated state, and reset your hamburger icon by removing the is-active class.

Hamburgers and sidebarEffects Collision


Find the inverse Fourier transform of $f$

Question: In Rudin's R&CA, the fourier inversion theorem states that if $f\in L^1$ AND $\hat f \in L^1$, and we define $g$ as
$$g(x)=\int_{\mathbb R} \hat f(t) e^{itx}\text{d}t,$$
then $g=f$ a.e.

Now, if $g_n=\chi_{[-n,n]}$, how do I prove that $g_n*g_1$ is the Fourier transform of an $f$ in $L^1$?

It is clear that $g_n*g_1$ is in $L^1$, and an obvious next step would be to apply the inverse Fourier transform to it to get (up to a multiplicative constant) $n\text{sinc} (x)\text{sinc}(nx)$. It is easy to prove that this is in $L^1$, however, I am confused by what I just did, since the theorem quoted above requires that both $f$ and $\hat f$ be in $L^1$. Is it valid to first compute the inverse transform and then prove that it is in $L^1$? Once you do that, how do you know that this function really transforms into the original?

Perhaps the exercise had in mind a clearer route, since the first part of the question only requires that I prove the existence of an absolutely integrable function whose Fourier transform is $g_n*g_1$. Once this is done, the above computations would be rigorous. The problem now becomes, how do I prove said function exists?
Answer: I'm not sure what you're confused about. Anyway:
Let $f=g_n*g_1$. You easily calculate $\hat g_n$ and $\hat g_1$ and see that they're in $L^2$, hence $\hat f=\hat g_n\hat g_1\in L^1$.
So $f,\hat f\in L^1$. Since $f$ is continuous the inversion theorem shows that $$f(x)=\int\hat f(\xi)e^{ix\xi}\,d\xi=\int\hat f(-\xi)e^{-ix\xi}\,d\xi
=2\pi\hat h(x),$$where $h(\xi)=\hat f(-\xi)$. (At first we know only that $f=\hat h$ almost everywhere, but since $f$ and $\hat h$ are both continuous it follows that $f=\hat h$ everywhere.)
Comment: I think that you miss a factor $2\pi$:
$$f(x)=\int\hat f(\xi)e^{ix\xi}\,d\xi=\int\hat f(-\xi)e^{-ix\xi}\,d\xi
= 2\pi \hat h(x).$$
The Fourier transform must be defined as
$$\hat f(t) = \frac{1}{2\pi} \int_{\mathbb R} f(x) \, e^{-itx} \, dx$$
when the inverse transform has the given form.
Comment: NO doubt. I never worry about where the $2\pi$'s go unless I'm writing something for publication. Different authors put them in different places - the Littlewood convention says $2\pi=1$ just for this reason.


Why doesn't my batch file work in Windows CE?

Question: My script is not executing on Windows CE version 8.
I am getting a file path from the user as input, appending the filename and attempting to 'start' it.
But the @ echo off isn't considered and all commands are shown in the console when runing in the device. Also, none of the start commands nor the set /p command is run. Error is shown
@ echo off
if exist clientshutdown3.exe (
   start clientshutdown3.exe
   start ConmanClient3.exe
   start CMAccept3.exe
   start MSVSMON.EXE
 ) else (
   set /p mypath=Enter path of pdf file:
)

if defined mypath start "" "%mypath%\clientshutdown3.exe"
if defined mypath start "" "%mypath%\ConmanClient3.exe"
if defined mypath start "" "%mypath%\CMAccept3.exe"
if defined mypath start "" "%mypath%\MSVSMON.EXE"

Comment: Which error is shown?
Comment: then maybe `set` does not allow the `/p` switch? can you manually run `set /?` from cmdline and see if it has any `/p` switch in the help?
Comment: can you test something simple? create a new file and do. `set /p "mypath=Enter path of pdf file: " && call echo %mypath% && pause` also, are you still running the same cmd window you did before the changes in your previous question? Remeber that one broke the environment.
Comment: @GerhardBarnard I'm using your code only, with the variable name set to mypath. When execiting set /p, it isn't waiting for user input.
Comment: `set /p` and `if defined` are Windows NT's cmd.exe features. Therefore they may not be available in WinCE. Try `echo %comspec%` to see what your shell is
Answer: The Windows CE command shell is not nearly as powerful as it's NT brothers.
Set /P is not supported under CE.
The shell hasn't changed since v5. (https://en.wikipedia.org/wiki/Windows_Embedded_Compact)
Here are a list of the v5 supported commands and their parameters.
http://nellisks.com/ref/dos/ce/SET.html
You can easily code this behavior up using another language if you really need to solve this using the shell.
Good luck.
Answer: According to wikipedia the console in WinCE is also cmd.exe. However they're not the same cmd.exe, so their functionality will be different
From the list of Command Processor Commands (Windows CE 5.0) on MSDN it seems Windows CE's cmd.exe is very primitive and more like command.com than Windows NT's cmd.exe. For example it doesn't support exit /B or copy /B and so on. Similarly it doesn't have set /P, set /A or set "with=quote" and supports only
SET [variable=[string]]

I've also found another detailed list of Script Commands for Windows Mobile Devices. In this list the if command is claimed to have only the below forms
if [not] errorlevel number scriptCommand
if [not] string1==string2 command
if [not] exist filename command
if [not] procexists processName command

There's no if defined in this list. However the document on MSDN disagrees, as it doesn't list the strange procexists form but the IF [NOT] DEFINED variable command one
Nevertheless, both agree that if can't have an else, thus your if/else block won't work either. And even if it has if defined, the last lines in your script won't work because you used start "" which isn't available in WinCE. You must use START command [parameters] instead
In summary, you'll get issues with if/else, set /P and start "" (and possibly if defined)


Find the value of $\log_{xz}(xy^4z) \times \log_{xy}(xyz^4)$

Question: if $x,y,z \gt 1$ and $x^2=yz$
find the value of
$$E=\log_{xz}(xy^4z) \times \log_{xy}(xyz^4)$$ what i did is
$$E=\log_{xz}(xy^4z) \times \log_{xy}(xyz^4)=(1+4\log_{xz}y)\times (1+4\log_{xy}z)$$  after that i could not proceed
Answer: $$
(1+4\log_{xz}y)\times (1+4\log_{xy}z)
=(1+4\,\frac{\log_{x}y}{\log_{x}(xz)})\times (1+4\,\frac{\log_{x}z}{\log_x(xy)})\\
=(1+4\,\frac{\log_{x}y}{1+\log_{x}(z)})\times (1+4\,\frac{\log_{x}z}{1+\log_x(y)})\\
=(1+4\,\frac{\log_{x}y}{1+\log_{x}(z)})\times (1+4\,\frac{\log_{x}z}{1+\log_x(y)})
$$
Now, since $yz=x^2$, we have $y=x^2/z$, and so
$$
\log_xy=\log_xx^2-\log_xz=2-\log_xz.
$$
Then
\begin{align}
(1+4\log_{xz}y)\times (1+4\log_{xy}z)
&=(1+4\,\frac{\log_{x}y}{1+\log_{x}(z)})\times (1+4\,\frac{\log_{x}z}{1+\log_x(y)})\\
&=(1+4\,\frac{2-\log_{x}z}{1+\log_{x}(z)})\times (1+4\,\frac{\log_{x}z}{3-\log_x(z)})\\
&=\frac{(9-3\log_xz)(3+3\log_xz)}{(1+\log_xz)(3-\log_xz)}\\ \ \\
&=3\times3=9.
\end{align}
Answer: Late to the party, but it is maybe simpler to replace directly $x^2=yz$, then $E =$
$$\log_{xz}(x^3y^3) \times \log_{xy}(x^3z^3)$$
then using $\log_{b}(x) = \frac{\log(x)}{\log(b)}$
$$= \frac{\log(x^3y^3)}{\log(xz)}\times\frac{\log(x^3z^3)}{\log(xy)}$$
then since $\log(x^n) = n \log(x)$
\begin{align}
&= \frac{\log((xy)^3)}{\log(xz)}\times\frac{\log((xz)^3)}{\log(xy)}\\ \ \\
&= 3\,\frac{\log(xy)}{\log(xz)}\times 3\,\frac{\log(xz)}{\log(xy)}\\ \ \\
&= 9
\end{align}
Comment: that was pretty clever idea


Div does not fill parent with width:100%

Question: html

test

</main

CSS
div.homediv {
  background-color: yellow;
  width: 100%;
  position: static;
  /*The lower the z-index, the further in the background the element*/
  z-index: -1;
}

At first glance, this should make the div horizontally fill the screen. But it did not. A few answers on here said that the width:100% will only work when the width of the parent is set, but that was set. To ensure that, I even gave html, body, main and my div the width:100% attribute.
This did not fix it.
Answer: After some trying around in the chrome DevTools, I found out that main does fill the screen width. But it contained some seemingly pre-set attributes that I had to remove. Google told me that padding and margin are - if not specified - set by the browser, so to fix the css, I had to add
main {
  padding:0;
  margin:0;
}

Answer: I think space is from  tag, not  so try
body {
  margin: 0;
  padding: 0;
}

But if you use a reset CSS you don't have this problems. Read about importance of CSS reset. You can use this but also it's a lot good resets.
Answer: Use this code, I hope it works for you:
body{
    padding:0;
    margin:0;
}


Mascara em campo de form Laravel

Question: Boa noite, tudo certo?
Não encontro uma forma de incluir uma máscara de validação com o Form Collective do Laravel.
Abaixo o trecho do código com um campo:
 {{Form::label('comp_nota','Competência')}}
{{Form::text('comp_nota','',['class'=>'form-control','required','placeholder'=>'Ex: 08/2018'])}}

Preciso que ao digitar a competência o campo adicione a / no meio do campo. ex: 02/2018.
Ou seja, o usuário só digita 022018.
Oque posso usar galera?
Comment: {{Form::text('comp_nota','',['class'=>'form-control','required','placeholder'=>'Ex: 08/2018', pattern="[A-Z]{3}[0-9]{4}"])}}
Answer: Solução:
Uma forma de resolver é utilizar a biblioteca jquery.mask para as máscaras de seus campos.

Exemplo de uso:

jQuery(function ($) {
    $("#comp_nota").mask("99/9999");
});
Answer: Problema
Criar campo com input type date com laravelcollective/html
Solução
{{Form::label('comp_nota','Competência')}}
{{Form::date('comp_nota','',['class'=>'form-control','required','placeholder'=>'Ex: 08/2018'])}}

Notas
Avalie o suporte deste atributo relativamente aos diferentes browsers https://caniuse.com/#search=input%20date
Comment: Boa noite Jorge, neste caso ele fica no formato dd/mm/aaaa, eu precisava do formato mm/aaaa
Comment: Penso que o melhor neste caso seria usar uma inputmask via biblioteca em javascript
Answer: Precisei usar essa a biblioteca jQuery-Mask-Plugin no Laravel, compartilho a minha solução.
<!doctype html>

        @yield('content')

    @yield("script")

Formulário Cadastrar

@extends('layouts.app')

@section('script')

@endsection

@section('content')
<form class="form-group" action="{{ action('UserController@store', 0) }}" method="post">
    @csrf

        CPF

        <input class="form-control" id="cpf" type="text" name="cpf" required>

</form>

@stop

Mascara em campo de form Laravel


Server 2008 R2 in office with 5 users, Opening another office down the road, same domain?

Question: Hope this is the best place to ask this question!
We currently have a small office with 5 computers and a server 2008 R2. We have just opened another small office literally across the road... sadly out of Wifi range so are looking to connect another 5 PC's in this office, with server, and link it to the same domain potentially over VPN.
However I have no idea if this is the best way to go around this. All users in both offices need to be able to log on to any PC and the file server in our primary office needs to be able to be accessed in our secondary office.
Both offices have a broadband connection and is currently running around 4mb/s down.
Any input would be gratefully appreciated and wither or not this is the best way to go about this?
Cheers in advance,
Chris
Comment: `literally across the road`, how wide is the road? Try attaching a directional yagi antenna, then you should be good for a few kilometers.
Comment: how far is the actual distance between buildings?  Consider using wireless repeaters between them to connect the 2 LANs if you don't want to go s2s vpn.
Comment: Ubiquiti Nanostation M5s could probably pull off ~100Mbps full-duplex through a window even...
Comment: Question: why does each user need to remotely access one another's computers?
Comment: @gravyface I think he means the users can work at any computer in either office and need to be able to sit down at any computer and be able to work/logon to the workstation and access the file server in the main office.
Comment: Hey guys, Site to site should be alright for us. Got VPN set up and have a DC at each site, Just confused now as how to share files between them. MikeAWood suggested DFS-R but I have no idea where to start with this and will this work over a Broadband connection through VPN sufficiently?
Comment: @user181682 I would highly recommend you seek out a professional to at least give you a quote on a point-to-point wireless link if there's a clear line of sight. No recurring costs each month, 10-20 times the speed, no need for DFS, can bridge them right on your LAN.
Answer: Yes, definitely use 1 domain for this (preferably with at least one Domain Controller at each site) and use something like a site-to-site VPN to logically stretch the one network across the two sites. Talk to your ISP about what options they have to facilitate connectivity between the two sites. They can probably do MPLS, or a simple site-to-site link for you.
Comment: Hey MDMarra, A domain controller at each site is do-able and site-to-site VPN is what im planning however I have managed to set-up our primary server for routing and remote access to allow VPN however I am stuck as to how to set up our secondary server I have AD installed on it currently and also routing and remote access... Confused as to how to set this up do I run DCPROMO to set up another site at office 2?
Comment: You join the new server to the existing domain, then you run `dcpromo` and select "Add to an existing forest" (or whatever the actual text is).
Comment: Ideally a step by step as to what I need to do on "server2" would be ideal!
Comment: And about VPN to have an "Always on" connection?
Comment: Like I said...a site to site VPN or contact your ISP for their options...
Comment: Got VPN and DC's at each site, just wondering about file sharing now! Cheers!
Answer: Windows 2008 will let you do DFS-R which if setup correctly, you could replicate your files from one location to the other in near-realtime (bandwidth permitting of course).  If you did both as an AD member server, you could easily allow logins at both locations and access to their files would happen between either server.  The other added benefit of this is that if one server goes down, you could set it up to use the other office's server during disaster recovery.
Comment: Hey, sounds IDEAL! How do you set this up?
Comment: You'd still need the VPN like MDMarra mentioned below, but read up on DFS and DFS-R and how it is setup.  It can work well for situations like yours if you have the knowledge to set it up properly.  Doing so is not a simple "do this" answer, so you'll likely need to do more research.
Comment: Read up on it and have managed to get OUR DC1 "Server" as namespace and replica to DC2 "Server(Other Location)" looking great so far and works a treat!! What a fab solution I would never have thought of! Got all files backed up at each location then aswell, cost effective! Just looking to get roaming profiles setup now as the paths are slightly different, Im assuming is just changing it from what is it just now "\\SERVER\ShineUserRoam$\CQuinn" to something like "\\domain.local\centralshare\ShineUserRoam$\CQuinn"?
Comment: Depending on the size of the files, it can take a bit for everything to sync.  But if you can deal with the lag of the replication, it works in some cases.  If you have things like PST files or other large work files, you might have to use a different method for syncing over user folders. But YMMV.