How to use values from columns with LIKE - Postgresql

Question: I am trying to check the validity of a list of emails. Valid emails are those that are formatted as:
firstname.lastname@example.com
I can find the valid emails using regex or LIKE operator. But I would like to learn if there is a way to use the data from other columns such as 'name' and 'lastname' to avoid any problems that can arise from unique names that include different characters that isn't covered by [A-Za-z] in Regex.
I've tried this:
SELECT name,
       lastname,
       email,
       CASE
           WHEN email ~ '[A-Za-z]*\.[A-Za-z]*\@[A-Za-z]*\.[A-Za-z]*' THEN true
           ELSE false
       END AS valid
FROM personlist

and this:
SELECT name,
       lastname,
       email,
       CASE
         WHEN email LIKE '%.%||%.%' THEN true
         ELSE false
       END AS valid
FROM   personlist

They seem to work just fine but I want to learn if there is a way to use the data from the other columns with an operator such as LIKE. I think using the data from existing columns would result in more targeted and solid queries.
For example:
+-----------+----------+-----------------------------+-------+
|   name    | lastname |            email            | valid |
+-----------+----------+-----------------------------+-------+
| Molly-Rae | Jackson  | email@example.com | true  |
| Molly-Rae | Jackson  | firstname.lastname@example.com  | false |
+-----------+----------+-----------------------------+-------+

Comment: Sample data and desired results would be helpful.
Comment: Also I need to disregard the case sensitivity and delete any spaces in names/lastnames. Would ILIKE and REPLACE be enough? I can't try them since I can't use the data from the columns with LIKE operator.
Comment: Your question is unlcear, I think this is what you're asking. Do you know host and domain? Then you can do a direct comparison: CASE WHEN name || '.' || lastname || '@' || host || '.' || domain = email THEN TRUE ELSE FALSE END. If you don't know host & domain, then you can split the email on '@' and do a direct comparison  between the name, lastname and the left portion, and a regex on the right half (just make sure that count of '.' > 0?)
Comment: I don't know the domain. I only know the data in columns name and lastname.
Comment: Unrelated, but: your CASE expression, can be simplified to `email ~ '[A-Za-z]*\.[A-Za-z]*\@[A-Za-z]*\.[A-Za-z]*' as valid` to do a case insensitive matching use `~*` instead of `~`
Comment: Yes, I missed it. Thanks for pointing that out.
Answer: You can use the other columns to compute the pattern you want to validate against. For example:
select
  name,
  lastname,
  email,
  lower(email) like lower(name || '.' || lastname || '@xmail.com') as valid
from personlist


Arquivo de conexão PDO. Como usar?

Question: Tenho um arquivo de conexão PDO. Para incluir esta conexão nos outros arquivos do sistema afim de fazer as requisições no banco de dados, vou usar isso????
<?php require('conexao.php'); ?>

Comment: Tá... agora, qual sua dúvida?
Comment: respondendo: sim..... more any information?
Comment: Se você que sabe o conteúdo do arquivo está em dúvida, imagine nós.
Answer: Bom, sua dúvida ficou 'meio' vaga pra mim, quer dizer, meio é apenas pra não dizer completamente, mas enfim...
O arquivo PDO que voce deve estar se referindo funciona como uma classe, costuma-se criar um arquivo separado e fazer apenas um require_once por praticidade, mas claro, se em toda interação com o banco, voce quiser abrir uma conexão com o banco manualmente, é so vc colocar no seu código sem fazer referencias
Aqui na empresa usamos 3 classes para conexão com um banco...
pdo.php <-- onde realizamos a conexão, digamos física;
cmd_sql.php <-- onde criamos classes para nos auxilias a montar o SQL;
dadosconectabanco.php <-- onde colocamos os dados necessarios no pdo.php para realizar a conexão ao banco
Nesse último vale ressaltar que devemos criar um pra cada sistema, isso porque ele deve conter informações mais especificas sobre o banco que voce vai se conectar, seja SQL, oracle ou anyother.. informações tipo: Porta, IP, Schema, <--[1] Tabela, Login, senha, etc, etc
[1] - Esses voce pode colocar direto no PDO, muitas vezes esses dados são meio padrões

Arquivo de conexão PDO. Como usar?


Limit entity reference options base on taxonomy tag

Question: I have three content types. Building, Department and Person. I connect this contents whit entity reference base on Content types. The problem is that I have a lot of persons and a lot of departments and also multiple buildings. How can I limit selection in edit mode, that I can add persons in department only from particular building wher the department is placed? My first try was to add taxonomy term (building A) to person and department placed in building A and then try to filter this in view but without a success because for building B I will need to create new Content type and add different view for same content structure. I could create Content Type "Person building A" and then filter by content type but this does not seems like a good solution.
Answer: I did something like this recently myself.
Your Person content type should have two entity reference fields, one to a Building, and a second to a Department. A Department also has an entity reference to Building.
Use a hook_form_alter to target the Person form.
In that function get a list of the Departments and their Building references, and attach it to the form along with a reference to a custom Javascript library. (Note that you'll have to use the proper machine name for your content types and fields.)
$departments = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'department']);

$department_data = array_map(function($department){
    return $department->field_ref_building->target_id;
}, $departments);

$form['#attached']['drupalSettings']['dept_bldg_info'] = $department_data;

$form['#attached']['library'][] = 'my_module/my_module.library_name';

The library file will look something like this:
Drupal.behaviors.chartInfoHierarchicalSelect = {
  attach: function (context, settings) {
    // Apply to the HTML page context & the person forms.
    if (context.location || context.id == 'node-person-edit-form'|| context.id == 'node-person-form') {
      let building_inputs = jQuery('[name$="[field_ref_building]"]'),
        department_inputs = jQuery('[name="[field_ref_department]"]');

      building_inputs.each(function () {
        // Ensure initial load has proper limits.
        updateDepartments(jQuery(this));
        // Update on change.
        jQuery(this).change(function () {
            updateDepartments(jQuery(this))
        });
      });

      function updateDepartments(building_input) {
        var selected_building = building_input.val();

        department_inputs.each(function () {
          var opt_val = jQuery(this).val();
          if (opt_val != '_none' && drupalSettings.dept_bldg_info[opt_val] == selected_building) {
            jQuery(this).prop('disabled', false);
          }
          else {
            jQuery(this).prop('disabled', true);
            jQuery(this).prop('selected', false);
          }
        });
      }
    }
  }
};

Then when you select a building, you should see the appropriate departments get enabled/disabled.
Comment: Thank you for your answer. I have a problem passing the argument to contextual filter in edit mode. Can you hint me how can I do that?
Comment: Sorry, I don't understand your question. Based on the edited question posed, you're mixing apples and oranges. "Contextual filters" is for Views, not editing a piece of content. Are you trying to limit the selections on a node edit form? For example, when you select the building, it limits the selection options for department, and when you select the department, it limits the selection options for person?
Comment: Maybe I understand your answer wrong. What I want to do is to limit the selections of persons that I can chose from in edit mode. I have like 20 buildings and every building will have like 20 department and every department will have 3 peoples. I first create Buildings then I create department and on the end person. I know that person will work in building A so I want to limit choice of department just for building A. Otherwise I will have like 400 options for choosing. So I added taxonomy term Builing A,B,C... So a could somehow filter choice but maybe this is wrong way to do it.
Comment: Thank you it worked!


Is there an intuitive explanation of $n$-dimensional sphere's surface and volume being maximal in dimensions 5 and 6?

Question: I was wondering if there is an intuitive explanation why the surface of an $n$-dimensional sphere is maximal at $n=6$ and for the volume $n=5$.
I know that for the surface you have:
$$A_n=\frac{2\pi^\frac{(n+1)}{2}}{\Gamma(\frac{n+1}{2})}$$
And for the volume
$$V_n=\frac{A_{n-1}}{n}$$
Finally you get
$$A_n(R)=A_nR^n$$
$$V_n(R)=V_nR^n$$
Where $R$ is the radius of the ball.
Plugging in the dimensions it's easy to show that $V_n$ is max for $n=5$ and the surface for $n=6$
Is there an intuitive way of explaining this?
Comment: Maybe, but I would like an explenation from a physicist rather than a mathematician due to the way one looks at space.
Comment: According to [Mathworld's Hypersphere article](http://mathworld.wolfram.com/Hypersphere.html), "*for the unit hypersphere, the hyper-surface area reaches a maximum and then decreases towards 0...  the seven-dimensional unit hypersphere has maximum hyper-surface area*". For the volume the maximum does occur in dimension 5, but that is also an artifact of choosing radius = 1, for other radii it occurs in other dimensions, see [Richeson's explanation](https://divisbyzero.com/2010/05/09/volumes-of-n-dimensional-balls). In other words, there is nothing special about 5 and 7.
Answer: Here is a naive intuitive explanation for the growth in volume of the unit $n$-sphere as $n$ increases.
Embed the $n$-sphere in an $n$-cube which has   $2^n$ corners, $2n$ facets and volume 1. The space in the cube not occupied by the sphere is concentrated near the corners and the space in the cube occupied by the sphere is concentrated near the middle of the facets. For   $n \leq 4$,  the latter effect overrides the former. But for $n > 4$, the corners win.


Trouble installing path for Python 3.7 on Windows 10

Question: When I try to enter 'python' into my cmd window, I get back this error:       "'python' is not recognized as an internal or external command,
operable program or batch file."
Any ideas how to get my cmd window working?
I tried going into environmental variables and adding my python path to the path system variables, however this is not working.

python
  'python' is not recognized as an internal or external command,
  operable program or batch file.
Comment: Have you installed python? If so, how?
Comment: Did you reload the cmd window after updating the system PATH? It won't update otherwise.
Answer: This might be what you are looking for
Running path can display the system path, and ensure things are configured correctly :)
Comment: After doing that, I got a huge line of jumbled paths.  Is it supposed to be about 50 files separated by '/'?
Answer: Answered over here
Assuming you googled and found that (or something similar) yourself, then my guess is you're running into a different issue. For example, the semicolons in the path, especially the proper positioning of them, are very important, could your issue be that simple?
Answer: Try entering:
py

Some systems use this to function like mine. I had the same error but then I tried py and it worked. Maybe this will work for you


Building Custom Forms in Drupal 7

Question: I'm new to Drupal 7 and installed it on my local machine to play around.
I'd like to build a basic Job Posting Form and wanted to ask about questions/best practices regarding Drupal.
This was the process I was going to follow:

Create a new content-type "job", add a title, description and pay - all text fields.
Create a new module, then within the module build out the custom form to create a new job listing.  How do I associate the new form with the content-type?  Should I build the form code in my custom theme folder (template.php) or in a new module?
When the form is submitted, how does the data get saved?  How do I associate the submitted form with the database?  Most of the examples using the Form API only mention building the form but not how to store the data (in my example, storing the "job" as new content).

I'm not asking for you to write code for me, but I'm having a difficult time understanding the workflow and best practices for working with Forms in Drupal 7.  Any good guides on how to accomplish what I need would also be appreciated.
Answer: Great to know you're exploring Drupal! :D

Create a new content-type "job", add a title, description and pay -
all text fields.

Since you want to ask data from users or something like a survey, Geek Alvaro J Hurtado V is right. The Entityform module is the way do go since it uses entities and fields which are future proof and used in Drupal 8.
Brings me to another module called Views, Entityform works well together with the Views module. This module helps to create data lists without any coding needed. This is one of the most used module in the Drupal world. Check it out if you have time. :)

How do I associate the new form with the content-type?
When the form is submitted, how does the data get saved? How do I associate the submitted form with the database?

The Entityform module already handles this for you out of the box.
So what you need to do is to create your survey form using the Entityform module and you're basically good to go. You would have:

A public form where your anonymous/not logged in users can fill-up.
A content type where it relates the data submitted by the user.
A page which lists all the user submitted data.
Answer: Jobs will likely be included in content listings on the website. a "job form" should just be a content type. While frowned upon in general this content type could be given Anonymous User access to create new content.
Drupal handles storing content type data for you. Now you just need to likely work with that data. Look at using Rules or Drupal Hooks to store the newly created (and or approved/vetted -- you can approve Node content with many modules, 1 of which is Workbench) job entries in a Queue (using Rules Queue) for additional processing during Cron run.
Using the Features module -- you can do 99% of the above configuration and business logic in your website as an Administrator and then export this configuration and business logic to code in a Feature.
EDIT
sorry frowned is a poor choice of words. Anyway you cut it people are submitting content to your website (job postings) that type of stuff should be audited somehow (right? Viagra posts anyone?).
I'm suggesting this route because you could try hand coding stuff, and you'd be re-creating all or some of the modules i mention here. There are security concerns giving anonymous users access to create content, such as you'd only want to give them access to Filtered HTML as an input type -- if you don't understand the possible dangers then it's frowned upon to be playing with fire.
Comment: Given that what you described is generally frowned upon, what method "should" be done to do it more effectively?  For example, what if my form was significantly more advanced, what approach should I take in that case?  I was hoping to understand how to use Drupal without necessarily installing a bunch of custom modules, but maybe that's the best approach is to just install a bunch of module and not mess with any code...
Comment: see my edit plz
Comment: In general your asking about Forms. The FormAPI in Drupal is for any type of Form. But Drupal provides many forms for you out of the box. Such as to create Content Types, Contact Page forms, User profile pages, possibly "webforms" which store data exportable to CSV. It's not advisable to try to create your own forms that replace drupal built-in components such as `content` forms via a `Content Types` as I've outlined here. Make sense? So try to look through core/community for a suite of modules that fit your needs which your custom modules can hook into and adapt to your needs.
Answer: If you build simple form the best is to create content-types, install couple standard module and do job.
Good module for the form is WebForm Module
If you have a complicated forms the best is to custom build form and you have module with example how to do that Examples for Developers
I hope I helped you.
Comment: So, how can I associate a content-type with a custom form in my module?  I'd like to create a content-type, then build a wizard form to collect a form based on the content-type.  Do I use the WebForm module for that?
Comment: One solution is to create own entity types with module
[entityreference](https://www.drupal.org/project/entityreference)
here is the good how
http://www.trellon.com/content/blog/creating-own-entities-entity-apito page
Answer: In this case, I think the best option is entityforms.
https://www.drupal.org/project/entityform

Building Custom Forms in Drupal 7


Does this proof contain circular logic?

Question: I am trying to prove that $e^x$ is a solution to $f'(x)=f(x)$, and there is a point at which I am concerned that there might be circular logic.
Here's what I've got so far:
$$f'(x)=f(x)$$
$$\frac{f'(x)}{f(x)}=1$$
$$\int\frac{f'(x)}{f(x)}dx=x+c_0$$
Letting $y=f(x)$ gives
$$\int\frac{dy}{y}=x+c_0$$
Which gives $$\ln|y|=x+c_0$$
$$f(x)=c_1e^x$$
QED
The bit I'm concerned about is $\int\frac{dy}{y}=\ln|y|$.
Is there any proof of $$\int\frac{dx}{x}=\ln|x|$$
which doesn't use $\frac{d}{dx}e^x=e^x$?
Edit: If it wasn't clear, I am asking if there is a way that one can prove that $$\int\frac{dx}{x}=\ln|x|$$
without relying on the fact that $\frac{d}{dx}e^x=e^x$?
Comment: How do you define $e^x$? Some people *define* $\ln(x) := \int_1^x \frac{1}{t} \, dt, \; x>0$ and then define $e^x$ as its inverse. In that case, there is no circular reasoning.
Comment: @MarkViola If one first define $\log$ from the integral and then $\exp$ as its inverse function, then one can define $a^x=\exp(x\log a)$; in the particular case of $a=e=\exp(1)$, we get $e^x=\exp(x)$. No need to have predefined general exponential functions.
Comment: Assuming you have defined $e = \lim_{n \to \infty} (1+1/n)^{n}$, you could differentiate $\ln(x)$ directly and appeal to this limit. See https://math.stackexchange.com/questions/1341958/proof-of-the-derivative-of-lnx
Comment: @Sobi Using the definition of $\exp(x)$ to be the inverse of $\log(x)=\int_1^x \frac{1}{t}\,dt$, one would need to still show that $\exp(x)=(e)^x$, which is not directly evident!
Comment: And how does one know that $\exp(x)$ has the properties of an exponential function without showing this from your defining it as the inverse of the integral representation of the logarithm?  Of course, this is not difficult to do.  My "point of view" is only this: it is not immediately obvious.  Does that clarify my comment?
Comment: @Sobi which ever way makes my proof valid...?
Comment: @MarkViola Yes, indeed! Thanks for pointing that out!
Comment: @egreg You are presuming that the function $\exp(x)$ is the number $e$ raised to the power $x$.  You need to prove that.
Comment: @MarkViola Not at all; I'm presuming that $\exp$ is the inverse function to $\log$. It's easy to prove that, for integer $n$, $\exp(n\log a)=a^n$, so it makes sense to ***define*** $a^x=\exp(x\log a)$ for any real $x$. If I ***define*** $e=\exp(1)$, then I get $e^x=\exp(x)$.
Comment: @egreg One can call the inverse of $\int_1^x \frac1t\,dt$ as $f(x)$.  And clearly, $f'(x)=f(x)$.  But we have not shown that $f(x)=e^x$ where we the number $e$ can be defined as $\lim_{n\to\infty}\left(1+\frac1n\right)^n$ (Among Other Possible and Equivalent definitions), and exponentiation of any real number $x$ can be defined as the limit of $e$ to the rational number $p/q$ using density of the rational numbers.
Comment: @MarkViola From $e=\exp(1)$ it's quite easy to show that $e=\lim_{n\to\infty}(1+\frac{1}{n})^n$. My point of view is that defining the exponential with rational numbers is to be avoided with great care. The path I follow allows to prove existence of $n$-th roots for every integer $n$: just check that $(\exp(\frac{1}{n}\log a))^n=a$, so $\sqrt[n]{a}=\exp(\frac{1}{n}\log a)$..
Comment: @egreg Yes, we could define $e$ as the number such that $\int1^e \frac1t\,dt=1$.  But so what?  How does that imply that $(\exp(1))^x =\exp(x)$?  This is not difficult to show, but my point was only that it isn't blindingly obvious that $\exp(x)=e^x$ without a bit more work.  Does that make sense now (I hope)?
Comment: @MarkViola Sorry, but you seem not wanting to understand my point of view: $e^x=\exp(x)$ ***by definition***.
Answer: Assuming the question you are asking is indeed that which you are trying to solve, to show that $e^x$ is a solution to $f' = f$ all you have to do is show that $\frac{d}{dx}e^x = e^x$. Which can be fairly easily done by looking at the series definition of $e^x$ term by term and differentiating.
If you're interested in investigating whether or not $ke^x$ is the only solution to $f' = f$ (which it is), then other steps are necessary.
Comment: I know how to prove that $De^x=e^x$ with series, but I want to know if solving the ODE is a valid proof
Comment: Using the definition of $\exp(x)=\sum_{n=0}^\infty \frac{x^n}{n!}$, one would still need to show that $\exp(x)=(e)^x$, which is not directly evident.
Comment: Well, the only other step is invoking Cauchy's / Picard's theorem on uniqueness of solution to an ODE.
Answer: Here's a way to remove the circularity.
Define $g(x) = \int_1^x dt/t$. Then
$$
g(xy) = \int_1^{xy}\frac{dt}{t} = \int_1^x\frac{dt}{t} + \int_x^{xy}\frac{dt}{t} = \int_1^x\frac{dt}{t} + \int_1^y\frac{du}{u} = g(x)+g(y)
$$
where $t = xu$ is used for the substitution. This property is unique to logarithm functions, and its base will be the number $e$ such that $g(e) = 1$. So $g(x) = \log_e(x)$, and $g^{-1}(x) = e^x$.
Comment: Yes. The base of any logarithm function is the value it maps to 1.
Comment: No, $g$ is defined by $g(x) = \int_1^x dt/t$. We then show it has the property $g(xy) = g(x) + g(y)$, which means it must be a logarithm to some base. Then we define $e$ as that base.
Comment: just for clarification: are you defining $e$ as the base of the logarithm?
Comment: Okay I think I get it... We define $g(x)$ as the function that satisfies $$g(xy)=g(x)+g(y)$$ Then we note that its a logarithm, then we define $e$ as its base?
Comment: Ohh okay. That makes sense. Thanks!
Comment: That's the approach that Tom Apostol takes, in volume 1 of his Calculus text.
Answer: The usual proof of this is by setting $g(x)=f(x)e^{-x}$ and prove $g'=0$.
See for instance: Proof that $C\exp(x)$ is the only set of functions for which $f(x) = f'(x)$
Nevertheless your reasoning is correct, but solving the ODE this way lacks of rigour (dividing by $f(x)$ without discussing the annulation). Instead it should be used as a hint to find that solutions looks like $Ce^x$ then by CL theorem you claim their maximality and uniqueness.
See for instance LinAlgMan's answer here: https://math.stackexchange.com/a/409974/399263
Comment: I like your approach here. Thank you
Answer: Let's suppose we know nothing about exponential and logarithm. Now we're given the Cauchy problem
\begin{cases}
f'(x)=f(x)\\[6px]
f(0)=1
\end{cases}
Let's suppose a solution exists defined over $\mathbb{R}$. For $y\in\mathbb{R}$, define $f_y(x)=f(x+y)$. Then, differentiating with respect to $x$, $f'_y(x)=f(x+y)=f_y'(x)$ and $f_y(0)=f(y)$. If $f(y)\ne0$, we obtain that $g(x)=f_y(x)/f(y)$ is a solution of the same Cauchy problem, so we conclude that $g=f$, so that $f(x+y)=f(x)f(y)$ (at least, when $f(y)\ne0$).
Consider $Z=\{x\in\mathbb{R}:x>0, f(x)=0\}$ and assume it is not empty. Then, if $z=\inf Z$, we have by continuity that $f(z)=0$. Now $z>0$, because $f(0)=1$, so $f(z/2)\ne0$. But we have just proved that $f(z)=f(z/2+z/2)=f(z/2)^2\ne0$: a contradiction. Similarly, $f$ cannot have a negative zero. Thus $f$ is everywhere positive and strictly increasing.
In particular $f(1)>1$ and from $f(n)=f(1)^n$ we deduce that
$$
\lim_{x\to\infty}f(x)=\infty
$$
From $f(0)=f(x)f(-x)$, we get therefore that $\lim_{x\to-\infty}f(x)=0$.
The inverse function $l$ of $f$ is thus defined over $(0,\infty)$. For every $x\in(0,\infty)$, we have $f(l(x))=x$, so by differentiating,
$$
1=f'(l(x))l'(x)=f(l(x))l'(x)
$$
and so $l'(x)=1/x$. By the fundamental theorem of calculus, since $l(1)=0$,
$$
l(x)=\int_1^x\frac{1}{t}\,dt
$$
Since
$$
l(xy)=\int_1^{xy}\frac{1}{t}\,dt=\int_1^x\frac{1}{t}\,dt+\int_x^{xy}\frac{1}{t}\,dt
$$
In the second integral we can do the substitution $t=xu$, getting
$$
l(xy)=\int_1^x\frac{1}{t}\,dt+\int_1^{y}\frac{1}{u}\,du=l(x)+l(y)
$$
Now we can drop our assumption about the existence of $f$, because we can consider the function
$$
\log x=\int_1^x\frac{1}{t}\,dt
$$
which satisfies $\log(xy)=\log x+\log y$, is increasing and has
$$
\lim_{x\to0}\log x=-\infty,\qquad\lim_{x\to\infty}\log x=\infty
$$
by considering that $\log(2^n)=n\log2$ and $\log2>0$.
The inverse function $\exp$ of $\log$ is therefore a solution of our Cauchy problem.
Now it's not difficult to show that every solution of the differential equation $f'(x)=f(x)$ is of the form $f(x)=c\exp x$. Indeed, if $f$ is such a solution, then
$$
h(x)=f(x)\exp(-x)
$$
is constant, as
$$
h'(x)=f'(x)\exp(-x)-f(x)\exp(-x)=0
$$
Thus $c=f(0)$.
Can we say that $\exp x=e^x$? This is not really difficult. Note that $\log'1=1$, so
$$
1=\lim_{n\to\infty}\frac{\log(1+1/n)-\log1}{1/n}
$$
From the main property of $\log$, we get that, for integer $n$
$$
\log(x^n)=n\log x
$$
Thus we have
$$
1=\lim_{n\to\infty}\log\left(\left(1+\frac{1}{n}\right)^n\right)
$$
and, by continuity,
$$
\exp1=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n=e
$$
For positive integer $n$, we have $\exp n=\exp(1+1+\dots+1)=(\exp 1)^n=e^n$. For negative $n$, $1=\exp(n-n)=\exp(n)\exp(-n)$, so also in this case $\exp n=e^n$.
If $p$ is an integer and $q$ is a positive integer, we have
$$
e^p=\exp p=\exp(q(p/q))=(\exp(p/q))^q
$$
and so $\exp(p/q)=e^{p/q}$. Since the functions $x\mapsto\exp x$ and $x\mapsto e^x$ coincide over the rationals, they are the same.

Actually, the functions $\exp$ and $\log$ allow to prove the existence of $q$-th roots. Let's work under the assumption we don't know them, so we don't know the existence of the functions of type $a^x$ (for $a>0$) for lack of tools.
If $a>0$, we note that $a^n=\exp(n\log a)$, so we can define $a^x=\exp(x\log a)$. By the very definition, it follows that
$$
(a^{1/n})^n=(\exp(\tfrac{1}{n}\log a))^n=\exp(n\tfrac{1}{n}\log a)=\exp\log a=a
$$
so $a^{1/n}$ is the (unique) positive real number whose $n$-th power is $a$.
By defining
$$
e=\exp1=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n
$$
we have that $e^x=\exp x$ by definition, but also that, for a rational $p/q$ and any positive $a$,
$$
(a^{p/q})^q=a^p
$$
so our definition of the general exponential function is what we expect it to be.
Comment: Great answer. Thank you
Answer: This is one way to define the logarithmic functions.
$$\ln x= \int _1 ^x \frac{dt}{t},  \text { for  x > 0 }  $$
So with this convenience, your proof is OK.
Comment: Using the definition of $\exp(x)$ to be the inverse of $\log(x)=\int_1^x \frac{1}{t}\,dt$, one would need to still show that $\exp(x)=(e)^x$, which is not directly evident!
Comment: does this definition ensure that $e^x$ and $\ln x$ are inverses?
Comment: See [THIS](https://en.wikipedia.org/wiki/Characterizations_of_the_exponential_function) and [THIS](https://paramanands.blogspot.com/2014/05/theories-of-exponential-and-logarithmic-functions-part-3.html#.W9TWx_ZFxPY), [THIS](https://paramanands.blogspot.com/2014/05/theories-of-exponential-and-logarithmic-functions-part-2_10.html#.W9TXO_ZFxPY), and [THIS](https://paramanands.blogspot.com/2014/05/theories-of-exponential-and-logarithmic-functions-part-1.html#.W9TXVfZFxPY).
Comment: @clathratus No, it does not. That is why they define $e^x$ to be the inverse of $\ln x $
Comment: @MarkViola how does one do so (prove that $\exp(x)=e^x$)?
Comment: @MarkViola wow, thank you. I'll look at these and tell you what I conclude

Does this proof contain circular logic?


Square Matrix example

Question: How can i find a 2x2 and 4 x 4 square matrix whose fourth power is zero but so that none of its lower power is zero.
I could find 2x2 matrix with this condition but someone can help me with the 4 x4 matrix please...
Comment: So the minimal polynomial of the matrix is $x^4$. But the minimal polynomial is a divisor of the characteristic polynomial, and the characteristic polynomial of a 2x2 matrix has degree 2. Your claim seems to be impossible.
Comment: Why don't you try making your 4x4 matrix by putting two copies of your 2x2 matrix on the diagonal and all zeros on the off diagonal.
Comment: possible duplicate of [For which ${n\in{\Bbb Z}}$ does there exist a matrix $P\in{\Bbb C}^{4\times 4}$ such that $P^n=M$?](http://math.stackexchange.com/questions/625218/for-which-n-in-bbb-z-does-there-exist-a-matrix-p-in-bbb-c4-times-4)
Answer: See my answer earlier today.
Assuming you are working over $\mathbb{R}^{n\times n}$ or $\mathbb{C}^{n\times n}$ you always have $A^n=0$ for nilpotent matrices $A$.
Answer: Although the 2x2 case is not possible the 4x4 case is, which I think is the point of the exercise. Look into the Cayley - Hamilton theorem, minimal polynomials, and nilpotent matrices. In the mean time consider...
 \begin{bmatrix} 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 \end{bmatrix}
Comment: Also:

$$\begin{bmatrix} 0 & a & 0 & 0\\ 0 & 0 & a & 0\\ 0 & 0 & 0 & a\\ 0 & 0 & 0 & 0 \end{bmatrix}$$

with $a\in\Bbb R$.

Square Matrix example


Prove this is a subgroup: Subset of $S(A)$ consisting of all the permutations $f(a) = a$

Question: Let $A$ be a set and $a \in A$. Let $G$ be the subset of $S(A)$ consisting of all the permutations $f$ of $A$ such that $f(a)=a$. Prove that $G$ is a subgroup of $S(A)$.
I really have no clue how to go about this other than needed to prove that $G$ is closed and contains it's inverse.
Answer: The identity permutation fixes $a$, and so is in $G$. If $f,g$ fix $a$, then $(fg)(a)=f(g(a))=f(a)=a$, so $fg$ fixes $a$. Therefore, $G$ is closed under multiplication. If $f$ fixes $a$, then $a=f^{-1}(f(a))=f^{-1}(a)$, so $f^{-1}$ fixes $a$. Therefore, $G$ is closed under inversion.
Answer: You may check the subgroup criterion — $H$ is a subgroup of $G$ iff $H$ is non-empty and for every $x, y \in H, \, xy^{-1}\in H$.


If there is no censoring, can be the naive 3rd quantile different from the one calculated with from the Kaplan-Meier?

Question: I know, that the median survival time calculated from the Kaplan-Meier estimator is equal to the "naive" descriptive median of the survival time when no censoring in data occurs.
Does it apply also to the other quantiles, like the 3rd quantile? Is this possible that they differ, if no censoring occurs and all subjects experience the event?
<code>> quantile(d$time)
     0%     25%     50%     75%    100%
 2.5000  3.1375  4.3050 11.3700 71.4200

> km  <- survfit( Surv(time, event) ~ 1, data = d, conf.type = "log-log")
>
> quantile(km)
$quantile
    25     50     75
 3.120  4.305 12.140
</code>
No censoring:
<code>> d %>% count(event)
  event  n
1     1 86
</code>

EDIT:
OK, got it, thanks to @Frank Harrell
I should use the empirical CDF with averaging at discontinuities:
<code>> quantile(km)$quantile
    25     50     75
 3.120  4.305 12.140

> quantile(d$time, type=2)
    0%    25%    50%    75%   100%
 2.500  3.120  4.305 12.140 71.420
</code>
Answer: There are multiple definitions of sample (and population, in case of discreteness) quantiles.  If you use the empirical cumulative distribution function definition (which is not a weighted average of two estimates) this agrees fully with Kaplan-Meier under no censoring, because K-M is precisely one minus the empirical cumulative distribution function.  Note that sample quantiles are noisy estimates --- even more so with censoring which lowers the effective sample size.
Comment: Thank you. Now it all agrees. But please, tell me, when I report the survival data with no censoring, and use R, which by default uses type 7 (or SAS, uses type 3), should I always report the type 1 instead? Or report the one from the survival estimator? Because now I have two set of numbers, describing the same, but not exactly the same. This confuses my readers... Should I always report the type 1 (empirical CDF) quantiles instead of the default type 7?
Comment: I'm sorry, it's type 2, with averaging at discontinuities. This is not taught in typical textbooks to use type 2 quantile, most of my colleagues don't even know it exists. And we get discrepancies with Kaplan-Meier. Should we always summarize our data with type 2? So why R by default uses type 7?
Comment: Use empirical CDF if you wish to compare to Kaplan-Meier.


Multinomial logit: mlogit vs statsmodels

Question: I am doing a comparison between mlogit in R and statsmodels in python and have had trouble getting them to produce the same result. I'm wondering if the difference is a result of libraries or I am specifying something incorrectly. Any help would be appreciated.
I am using the "TravelMode" dataset to test the two.
In R:

> library("mlogit")
> library("AER")
> data("TravelMode", package="AER")
> write.csv(TravelMode, "travelmode.csv")
> TM <- mlogit.data(TravelMode, choice = "choice", shape = "long",
                    chid.var = "individual", alt.var = "mode", drop.index = TRUE)
> TMlogit = mlogit(mFormula(choice ~ vcost), TM)
> summary(TMlogit)
Call:
mlogit(formula = mFormula(choice ~ vcost), data = TM, method = "nr",
    print.level = 0)

Frequencies of alternatives:
    air   train     bus     car
0.27619 0.30000 0.14286 0.28095

nr method
4 iterations, 0h:0m:0s
g'(-H)^-1g = 0.000482 #'
successive function values within tolerance limits

Coefficients :
                    Estimate Std. Error t-value  Pr(>|t|)
train:(intercept) -0.3885180  0.2622157 -1.4817 0.1384272
bus:(intercept)   -1.3712065  0.3599380 -3.8096 0.0001392 ***
car:(intercept)   -0.8711172  0.3979705 -2.1889 0.0286042 *
vcost             -0.0138883  0.0055318 -2.5106 0.0120514 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Log-Likelihood: -280.54
McFadden R^2:  0.011351
Likelihood ratio test : chisq = 6.4418 (p.value = 0.011147)

In statsmodels:

> import pandas as pd
> import statsmodels.formula.api as smf
> TM = pd.read_csv('travelmode.csv')
> TM = pd.concat([TM, pd.get_dummies(TM['mode'])], axis=1)
> TMlogit = smf.mnlogit('choice ~ train + bus + car + vcost -1', TM)
> TMlogit_fit = TMlogit.fit()
Optimization terminated successfully.
         Current function value: 0.550273
         Iterations 6
> TMlogit_fit.summary()
<class 'statsmodels.iolib.summary.Summary'>
"""
                          MNLogit Regression Results
==============================================================================
Dep. Variable:                      y   No. Observations:                  840
Model:                        MNLogit   Df Residuals:                      836
Method:                           MLE   Df Model:                            3
Date:                Thu, 17 Mar 2016   Pseudo R-squ.:                 0.02145
Time:                        15:04:48   Log-Likelihood:                -462.23
converged:                       True   LL-Null:                       -472.36
                                        LLR p-value:                 0.0001497
=================================================================================
y=choice[yes]       coef    std err          z      P>|z|      [95.0% Conf. Int.]
---------------------------------------------------------------------------------
train            -0.3249      0.172     -1.891      0.059        -0.662     0.012
bus              -1.4468      0.205     -7.070      0.000        -1.848    -1.046
car              -0.7247      0.157     -4.603      0.000        -1.033    -0.416
vcost            -0.0105      0.002     -6.282      0.000        -0.014    -0.007
=================================================================================
"""

I would think the values of the coefficients would be closer to each other when comparing between the two models. Any help would be appreciated.
Comment: Those two are **not** the same model. For a recent discussion about the status of discrete choice models for statsmodels see the thread of https://groups.google.com/d/msg/pystatsmodels/IoQckMN32zA/_qBslon1BgAJ  and the newly published package `pylogit` that reproduces R's mnlogit results.
Comment: @user333700, why not post an answer explaining how & why the 2 models are not the same?
Comment: FWIW, this strikes me as potentially on topic. (It may well be off topic, but I can't tell.)
Comment: @gung I was hoping somebody else provides an explanation because I'm short in time right now. A brief answer is here http://stackoverflow.com/questions/34548375/multinomial-conditional-logit-regression-why-statsmodel-fails-on-mlogit-package/34566565#34566565 In Stata the R's mnlogit equivalent is asclogit and the statsmodels equivalent in Stata is mlogit, as far as I know.
Comment: @user333700 I was able to achieve identical results using pylogit, thanks.
Answer: I'm the creator of pylogit. Thanks for using my package!
To answer your question, the differences in estimation results comes from differences in the way choice data is represented in statsmodels versus mlogit. The TravelMode dataset is in long format natively (i.e. when you wrote it to csv). I.e. it has one row per alternative per observation. However, statsmodels assumes ones data is in wide format, with one row per observation. Thus there are 4 times as many "observations" in the statsmodels model (840) than there are in your mlogit model. Try calling length(unique(TravelMode$individual)).
Moreover, your variables (pd.get_dummies(TM['mode'])) in your statsmodel model do not represent alternative specific constants, but are simply the alternative identifiers for each row of the long-format data. This is in contrast to the intercepts that were estimated in the mlogit model.
Comment: timothyb0912 can you provide an example where `pylogit` results are replicated using `statsmodels`? Maybe for the simplest case of multinomial logit
Comment: @Gigi

Example 1:
https://github.com/timothyb0912/pylogit/blob/master/examples/notebooks/mlogit%20Benchmark--Train%20and%20Fishing.ipynb

Example 2:
https://github.com/timothyb0912/pylogit/blob/master/examples/notebooks/mlogit_Benchmark--Heating.ipynb
Comment: @Gigi sorry for my earlier response. I thought you wanted a replication from mlogit in R. I don't have any replications using statsmodels because that package didn't support the use cases I needed. In fact, when I first created pylogit, I tried to have it added to statsmodels (https://groups.google.com/g/pystatsmodels/c/IoQckMN32zA/m/_qBslon1BgAJ)

I can create one using https://www.statsmodels.org/stable/examples/notebooks/generated/discrete_choice_overview.html#Multinomial-Logit, but it may take me a while to prioritize it.
I'm happy to take a pull-request in the meantime with a notebook.
Comment: Got it! thanks for your response.


How to create a full project on drupal.org?

Question: I have created a custom module in Drupal 7. And now I want to contribute this module via drupal.org. For this I have created my account on drupal.org and created a sandbox project.
Now I am not getting how to make it full project.
Answer: For promoting the sandbox module to full project requires for going through a one time review process.
Check:
Apply for permission to create full projects
Before creating an issue for the promotion, make sure you go through the project application checklist to get good reviews.
Answer: Your starting point is https://www.drupal.org/project/projectapplications
You'll need to create an issue according to the instructions on this page. People will review (automated and manually) to check if this module is good for contrib.
Comment: how to get Git clone command for the sandbox .?
Comment: When you visit your sandbox page, it will have a tab 'Version control'. This will contain your GIT clone command. I think you just have to leave out your username. Ex: email@example.com: remove 'user@'.
Comment: There is a maintainer checkbox next to the version drop-down on the 'Versions control' page. This toggles the private and public git clone commands. (But is is basically removing the user@ part)
Answer: To promote your sandbox project to full project, you will have to apply for permission to create a full project as described here in drupal docs: https://www.drupal.org/node/1011698 .
After getting permission you will be able to promote your sandbox to a full project.
Here are complete screenshots: https://www.drupal.org/node/1068952.
Answer: As of 2017/03/07, users do not need to go through the Project Application Review process to promote a project.  With this change, people without the git-vetted status can promote one sandbox project to full project status.  See also the change record:

Strong signals about security advisory coverage are available on
  project pages on Drupal.org, and in the updates.xml that is served by
  Drupal.org for core to consume. There is also now a field for project
  maintainers to opt into security advisory coverage.
This means that we're now able to open the gates, to allow any user
  who has accepted the Git repository usage policy to promote their
  sandbox projects to full projects with releases.
At the same time as we make this change, we'll be repurposing the
  'git-vetted' user role as a 'may opt-into security coverage' role. The
  existing project application process move from a gate on promoting
  full projects to the gate for opting in to security advisory coverage.
  That process will be further refined by various stakeholders in follow
  ups.
We'll be updating the documentation to reflect this change in process
  as well.
Answer: An alternative approach to "create a full project on drupal.org", is to investigate the existing (+17K) contributed modules, and narrow them down to projects with status like:

Seeking new maintainer (685 hits).
Unsupported (1.524 hits).

From the search results that you get, verify if there is anything that has a "namespace" (= the machine name of your module) that might fit (or is close enough) to what your (new) module is about.
Then request the module's ownership to be treansfered, using these steps (in specified order):

Contact the module owner via the contact form of that owner on Drupal.org, asking for the ownership to be transferred.
If current owner indicates to agree with a transfer, or if after 2 weeks you have not received any response to step 1, then file an issue in
the Drupal.org project ownership project (component = Ownership transfer), to request the "ownership to be transferred" (include relevant communication from step 1 to motivate your request). Issue # 2367923 is an example of such issue.
The people handling the request from step 2 will then also try to contact the current owner (if you didn't get a reply to step 1.). And after a grace period of (about) 2 weeks, the project's ownership will be changed to you (unless there was some type of feedback from the current owner to not do so).
Do whatever you want to do with the module for which you became the new owner, without any review process involved. But make sure to:

give credit to the previous owner somehow.
NOT destroy any (GIT) history of the old version of the module.

The above period works fine, though it takes a little time (a few weeks at max) to complete all the steps ... And it has the advantage (I think) that you contribute a very little bit to reduce the amount of abonded-looking contributed modules.
PS: There are occasions where the current maintainer responds/reacts with something like "Hm, somebody interested in contributing to a 2nd live to a module I started ... how about I only grant co-maintainer status instead of transferring module ownership?". If that happens, then "you" have to decide if you yes/no are willing to accept that. A possible compromise in that case could be "how about we turn the table: I become owner, and make you (current owner) a co-maintainer".
Comment: This is great info. I wonder if it should be attached to a question specifically asking "Are there alternatives to applying for full project status?" instead of this one. If the question doesn't already exist, might not be a bad idea to create it. Just a thought.
Comment: Thanks for the kudos, you make me doubt if I should do so. I find it strange to answer my own question. I know you can do so, but it gives me the impression like "look how smart I am, in case you have a question like so, this is the answer to it" ... no? Maybe a question like "What are the pros and cons of taking over an existing contributed module?" is something I might consider (with a variation of my answer here ...).
Comment: :) I've thought about that, and have yet to do it myself. But when you ask a question there is a prompt right there that says, "Answer your own question – share your knowledge, Q&A-style". That seems rather encouraging, no? And there is also this: [Help Center: Can I answer my own question?](http://stackoverflow.com/help/self-answer). It makes perfect sense to me, and with D8 on the horizon it would be great if more people would share in this way instead of waiting to be asked.
Comment: I just read it through. Had no idea it was such a sensitive thing, or that the PAR system is as broken as it is. No doubt the offer from kreynen to transfer projects to others didn't help (eep). On the up side, maybe the PAR admins have been given a little push to improve things. It would also be nice to see more effort behind cleaning up existing projects - maybe an Adopt-a-Project program. :) Where is this community wiki that it's been moved to? I'm not familiar with how that works.
Comment: @othermachines Thx for your feedback. About your "Adopt-a-Project": too late ... read my comments I added to the 2 newests answers there (i.e. the "Open Letter" link). About community wiki: http://drupal.stackexchange.com/help/privileges/community-wiki .. So all that's needed is that little checkbox bottom right if you create a new post. "I" did not ever mark my question (or answer) as such (a moderator did). PS: I just realized that about 40% of all my questions were converted to a wiki post also ... I try to understand "why" ...


Inserir duas checkbox em campos diferentes em mysql

Question: Tenho este código que cria esta tabela com os dois primeiros campos já preenchido de padrão:
<?php
$result_cursos = "SELECT nome,
                         Quarto

FROM centrodb.utentes

WHERE descricaovalencia = 'LAR' AND nome <> 'CLASSE' AND ativo = '1' ORDER BY nome ASC;";

    $resultado_cursos = mysqli_query($conn, $result_cursos);

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= 'Utente	';

$tabela1 .= 'Quarto	';

$tabela1 .= 'Data Registo	';

$tabela1 .= 'Micção	';

$tabela1 .= 'Dejecção	';

$tabela1 .= 'Colaborador	';

$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .='
';

    while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {

$tabela1 .= '
';

$tabela1 .= ' <input type="text" size="45" name= "NomeUtente[]" id= "NomeUtente" value="'.$rows_cursos['nome'].'">	';

$tabela1 .= ' <input type="text" size="1" name= "Quarto[]" id= "Quarto" value="'.$rows_cursos['Quarto'].'">	';

$tabela1 .= ' <input type="datetime-local" name= "DataRegisto[]" id= "DataRegisto">	';

$tabela1 .= ' <input type="checkbox" name= "Miccao[]"  value="Realizado"> Realizado <input type="text" name= "Tipo1[]" id= "Tipo1" size="30" >	';

$tabela1 .= ' <input type="checkbox" name= "Dejeccao[]" value="Realizado"> Realizado <input type="text" name= "Tipo[]" id= "Tipo" size="30" >	';

$tabela1 .= ' <select name="Colaborador[]" id="Colaborador">
   <option value="ANA CRISTINA MACHADO FERREIRA">ANA CRISTINA MACHADO FERREIRA</option>
   <option value="ANA PAULA PEREIRA BARBOSA">ANA PAULA PEREIRA BARBOSA</option>
   <option value="ANA PAULA SANTOS FLORES SILVA GONÇALVES">ANA PAULA SANTOS FLORES SILVA GONÇALVES</option>
   <option value="ANABELA OLIVEIRA FERNANDES DE MOURA CAMPOS">ANABELA OLIVEIRA FERNANDES DE MOURA CAMPOS</option>
   <option value="CLARINDA ROSA GONÇALVES MOREIRA FERNANDES">CLARINDA ROSA GONÇALVES MOREIRA FERNANDES</option>
   <option value="EUNICE MIRIAM MARTINS AZEVEDO">EUNICE MIRIAM MARTINS AZEVEDO</option>
   <option value="FERNANDA ALMEIDA">FERNANDA ALMEIDA</option>
   <option value="FERNANDA MARIA VASQUES MENDONÇA PEREIRA">FERNANDA MARIA VASQUES MENDONÇA PEREIRA</option>
   <option value="FLORINDA MARIA SANTOS CARDOSO DA COSTA PINTO">FLORINDA MARIA SANTOS CARDOSO DA COSTA PINTO</option>
   <option value="GEORGINA MARIA MATOS DE CARVALHO ARAÚJO">GEORGINA MARIA MATOS DE CARVALHO ARAÚJO</option>
   <option value="ISABEL MARIA GONÇALVES RODRIGUES GRAÇA">ISABEL MARIA GONÇALVES RODRIGUES GRAÇA</option>
   <option value="ISABEL MARIA MATOS MEIRELES BARROS BARGE">ISABEL MARIA MATOS MEIRELES BARROS BARGE</option>
   <option value="JOANA RAQUEL COSTA LOPES">JOANA RAQUEL COSTA LOPES</option>
   <option value="LUISA DA CONCEIÇÃO COELHO DE ALMEIDA">LUISA DA CONCEIÇÃO COELHO DE ALMEIDA</option>
   <option value="MARIA ALICE SANTOS MAIA">MARIA ALICE SANTOS MAIA</option>
   <option value="MARIA BERNADETE MONTEIRO MOREIRA">MARIA BERNADETE MONTEIRO MOREIRA</option>
   <option value="MARIA CONCEIÇÃO ALMEIDA MARTINHO DIAS">MARIA CONCEIÇÃO ALMEIDA MARTINHO DIAS</option>
   <option value="MARIA DE JESUS BENTO MENDES">MARIA DE JESUS BENTO MENDES</option>
   <option value="MARIA HELENA TEIXEIRA FERREIRINHA">MARIA HELENA TEIXEIRA FERREIRINHA</option>
   <option value="MARIA JOSÉ NOGUEIRA RODRIGUES PEREIRA">MARIA JOSÉ NOGUEIRA RODRIGUES PEREIRA</option>
   <option value="MARIA MANUELA MARTINS MORENO">MARIA MANUELA MARTINS MORENO</option>
   <option value="MONICA ALEXANDRA HORA GOMES MEDEIROS">MONICA ALEXANDRA HORA GOMES MEDEIROS</option>
   <option value="MÁRIO ANTÓNIO MOREIRA FERREIRA">MÁRIO ANTÓNIO MOREIRA FERREIRA</option>
   <option value="PATRÍCIA ALEXANDRA SILVA INÁCIO">PATRÍCIA ALEXANDRA SILVA INÁCIO</option>
   <option value="PAULA CRISTINA RIBEIRO DA SILVA RODRIGUES">PAULA CRISTINA RIBEIRO DA SILVA RODRIGUES</option>
   <option value="PAULA MARIA RODRIGUES DA SILVA">PAULA MARIA RODRIGUES DA SILVA</option>
   <option value="PEDRO MONTEIRO">PEDRO MONTEIRO</option>
   <option value="SILVIA MANUELA DA SILVA BORGES">SILVIA MANUELA DA SILVA BORGES</option>
</select>	';

$tabela1 .= '
';
    }
$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= '
';

echo "<form method='POST' action=''>";
echo $tabela1;

echo "<input type='submit' name='registar' value='Registo'>";

echo "</form>";

echo "
";
echo "
";

?>

Depois de criar a tabela, tenho este código para inserir na tabela da base de dados. Só pode inserir a linha da tabela que eu preencher.
<?php
if(isset($_POST['registar']))
{
for ($i=0;$i<count($_POST["NomeUtente"]);$i++) {
    $utente = $_POST['NomeUtente'][$i];
    $quarto = $_POST['Quarto'][$i];
    $data = $_POST['DataRegisto'][$i];
    $miccao = $_POST['Miccao'][$i];
    $tipo1 = $_POST['Tipo1'][$i];
    $dejeccao = $_POST['Dejeccao'][$i];
    $tipo = $_POST['Tipo'][$i];
    $colaborador = $_POST['Colaborador'][$i];

    $sql = "INSERT INTO registoMiDe (NomeUtente, Quarto, DataRegisto, Miccao, Tipo1, Dejeccao, Tipo, Colaborador) VALUES ('$utente', '$quarto', '$data', '$miccao', '$tipo1', '$dejeccao', '$tipo', '$colaborador')";
$res = mysqli_query($conn,$sql);

}
}
?>

O problema é que quando preencho só uma checkbox em cada linha como mostro na imagem:

ele insere oos valores da checkbox na mesma linha e não pode. Na primeira só devia inserir o valor da checkbox da micção e na segunda o valor da checkbox da dejecção.
Mostro como estaá a preencher erradamente na tabela da base de dados na imagem:
Comment: não, o meucódigo está todo aqui. O problema é que o código só faz o registo das checkbox correto na primeira  linha da tabela que mostro ao utilizador. Depois dessa linha ou marco as duas checkbox ou então insere as duas colunas em branco
Answer: O comportamento do input type="checkbox" do html é enviar para o server-side apenas os checkboxes marcados
Da forma que você está fazendo ao enviar o formulário:

vai retornar
Array ( [0] => ABEL DE FIGUEIREDO PINTO [1] => ADELINO VALE LOUREIRO )
Array ( [0] => 16 [1] => 30 )
Array ( [0] => 2018-03-31T15:00 [1] => 2018-03-31T15:00 )
Array ( [0] => Realizado )  //faltando [1]
Array ( [0] => Realizado )  //faltando [1]
Array ( [0] => MARIA JOSÉ NOGUEIRA RODRIGUES PEREIRA [1] => MARIA JOSÉ NOGUEIRA RODRIGUES PEREIRA )

Portanto ao realizar o loop for as sql serão:
para $i=0
INSERT INTO registoMiDe (NomeUtente, Quarto, DataRegisto, Miccao, Tipo1, Dejeccao, Tipo, Colaborador)
VALUES ('ABEL DE FIGUEIREDO PINTO', '16', '2018-03-31T15:00', 'Realizado', '', 'Realizado', '', 'MARIA JOSÉ NOGUEIRA RODRIGUES PEREIRA')

para $i=1
INSERT INTO registoMiDe (NomeUtente, Quarto, DataRegisto, Miccao, Tipo1, Dejeccao, Tipo, Colaborador)
VALUES ('ADELINO VALE LOUREIRO', '30', '2018-03-31T15:00', '', '', '', '', 'MARIA JOSÉ NOGUEIRA RODRIGUES PEREIRA')

Você obterá sucesso dessa forma
PHP
if(isset($_POST['registar']))
{
$NomeUtente = $_POST['NomeUtente'];

for ($i=0;$i<count($_POST["NomeUtente"]);$i++) {
    $utente = $NomeUtente[$i];
    $quarto = $_POST['Quarto'][$i];
    $data = $_POST['DataRegisto'][$i];
    $miccao = $_POST['Miccao'][$i];
    $tipo1 = $_POST['Tipo1'][$i];
    $dejeccao = $_POST['Dejeccao'][$i];
    $tipo = $_POST['Tipo'][$i];
    $colaborador = $_POST['Colaborador'][$i];
    ..............................

e no formulário
no while incremente um contador concatenando o $j exceto em NomeUtente[]
$j=0;
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {

$tabela1 .= '
';

$tabela1 .= ' <input type="text" size="45" name= "NomeUtente[]" id= "NomeUtente" value="'.$rows_cursos['nome'].'">	';

$tabela1 .= ' <input type="text" size="1" name= "Quarto['.$j.']" id= "Quarto" value="'.$rows_cursos['Quarto'].'">	';

$tabela1 .= ' <input type="datetime-local" name= "DataRegisto['.$j.']" id= "DataRegisto">	';

$tabela1 .= ' <input type="checkbox" name= "Miccao['.$j.']" value="Realizado"> Realizado <input type="text" name= "Tipo1['.$j.']" id= "Tipo1" size="30" >	';

$tabela1 .= ' <input type="checkbox" name= "Dejeccao['.$j.']" value="Realizado"> Realizado <input type="text" name= "Tipo['.$j.']" id= "Tipo" size="30" >	';

$tabela1 .= ' <select name="Colaborador['.$j.']" id="Colaborador">
....................
....................

$j++;
}


How to 'introduce' view & controller in MVC pattern?

Question: Using the MVC pattern in a desktop application, what's a good approach to introducing a view to its respective controller, and vice-versa? E.g., should you use constructor injection to give the view its controller, then have the view call a setView method on the controller and pass itself as the argument?
(Question isn't specific to any framework/platform.)
Answer: Views should be as dumb as possible.  They shouldn't know about, or rely on having specific controllers instantiate them.  At best they should have access to some kind of base controller class reference that is handed to them upon construction, usually as part of the "view data" object which wraps the Model to be used as well.
Your controller should be responsible for instantiating the view, giving the view the model it will be displaying, and returning the view's result.  The view shouldn't be calling back into the controller to tell it what to return, as this gives control of the logical flow to the View, which isn't really MVC-like.
Comment: Thanks! About the first part, when would you want to give the view the base controller class reference, rather than just the model?
Comment: You would give it both.  Depending on your implementation, it wouldn't be *required* to give it a controller reference, but generally the controller would have access to the initial request data, which your view might need. For example in ASP.Net MVC, each View gets passed a model, but there is also a well-known structure called "ViewData" which holds a "ControllerContext" object, which you can access if your view needs to poke around at request data.
Comment: How, then, does, say, in a GUI application, button click commands get to the model in this setup? Aren't buttons part of the views (windows, etc.)?


Lilypond: transpose a sequence to modes with different intervallic structure

Question: I am looking for a Lilypond function to transpose sequences of notes between modes that have different intervallic structure (e. g. from major to harmonic minor). My assumption is that the modes have identical number of pitches.
For example, I'd like to transpose this C-major sequence:
music = { c b d e}

to relative harmonic minor key, expecting these notes as the output:
a gis b c

If use the \transpose function I will get transposition to A major:

\transpose c' a {\music}
% result: a gis b cis

If I use the \modalTranspose function I will get transposition to A natural minor (not harmonic minor, as I expect):

majorScale = { \relative { c' d e f g a b  } }
\modalTranspose c' a \majorScale { \music }
% result: a g b c

It does not help to define a harmonic minor scale in the same way as majorScale, pitches that do not overlap will be left unmodified.
Is there a way to do this kind of transposition using built-in functions? Or do you perhaps have an example of a custom function for this?
Answer: \transpose will shift all pitches while keeping the relations between all pitches the same. \modalTranspose will not change the mode, but simply transpose to a specific different step while keeping the scale.
What you want is basically changing the scale while keeping the steps. This could be some somewhat like this:
transposeScale =
#(define-music-function (scaleA scaleB music) (ly:music? ly:music? ly:music?)
   (let* ((scaleA (ly:music-property scaleA 'elements))
          (scaleB (ly:music-property scaleB 'elements))
          (scaleA (map (lambda (x) (ly:music-property x 'pitch)) scaleA))
          (scaleB (map (lambda (x) (ly:music-property x 'pitch)) scaleB))
          (rootsA (map ly:pitch-notename scaleA)))
   (map-some-music
    (lambda (m)
      (let ((p (ly:music-property m 'pitch)))
        (if (not (null? p))
            (let* ((nn (ly:pitch-notename p))
                   (oct (ly:pitch-octave p))
                   (alt (ly:pitch-alteration p))
                   (pos (list-index (lambda (x) (= x nn)) rootsA))
                   (p2 (list-ref scaleA pos))
                   (oct2 (ly:pitch-octave p2))
                   (alt2 (ly:pitch-alteration p2))
                   (p3 (list-ref scaleB pos))
                   (new-pitch (ly:pitch-transpose p3 (ly:make-pitch (- oct oct2) 0 (- alt alt2)))))
              (ly:music-set-property! m 'pitch new-pitch)
              m)
            #f)))
    music)
   music))

\transposeScale { c d e f g a b } { c d es f g as b } { c' d' e' d' g' gis' a' b' c'' }


Trouble for logining in to Ubuntu

Question: I'm finding a trouble in root local host login in Ubuntu . I am using Ubuntu for the first time in my new laptop Acer aspire 5 A515-51 how could I over come it.
Answer: In order to login to root user, you need to login with local user first. You must be able login using your standard user credentials. After your login is successful with standard user, just open the terminal ( type CTRL+ALT+T to open terminal) and type
sudo su
Hit enter and it will ask you for password, enter the same password you used for login and it's done.
You will have successfully logged in as root.
Comment: Root login using GUI is disabled in Ubuntu. You should have standard user login credentials in order to login
Comment: This was the first time I'm loging in to Ubuntu
Answer: You cannot login as root in Ubuntu. If you want to execute commands with root privileges use sudo.
If you require root shell use

su -
Comment: That was not even working
Comment: what error you are getting?

Trouble for logining in to Ubuntu


How to use roles in .NET MVC Core

Question: I have tried for days now to implement roles in a MVC project. I have started a new project and chosen Authentication to "Individual user account". I added the [Authorize] to HomeControllers Indexpage and everything works. To add a role i included:
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

to startup.cs ->ConfigureServices
and then added a call to following functions from startup->Configure
private async Task CreateRole(IServiceProvider serviceProvider)
{
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    IdentityResult roleResult;
    roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}

private async Task SetUserAdmin(string username, IServiceProvider serviceProvider)
{
    var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
    IdentityUser user = await UserManager.FindByEmailAsync(username);
    await UserManager.AddToRoleAsync(user, "Admin");
}

this will create the role "Admin" and bind it to a specific user.
When i look at the table in the db via:
select * from AspNetRoles
select * from AspNetUsers
select * from AspNetUserRoles

The tables is populated and linked to eachother but when i use [Authorize(Roles="Admin")] error page 401 will appear, but when i read out the roles for the user via:
var roles = await UserManager.GetRolesAsync(await UserManager.FindByEmailAsync(username));

It will return the value "Admin".
What can be the problem?
Big thanks for any suggestions!
Answer: How did you add Identity in the startup file?
I think it's going wrong with services.AddIdentity.
I use:
services.AddIdentity<IndentityUser, IdentityRole>(options => options.Stores.MaxLengthForKeys = 128)
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

This is a known bug for .Net Core 2.1 .net core identity 2.1 role authorize not working
Should be solved in 2.2
Comment: Thanks for the reply, i have basically scaffolded in the identity and in services.AddDefaultIdentity added .AddRoles(). The database seems to be correct, but [Authorize(Roles="Admin")] brings me to 401 page, while [Authorize] works fine.
Comment: Which version of .Net Core are you using? Just for troubleshooting try services.AddIdentity() instead of services.AddDefaultIdentity().AddRoles(). Have you specified the AddEntityFrameworkStores?
Comment: I am using .Net Core 2.1. The change from AddDefaultIdentity to AddIdentity fixed the problem with reacting to [Authorize(roles="Admin")], but now the program tries to find the loginpage at Account/Login instead of Identity/Account/Login. Plus that the register doesnt work due to the IEmailSender... I cant seem to find a walkthrough online to this problem, even though it surely must be a common thing to implement? Do you know where this can be found so i can understand whats happening?
Comment: Thought so, this is a known bug: https://stackoverflow.com/questions/52526186/net-core-identity-2-1-role-authorize-not-working If it's possible I would suggest updating to .Net Core 2.2
Comment: Finally it works! Your link and C-Berber:s post fixed the problem. Big thanks for the help!

How to use roles in .NET MVC Core


Heat Equation with Neumann condition

Question: Suppose u solves $u_t-u_{xx} = 16u$ on the interval $(0, \pi),$ with the homogenous Neumann condition $u_x=0$ at $x=0,\pi$. Characterize the initial data $u_0=u(x,0)$ for which $u(x,t)$ stays bounded as $t \rightarrow\infty$.
I am not sure how to approach this PDE, thus any help/guidance is highly appreciated. Thanks!
Comment: Search for heat equation with damping term.
Comment: I changed $u_t$-$u_{xx}$ = 16 u to $u_t-u_{xx}=16u$ and did some other MathJax corrections. That is proper MathJax usage.
Comment: Thank you for doing that @MichaelHardy
Comment: Thank you, I am still unable to find how to approach this one. I was thinking of using separation of variables but unsure.
Comment: If you are thinking of using separation of variables, then try it and see how it goes.
Comment: https://math.stackexchange.com/questions/1477444/condition-on-ux-0-so-that-ux-t-is-bounded-in-a-heat-equation-with-neuman?rq=1
Answer: $$\begin{cases}
u_t -u_{xx} = 16u\\
u_x(0,t) = u_x(\pi,t)=0\\
u(x,0) = u_0
\end{cases}$$
Let $u(x,t) = X(x)T(t)$ and $\frac{dT(t)}{dt} = \mathring{T}(t)$
Therefore,
$u_t -u_{xx} = 16u$ becomes $\frac{\mathring{T(t)}}{T(t)}-16 = \frac{X''(x)}{X(x)} = \lambda$.
Here, $\lambda$ is a constant because "[t]he left hand side is independent of t. The right hand side is independent of x. The two sides are equal. So
both sides must be independent of both x and t and hence equal to some constant, say [$\lambda]"$. (I actually still don't understand this sentence... If anyone can help me, please! )
$T(t):$ $T(t) = ce^{(16+\lambda )t}$ for some constant $c$.

$X(x): $
There are three cases - $\lambda = 0 , \lambda > 0, \lambda < 0$.
i) According to my experience, it $\frac{X''(x)}{X(x)} = \lambda > 0 $ ususally yields trivial solution. aka,  $X(x) = 0$. Thus I am going to skip the calculation here. I have calculated to verify and it does result in trivial solution.
ii) $\frac{X''(x)}{X(x)} = \lambda = 0 $ yields trivial solution.
iii) $\frac{X''(x)}{X(x)} = \lambda = -\mu^2 < 0 $
This is the fun part.
Solving the second order DE, $X(x) = A\cos (\mu x) + B\sin(\mu x)$.
Plugging in the boundary conditions, $B=0, A = a_n $when $\mu=n=1,2,3,...$
Therefore, $$u(x,t) = \sum^\infty_{n=1}a_n \cos (n\pi) e^{(16-n^2)t}$$
Now, we can use Fourier series and initial condition to solve for $a_n$.
$$a_n = \frac{2}{\pi}\int^{\pi}_0 u_0 \cos(n\pi)dx= \frac{2u_0}{\pi}\frac{(-1)^n-1}{n}$$
$$b_{2k-1} = \frac{2u_0}{\pi}\frac{-2}{2k-1}$$
Therefore, the final solution is, $$u(x,t) = \frac{-4u_0}{\pi}\sum^\infty_{k=1}\frac{cos(2k-1)\pi e^{(16-(2k-1)^2)t}}{\pi (2k-1)}$$
Comment: $a_n = \frac{2}{\pi}\int^{\pi}_0 u_0 \cos(n\pi)dx= \frac{2u_0}{\pi}\frac{(-1)^n-1}{n}$ appears wrong: there's no $x$ is the $\cos$...

Heat Equation with Neumann condition


Find all triplets $(x,y,z)\in\mathbb{R}^3$

Question: Find all triplets $(x,y,z)\in\mathbb{R}^3$ such that
\begin{align*}
x^2-yz &= |y-z|+1, \\
y^2-zx &= |z-x|+1, \\
z^2-xy &= |x-y|+1.
\end{align*}
Solution: Interchanging $x,y,z$ by $(-x,-y,-z)$ we may w.l.o.g. assume that $x+y+z \ge 0$.
This is symmetric in $x,y,z$ so we may w.l.o.g. suppose that $x \ge y \ge z$ so that the system reads as
\begin{align*}
x^2-yz&=y-z+1\\
y^2-zx&=x-z+1\\
z^2-xy &=x-y+1
\end{align*}Subtracting the second from the first equation we find that $(y-z)(x+y+z-1)=0$ so that $y=z$ or $x+y+z=1$.
Subtracting the third from the second equation we find that $(x-y)(x+y+z+1)=0$ so that $x=y$ or $x+y+z=-1$.
Since clearly $x=y=z$ is not a solution, we must have $x=y$ and $x+y+z=1$.
Hence $x=-2y-1$ and the first equation is $x^2-y^2=1$ so that we find $(2y+1)^2-y^2=1$ and hence $y=0$ or $y=-\frac{4}{3}$.
However $y=0$ implies $x=-1<y$ which contradicts our assumption so the only solution in this case is $x=\frac{5}{3}, y=z=-\frac{4}{3}$.
Of course this gives rise to $6$ solutions by permuting the variables and introducing signs again.
Any other solutions for this system? I really think there is another method of solving (which may be elegant)
Answer: I think your method is probably best. The idea of fixing $x+y+z$ as non-negative and making $x$ the largest variable is an excellent method of reducing the number of cases.
However there are errors (typos?) in your solution. You can see this from your final solution, which contrary to your assumption actually has $x+y+z$ negative.
I wonder if you renumbered your equations when writing up your answer since right at the start you say "Subtracting the second from the first equation" when it's actually "Subtracting the third from the second equation". Later in the solution you have $y=x$ but then seem to switch to $y=z$.


Load an activitiy based on the mobile´s date; Eclipse app

Question: I would like to know if it is possible to load an activity based on the mobile´s date.
Ex. On 01 of January it loads Activity1,
    on 02 of January it loads Activity2,
    and so on.
(Edit)
HI.
I just started to learn java and android, i am still at a very low level programming.
I have managed to create a very simple app with various activities.
In this app, I would like to have an Activity in which other Activities are loaded automaticaly depending on the the day of the year.
I tried to do this but as I am just a beginner, I would need examples based the names of my activities (Main, One and two) and also for day 1 and 2 of Frebruary. So that I can understand better.
As I understood 1 of February would mean"32" and 2 of February would mean"33"
So if i have 3 Activities:
MainActivity.java, activity_main.xml, OneActivity.java, activity_one.xml and TwoActivity.java, activity_two.xml
When starting MainActivity, i would like it to load OneActivity if its is day 1 of February 2015 or load TwoActivity if its is day 2 of February 2015.
Comment: Did you try doing that? I don't see any reason of it not working.
Answer: you want to know if its possible?
YES
you did not add how, did you?
well for how you could use compareTo(Date anotherDate) .
Answer: Of course you can do this. To get the date, just use the Calendar API, like this:
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);

This will get you the day of the year. So Jan 1 will be 1, Feb 1 will be 32, and so on.
Then have an array of Strings that holds the class you want to open each day.
String[] className = {"empty because the first day is 1", "nameofClass1","nameofClass2", ... , "nameofClass365"};

Then you'll just have a Splashscreen sort of activity that will call an intent to that class.
Class<?> c = null;
if(StringClassname != null) {
    try {
        c = Class.forName(className[dayOfYear]);
        Intent intent = new Intent(this, c);
        startActivity(intent);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Comment: why an array of `String` instead of an array of `Class`?
Comment: I´m just a beginner, could you place the full code of the page as an example? I´m getting an error at"if(StringClassname != null) {".Where do I place the array of string? Where/how do I place the name of the Actovity I want to load?
Comment: I finally did it! Thank you so much. For me it wasn´t working because i hadn´t put the package plus activity name of the classes. Ex:    {"", "com.mares.marenostrum.MainActivity","nameofClass365"};


How to get only specific elements of list in racket

Question: Input:
'(("may 001" 75 72)
  ("may 002" 75 75)
  ("may 003" 70 73)
  ("june 101" 55 55)
  ("june 104" 55 54)
  ("aug 201" 220 220))

Desired output:
'(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73))

How do I achieve this? I only want the may terms.
Comment: It's important to show the desired output, but I think you need to show the original *input*, too.
Comment: output=>original output
Comment: Yes, I see that you're showing *actual* output and  *desired* output.  That's a good thing.  But what's the input?  What's the function that's producing it?  Was the original input a list of 100 elements?  How did it already get cut down to a list of 6 elements?  You're not showing us the whole problem, and you're not presenting any code that has a bug, etc.
Comment: possible duplicate of [racket/scheme filtering](http://stackoverflow.com/questions/13504302/racket-scheme-filtering)
Answer: The "normal" way of getting specific element based on their values is to use filter with a suitable predicate.
Something along these lines:
(define (may? str)
  (string=? "may" (substring str 0 3)))

(define (only-may ls)
  (filter (lambda (x) (may? (car x))) ls))

Answer: To be useful, we probably want a function that takes the name of a month and a list of records and returns a list of the matching records:
#lang racket

;; string ListOf(ListOf(String Int Int)) -> ListOf(ListOf(String Int Int))
(define (get-month target-month list-of-record)

  ;; ListOf(String Int Int) -> Boolean
  (define (record-matches? record)
    (regexp-match target-month (first record)))
  (filter record-matches? list-of-record))

Then we can use it in queries such as:
"scratch.rkt"> (get-month "may"
                          '(("may 001" 75 72)
                            ("may 002" 75 75)
                            ("may 003" 70 73)
                            ("june 101" 55 55)
                            ("june 104" 55 54)
                            ("aug 201" 220 220)))
'(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73))
"scratch.rkt"> (get-month "april"
                          '(("may 001" 75 72)
                            ("may 002" 75 75)
                            ("may 003" 70 73)
                            ("june 101" 55 55)
                            ("june 104" 55 54)
                            ("aug 201" 220 220)))
'()


Consulta Lambda

Question: tenho a seguinte consulta em T-SQL:
 SELECT TOP (60) COUNT(*) AS QTD, SUM(Duration) AS Total, AVG(Duration) AS Media, MIN(Duration) AS Menor, LEFT (TextData, 80) AS TextData
        FROM Traces WITH (nolock)
        WHERE (StartTime >= DATEADD(D, - 7, GETDATE())) AND (DataBaseName IN ('databaseName1', 'databaseName2'))
        GROUP BY TextData, DataBaseName
        HAVING (COUNT(*) > 1) ORDER BY Total DESC

Estou tentando escrever em Lambda, não gostaria de Linq, só se for o último caso.
Como montar?
tenho dúvidas quando ao LEFT e ao HAVING:
essa é minha consulta por enquanto.
 using (var ctx = new TracesEntity())
        {
            var lambda = ctx.TraceTabelas.Where(q => q.DataBaseName == "databaseName1" || q.DataBaseName == "databaseName2")
                .GroupBy(a => new { a.TextData, a.DataBaseName })
                .Select(b => new {
                                    QTD = b.Count(),
                                    Total = b.Sum(b1 => b1.Duration),
                                    Media = b.Average(b1 => b1.Duration),
                                    Menor = b.Min(b1 => b1.Duration),
                                    TextData = b.Select(b1 => b1.TextData)
                                })
                .Take(60)
                .OrderByDescending(b =>b.Total)
                .ToList();

            GridView1.DataSource = lambda;
            GridView1.DataBind();
        }

Comment: Você deveria ordenar primeiro e depois dar o `take`
Comment: Eu recomendaria muito que você mantivesse esse tipo de consulta no banco, através de `Stored Procedures` para ganhar performance na consulta ao invés de ter q fazer as relações no código assim.
Comment: lambda não tem uma perfomance boa? claro que muitas coisas já esta em stored procedure, mas não da pra criar tudo..até pq isso é uma page que é executada apenas 1 vez ao dia.
Comment: Como está o resultado até então?
Comment: textData não esta vindo..e deve estar errado outras coisas, por exemplo onde faço o having???, existe como em debug eu verificar qual a consulta ele esta montando em TSQL ?
Comment: Tem. Retire o `ToList()` e o `Take(60)`. `lambda` receberá um objeto de consulta.
Answer: Pra fazer o equivalente ao having no SQL no linq, basta colocar um Where() após o GroupBy():
using (var ctx = new TracesEntity())
{
    var lambda = ctx.TraceTabelas.Where(q => q.DataBaseName == "megacorretor" || q.DataBaseName == "stats_mega")
        .GroupBy(a => new { a.TextData, a.DataBaseName })
        .Where(group => group.Count() > 1)
        .Select(b => new {
                            QTD = b.Count(),
                            Total = b.Sum(b1 => b1.Duration),
                            Media = b.Average(b1 => b1.Duration),
                            Menor = b.Min(b1 => b1.Duration),
                            TextData = b.Select(b1 => b1.TextData).ToString().Substring(0,20)
                        })
        .Take(60)
        .OrderByDescending(b =>b.Total)
        .ToList();

    GridView1.DataSource = lambda;
    GridView1.DataBind();
}

Comment: só para completar faltou o () no cout, depois que coloquei funcionou
`Where(group => group.Count() > 1)`
Comment: Ah, sim. Desculpe. Escrevi a solução direto aqui e não testei. Valeu!
Answer: Faltou só uma última resposta a minha pergunta que era o LEFT que resolvi com Substring
 TextData = b.Select(b1 => b1.TextData).ToString().Substring(0,20)

Comment: Vou complementar a sentença da minha resposta com esta, ok?

Consulta Lambda


How to analyze multiple treatments and measurements?

Question: I've been asked to analyze data from an experiment measuring blood hormone levels from rats after a surgery. Hormone measurements were taken 10 days after surgery and 20 days after surgery. To make it more complicated, some of the rats in the surgery group were also subjected to a modified diet. So, there are three groups of rats (sham surgery + regular diet, surgery + regular diet, surgery + modified diet), and hormone measurements were taken at two time points.
What is the correct way to analyze the difference in hormone levels between these groups of rats, both within each time point and between time points? I'm having trouble figuring out the correct ANOVA and/or other method to use. I'm using R.
Comment: Were there no baseline measurements taken in the rates before surgery?  Do you only have 2 measurements at most taken on each rat?
Comment: That's correct. No baseline measurements, and only 2 measurements per rat. I think it's not the best experimental design, but the person who did the experiment left the lab before I got here, so I'm just trying to figure out how to make sense of it all!
Answer: There are a few ways to approach this.  In the simplest case (and the one I'd use and recommend), you can use a simple paired t-test with an adjustment for modified diet to compare the the differences in the measurements between the two time points.  So, you will create a new variable for each of the $n$ subjects, called $y_{diff}\equiv y_{20 day}-y_{10 day}.$  Then you will use regular OLS regression to model:
$y_{diff_i}=SurgeryX_{1i} + DietX_{2i} +\epsilon_i$
where $i=1, 2, . . . n$ and $X_{1i} = 1$ if the subject received the normal surgery, 0 otherwise; and  $X_{2i} = 1$ is the subject received the modified diet; 0 otherwise.  You can then use standard regression analysis to analyze the results -- since you've already taken the correlation due to the repeated measurements on each subject into account, there is no need to use any fancy machinery.
Comment: Thanks so much for your answer. Maybe I'm overthinking this, because we're reaching the boundaries of my statistics knowledge here, but the part that I'm still having trouble wrapping my brain around is the fact that the modified diet only happens in the rats w/ surgery, not the sham rats. Does that affect the interaction term in the model you gave? When I try this with `lm()` in R, it returns `NA` for the interaction coefficient and says that 1 coefficient is not defined because of singularities. Is this a problem I need to worry about?
Comment: Ahh right.  That was my mistake:  you'll need to remove the interaction.  There is no interaction needed here since there is only one level of the Surgery that was combined with modified diet.
Comment: I've modified my original answer to fix this mistake.
Comment: Does it make sense to analyze the difference between days 10 and 20, at all? Is it then possible that any difference between those days is just noise and says nothing about the treatments? A change from baseline (usually with baseline also in the model as a covariate) makes sense, but why look at $y_\text{diff}$? I would have thought a model for each timepoint or a joint model across timepoints (taking into account the correlation) would make more sense. I guess the other issue is missing data, which there may be (e.g. a MMRM would implictily impute it under MAR).
Comment: A paired t-test is just a special case of a mixed model/repeated measures model.


How to read specific chars and ints from file (update question)?

Question: I have an input file:
H
3(3,3)
V
1(5,4)
2(7,7)

I am reading this with:
 12 FILE *fp = fopen (argv[1], "r");
 13   if (fp == NULL)
 14   {
 15     return EXIT_FAILURE;
 16   }
 17   Stack* top = NULL;
 18   char gets[1024];
 19   while (fgets (gets, 1024, fp))
 20   {
 21     char node;
 22     int width = 0;
 23     int height = 0;
 24     int check = (sscanf (gets, " %c(%d,%d", &node, &width, &height));
 25     if (check == 1)
 26     {
 27       push(&top,node,0,0);
 28     }
 29     else if (check == 3)
 30     {
 31        push(&top,node,width,height);
 32     }
 33   }
 34   fclose (fp);

Which works fine.
  1 3(3,3)
  2 1(5,4)
  3 2(7,7)
  4 V
  5 H

But when I read something like this(input shortened as the file is big):
  1 93(11,16)
  2 11(12,33)
  3 H
  4 34(7,11)
  5 10(9,27)
  6 V
  7 32(12,30)
  8 30(12,16)
  9 41(12,19)
 10 H
 11 V
 12 50(12,13)

I get this, for example:
  1 9(0,0)
  2 1(0,0)
  3 H
  4 3(0,0)
  5 1(0,0)
  6 V
  7 3(0,0)
  8 3(0,0)
  9 4(0,0)
 10 H
 11 V
 12 5(0,0)

How can I fix this error to put the right output - so I get the proper value of a node instead of getting 9 instead of 93 for example.
Edit:
Its not working, I get something like this:
20 45(11,16)
 21 45(11,16)
 22 45(11,16)
 23 45(11,16)
 24 45(11,16)
 25 45(11,16)
 26 45(11,16)
 27 45(11,16)
 28 45(11,16)
 29 45(11,16)
 30 45(11,16)
 31 45(11,16)
 32 45(11,16)
 33 45(11,16)
 34 45(11,16)
 35 45(11,16)
 36 45(11,16)
 37 45(11,16)
 38 45(11,16)
 39 45(11,16)
 40 45(11,16)
 41 45(11,16)
 42 45(11,16)
 43 45(11,16)
 44 45(11,16)
 45 45(11,16)
 46 45(11,16)
 47 45(11,16)

which isnt even an input.
Comment: You will need to change `node` from `char` to a string (say `char tmp[32];`) and read into a temporary string with `" %[^(](%d,%d", tmp, &width, &height`, then you will check `isdigit(*tmp)` to determine if the 1st char in `tmp` is a digit or alpha-character. If digit, convert again with `sscanf`, if alpha, check length for the number of chars involved. The problem is you were going from reading a **single** character at the beginning to **multiple** characters.
Comment: @DavidC.Rankin thank you. Could you please post your code implmentation of this ?  I would greatly appreciate it as I am pretty lost now.
Comment: Sure, give me a sec, happy to do it.
Answer: Replace int check = (sscanf (gets, " %c(%d,%d", &node, &width, &height)); and char node; with bit more complex lines:
int node = 0;
int check = (sscanf (gets, "%d(%d,%d", &node, &width, &height));
if (check == 0)
{
  char n = 0;
  check = sscanf(gets, " %c", &n);
  node = n;
}

Comment: I get this error:  error: format '%c' expects argument of type 'char *', but argument 3 has type 'int *' [-Werror=format=]
       check = sscanf(gets, "%c", &node);
Comment: I have edited my original post. It still doesnt work unfortunately.
Answer: In this iteration of your question, what is changed is instead of having only a single-character before the first "(" or on a line by itself, you can now have multiple characters. You still want to be able to read either 'H' or 93 as the first part of the line, so you need to adjust your format-string to read multiple character before the first "(" and then either treat that as a string if it is an alpha-character, or convert it to an integer values if it is composed of digits. You can use something like:
#define MAXN   32
...
    while (fgets (buf, MAXC, fp)) {
        char tmp[MAXN];
        int node, width, height;
        switch (sscanf (buf, " %31[^(\n](%d,%d", tmp, &width, &height)) {
           ...

The format string being " %31[^(\n](%d,%d" where the '\n' is included in the negated character class along with '(' to trim the '\n' from those lines that just contain a single character. The circumflex (e.g. '^') at the beginning of the [^..] telling you to read character not including what is contained within the character class. (e.g. stop reading when the first negated character is encountered)
A full example would be:
#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */
#define MAXN   32

int main (int argc, char **argv) {

    char buf[MAXC];
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {
        char tmp[MAXN];
        int node, width, height;
        switch (sscanf (buf, " %31[^(\n](%d,%d", tmp, &width, &height)) {
            case 1 : printf ("single char/digit: '%s'\n", tmp);
                    break;
            case 3 : if (sscanf (tmp, "%d", &node) == 1)
                        printf ("all values: %d  %d  %d\n", node, width, height);
                    else
                        fputs ("error: parsing node from tmp.\n", stderr);
                    break;
            default : fputs ("invalid line format\n", stderr);
        }
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);
}

You can change the switch() statement to your if/else statements.
Example Use/Output
With your updated input, you would now get:
$ ./bin/fgets_sscanf_multival2 dat/multivals2.txt
all values: 93  11  16
all values: 11  12  33
single char/digit: 'H'
all values: 34  7  11
all values: 10  9  27
single char/digit: 'V'
all values: 32  12  30
all values: 30  12  16
all values: 41  12  19
single char/digit: 'H'
single char/digit: 'V'
all values: 50  12  13

Where you can push all value to your stack where needed. Let me know if you have further questions.
Comment: Sure, just drop another comment here and I'll get it when you wake up `:)`
Comment: We do this because when we start reading the file we don't know if it will be `'H'` or `93`, so we read into a buffer sufficient to hold the longest integer value (that would be 22 char including the `'\0'` but the next power of 2 32 is sufficient and provides a few characters of wiggle-room). Once we check the return -- we know which it was and for "all values" we then convert the string to an integer by calling `sscanf` again and on success we can `push()` all 3 values as needed.
Comment: Now you are also free to attempt the read with two-separate `sscanf` statements, one with `" %c"` into some char and one with `"%d(%d,%d"` into 3 `int` variables. Try the `int` one first and it fails try the `char` next (which will read something, but you would need to check that is was a digit -- indicating something went wrong with the integer parse. In that case you end up validating the return from 2 separate `sscanf` to handle your initial parse of what do I have?. By reading the first value as a string, the return of the call to a single `sscanf` tells us what we have. OK either way.
Comment: Thank you. This makes sense. I will try to implement it later as I have to sleep now. Is there any way to ask you questions regarding this later on ?
Comment: I have a question regarding the characters - you are storing it in a character array. Why do you do that when its only a single character? Edit : I guess my question is - if I have something like 3(3,3) does it go into the first swtich or second switch statement?
Comment: Thank you so much for the help. I really appreciate you spending the time to do so.


Lead sheets vs score at vocal auditions: Changing standards?

Question: I just discovered this video from 2 years ago in which the musical director and vocal coach Jake Anthony argues that there's been a shift in standard for auditioning (presumed musical theater or pop singing): that previously it was reasonable to present at an audition with a lead sheet for the accompanist, but that now, there's been a shift, and that one can't expect a pianist accompanying for auditions to know how to realize a  lead sheet, so one should bring a score.  He also suggests that an auditioning singer will be considered better prepared if they have score than a lead sheet.
I haven't auditioned for anything in ages, so this is news to me.  Can anybody confirm or deny this?  My interest isn't in auditioning, myself; I'm curious from a musicological perspective about musical practice, especially around different ways of writing music and different ways musicians collaborate, across different styles and demographics of musicians.  So I'm interested to know when this shift happened (if it in fact did), if anybody knows why (or even has a compelling theory) since it's not like scores were just invented yesterday, and how wide-spread it is (what genres of music has this shift happened in).
Comment: I suppose if you are auditioning for X Factor and other "karaoke" type shows a score would be appropriate. But if you were wanting to show off your style or interpretation of a piece, probably with key changes, a lead sheet should be adequate.
Comment: Perhaps the general piano audition accompaniment is more comfortable reading a score's "exact" part instead of interpreting with a lead sheet (hints of improvisation).  Maybe a general background of piano accompaniment has to do mostly with this.
Comment: @ShawnStrickland, that may well be true -- see discussion below -- but it does nothing to explain why it would be a recent change.
Comment: I really don't think this is a recent change, it's probably best transitioned to this over the last 20 years.  But the level of orchestration and detail for these styles of music (musical theater or pop singing) probably dictates a score to be more appropriate.  (Withholding the idea that in musical theaters some sections may be cut-and-pasted or a loop performed...)  A lead sheet, on the other hand (assuming you're talking about one that may use degree notation or Nashville notation, since key changes are brought up multiple times) is probably too malleable to be useful in an audition.
Answer: This is a pretty broad question, but in general I think a score is going to be preferred over a lead sheet in almost all situations.  In particular, a well-arranged piano score and NOT a PC score most of the time, as many PC scores try to jam in as much information about the orchestration and are extremely difficult to sight read.
The reason is that, short of extremely high-quality professional theater companies that can afford to hire the best accompanists in the city, accompanists are going to vary in quality dramatically.  A student theater group is going to use whoever is willing, and they commonly end up with someone who isn't very good.  Community and semi-pro companies tend to have reasonably skilled pianists, but they may not be completely rounded.  A lead sheet is worthless to someone without the training/experience to read one--a classically trained pianist can't do anything with it.  And even for someone with some skill in this area, a lead sheet still presents a lot of challenge if they're not familiar with the piece.  Really, lead sheets are a good notational system for something that's going to be rehearsed, but where you want to be vague enough to get out of the performer's way.  An audition is a sightread.
A score is at least providing notes that can be played, and a decently experienced musical theater accompanist should know how to fake through one if it's not easy enough to be totally sight read, even if their sheer technique is lacking.
I might expect to see auditioners to show up with lead sheets for a rock musical, but I would certainly ask first if this would be acceptable and be prepared for a "no".

He also suggests that an auditioning singer will be considered better prepared if they have score than a lead sheet.

My initial reaction to this was "no, that's not necessarily true", but when I thought back to the times that people have brought me lead sheets, I've invariably gotten the impression that they weren't well prepared.  I think it's primarily other factors with the lead sheet being only a consequence (specifically, I usually get the impression that the auditioner is only using that song because it's the only song they know, and that this crappy lead sheet is the only thing they could whip up), so if you can be professional about it you should be able to avoid that.
All of that being said, most accompanists will greatly appreciate a score with chord symbols, since the aforementioned faking is based on doing an on-the-fly harmonic analysis and re-realizing the music in a simpler way, and having the chord symbols eliminates a lot of the mental work.
Comment: I'm too young to know how things were in the biz 25 years ago, but I can offer some ideas based on my purely historical viewpoint.  Part of it may be that MT music has gotten exponentially more complex recently--a lead sheet would probably work just fine for a Classic Broadway show, but wouldn't be as viable for much of anything written recently.  Sondheim may be almost solely to blame for this.
Comment: Oh, what an interesting thought!
Comment: I've done bandcalls where lead sheets ( for not-so-good readers) or scores (for good readers) have been appropriate. Although sometimes, the full scores get changed on the night, and, no, you can't write on the sheet!! If I was being auditioned, I'd hopefully have copies of each - you never know what the players are going to be like.              I play in a jazz ensemble that uses lead sheets all the time, not for rehearsal, but to improvise off (your para.2).+1 for the answer !  Maybe standards are changing _ at recent auditions, some vocalists couldn't even say what key they wanted...
Comment: All these things are true -- I was a (classically-trained) pianist, and vastly preferred score to lead for all the reasons you mention -- but _why now?_  Weren't these things true 25 years ago when I was a piano-playing whippersnapper?  When apparently auditioning from lead sheets was normal?  (BTW, thanks for the answer!)
Answer: He's only kvetching.  A lead sheet, in the right key, marked up with the right 'geography' is fine. (What ISN'T much use is the 'vocal book' of a Broadway show, containing JUST the vocal line, no chord symbols.)   An audition accompanist's job description is 'cope'.  An auditionee's job is to know the song, and present sheet music that doesn't conflict with the way he's going to sing it. But simplification is fine.   Note also how much better most pianists' sight-reading gets when there are chord symbols :-)


Twig: How to show static text in the template to the Anonymous User?

Question: On a Drupal 8.9.13 website, I've removed the permission "View published content" from the Anonymous user.
By default, when someone visits the front page, Drupal will then display:

Access deniedYou are not authorized to access this page.

I want to replace this with some other text, e.g.

Please create an account to see our content.

To do this I try to create something like this in page--front.html.twig.
{% if not logged_in %}

Please create an account to see our content.

{% endif %}

However, I am stuck .

I am not able to get rid of the "Access denied" text for the anonymous user.
I can't get the the text "Please create an account to see our content." to show for the Anonymous user.  (If I remove "not" from the if-test it shows up as expected on the front page for the Authenticated user).

The site's theme is an otherwise unmodified subtheme of Bootstrap Barrio 5.1.4, but I don't think the problem is theme-dependent. Rather, the problem is that I don't understand the interplay between Twig and permissions (IMHO, there should be none).
Answer: Add a page--403.html.twig template to your theme.
See this change record: https://www.drupal.org/node/2960810
If you only want to change the default message you don't need a template. You can configure a node as access denied message in /admin/config/system/site-information.
Caveat for the non-template solution (as commented by @FreeRadical): If you restrict access to all nodes you have to find a different type of content. Could be a small module providing a custom controller which returns the static text.
BTW the themed page--403.html.twig is built in a subrequest which only job is to return a themed page with blocks. It's too late to make decisions on what to do with a 403 exception at this point. If you want to replace the core handling of a 403 exception (returning a themed subrequest) use an exception subscriber with default priority. See https://drupal.stackexchange.com/a/245211/47547
Comment: Thanks for the answer. I think there is a Catch 22 here: If you remove the permission "View published content" from the Anonymous user, configuring a *node* to show on 403 in /admin/config/system/site-information is not going to fly, because the Anonymous user will not be allowed to see it.  You may want to add that caveat to your answer. Using `page--403.html.twig` works.