How to optimise DB schema for a meal planner app?

Question: I am designing a DB schema for a meal planning application. Each meal plan consists of blocks (2 months of diet, 2 months of bulking), each block of meals for the day, each meal of the day of foods.
I made a normalized DB schema, however if I wanted to fetch a whole meal plan with it's analysis, the query would go through more than 6 different tables, which could really slow the application in the future. But I don't see a way to do it differently. To get the whole meal plan, it would have to through MealProgram > MealProgramBlock > DayMeal > DayMealFood > FoodOnDayMealFood > Food > FoodNutrient > Nutrient.
I know that NoSQL solution could be a fit for this use case, but that's a no-go in case I need to update a specific nutrient or food, I don't want to update all the existing records.
Table User {
  id varchar [primary key]
}

Table Food {
  id varchar [primary key]
  name String
}

Table FoodNutrient {
  foodId varchar [ref: > Food.id]
  nutrientId varchar [ref: > Nutrient.id]
  amount integer
}

Table Nutrient {
  id varchar [primary key]
  name varchar
  unitName String
}

Table MealProgram {
  id varchar [primary key]
  name varchar
  authorId varchar [ref: > User.id]
  customerId varchar [ref: > User.id]
}

Table MealProgramBlock {
  id varchar [primary key]
  name varchar
  programId varchar [ref: > MealProgram.id]
}

Table DayMeal {
  id varchar [primary key]
  blockId varchar [ref: > MealProgramBlock.id]
  name varchar
  day integer
  time varchar
}

Table DayMealFood {
  id varchar [primary key]
  dayMealId varchar [ref: > DayMeal.id]
}

Table FoodOnDayMealFood {
  id varchar [primary key]
  dayMealFoodId varchar [ref: > DayMealFood.id]
  foodId varchar [ref: > Food.id]
  weight integer
  unit varchar
}

Comment: Hard to help you, we hardly know anything about your requirements. And without much context, no (unique) constraints and varchar all over the place, you most likely have a challenge to get it right. About the varchar fields, is this valid content for these columns? "what about this piece of content that could go anywhere" And would it be valid to create a million records with this this content? And you're talking about a four month (2x2) diet, but it has no start nor end. There is no check either if you have any diet at all, you can't check for gaps, how many meals a day, in what order, etc
Comment: It's good to be cognizant of potential future performance issues related to design decisions; however, the initial design should not have unnecessary complications added to address issues that don't yet exist. Joining though six tables, assuming appropriate indexes, is probably not going to be unacceptably slow. As @FrankHeikens has mentioned, there are several issues with the model at this stage. Create a model that adequately addresses the problem domain. Don't intentionally create a non-performant design, but avoid premature optimization.
Comment: A varchar as id is not common, usually it's an integer/biginteger or a UUID. Time sounds like "time" to me, not "varchar". So please check your data types: https://www.postgresql.org/docs/current/datatype.html
Comment: @FrankHeikens I use Prisma as an ORM, and it uses CUID for IDs, therefore varchar. Didn't know it has time, only datetime, thanks
Comment: Do you really think you must have a CUID? A bigint gives you 9223372036854775807 unique values, that should be enough for the entire world population for the next couple of decades. And makes your database much faster and leaner.
Comment: Even though I see your point, in the question I meant to improve the whole structure.
Answer: The data-model so used strongly depends on  what kind of  database solution is hosting that  data . In your case its Postgres and these suggestions are targeted so . If e.g. the database was a MPP one like Teradata it'd be totally different. Having said that here are some pointers .Can grab  any that would work for you.

consolidate the DayMealFood and FoodOnDayMealFood tables into a single Meal table. This would allow you to store all of the information about a meal in a single place, and it would reduce the number of joins you need to perform when fetching a meal plan.

Add a meal_type column to the Meal table. This would allow you to distinguish between different types of meals, such as breakfast, lunch, dinner, and snacks. This information could be used to generate reports and insights about user meal patterns.

Add  a meal_plan_id column to the Meal table. This would allow you to associate meals with meal plans, and it would make it easier to fetch all of the meals in a particular meal plan.

Add a created_at and updated_at column to all of the tables in your data model. This would allow you to track changes to the data over time

composite primary key for the DayMealFood table. Single id value is not very useful for querying the table e.g.  to find all of the meals that contain a particular food, need a  join  of  DayMealFood table &  Food table. composite primary key  ( dayMealId and foodId columns) would allow you to query the table by day meal or by food without having to join 2 tables.

materialized view for the MealPlan. improves performance by caching frequently used data  When a user requests a meal plan, the application could first check to see if the meal plan is in the materialized view. If the meal plan is in the materialized view, the application can simply return the data from the materialized view

use a caching layer to store the data from the DayMealFood table. This would allow the application to fetch data from the caching layer instead of the database. This would significantly improve the performance of the application when users request meal plans
Answer: From a comment of yours in the chat we see you're using Prisma. Unfortunately Prisma does not do JOINs yet. So it actually performs multiple SQL queries on your normalized tables where a bunch of JOINs in a single query would usually not be a performance issue at all - they actually are the foundation of SQL databases.
So, the choice of technology is the culprit here. See also: https://github.com/prisma/prisma/issues/5184
If you can't find an alternative technology suitable for you and you have to go with Prisma, a denormalization could be an approach.
Updating multiple records for a change of nutrient or food may feel wrong in the world of RDBMs but a technology not even capable of doing JOINs also is.
An alternative could be:
Choose another ORM (if you really need one) that is able to perform JOINs, like sequelize or knex
A more radical alternative could be:
Choose a tool for defining your DDL (database schema) and running migrations, like flyway and write your SQL statements vanilla using the pg client lib.


Como buscar registros até o mês anterior?

Question: Preciso pegar todos os dados, desde o inicio até o mês anterior, essa consulta tem que ser dinâmica, não posso colocar uma data fixa, pois no mês que vem precisaremos consultar novamente...
Em resumo, hoje preciso pegar todos os dados até o dia 28/02/2021 e no mês que vem até o dia 31/03/2021 e assim por diante.
Answer: <code>    ... where DATEPART(m, _DATA_ ) = DATEPART(m, DATEADD(m, -1, getdate()))

</code>
Extrai o mês da data

DATEPART(m, DATA )

e compara diminuindo um mês da data atual

DATEPART(m, DATEADD(m, -1, getdate()))


Property of functions like $\sin{2x}$

Question: Let $f:\mathbb{R}\longrightarrow[-1,1]$ be a function twice differentiable such that
$$f(0)^2+f'(0)^2=4.$$
Prove or give a counterexample that for all such function $f$, there exists $c\in \mathbb{R}$ such that $f(c)+f''(c)=0$.
The function $f(x)=\sin{2x}$ satisfies the conditions and the result. But how can we prove the result for all $f$ or refute it? I really can't see any counterexample. I tried to observe the function $g(x)=f(x)^2+f'(x)^2$ (observe that $g'(x)=2f'(x)[f(x)+f''(x)]$) and I thought that I proved the result finding a point that satisfies $g'(c)=0$, but I realize that maybe $f'(c)=0$, and from that point I couldn't prove anything useful.
Comment: "But how can we prove?": prove what ?
Comment: @YvesDaoust prove that there exists a $c\in\Bbb R$ with $f(c)+f''(c)=0$, obviously
Comment: @vrugtehagel: this was already proven by the OP. So what ?
Comment: @YvesDaoust I think that nothing was proved.
Comment: @Harry49 for $2 (\arctan{\pi x})/\pi$ also exists such $c$
Comment: @math_pi: does one really need to prove $\sin^2(2\cdot0)+(\sin'(2\cdot0))^2=4$ and $\sin2c+\sin''2c=0$ for some $c$ ???
Comment: @YvesDaoust this is just an example of a function that satisfies the conditions of the problem but doesn't prove that it's true for every such fucntion $f$.
Comment: @math_pi: there is no "for all" anywhere, hence my question.
Answer: Intuitively, we start with $f(0)=0, f'(0)=2$.  We should be able to make $|f''(x)|$ big enough so we don't overrun $[-1,1]$  We need $f''(0) \neq 0$ or $c=0$ gets us.  We can patch together polynomials to do what we need as long as we keep the first derivatives smooth.  So take $$f(x)=\begin {cases} \frac 12+2x &-.1 \le x \lt .1\\ 0.4+4x-10x^2 &.1 \le x \lt .2\\0.8& x \ge .2\end {cases}$$  I think that does what you need and will leave the negative end to you.
Comment: @math_pi:  I thought I had it smooth enough, but you are right.  The idea is sound.  I have to leave now and can't patch it up.  There is a problem at $0.1$ as well.  You can also use $e^{(-1/x)} to smooth things out.
Comment: What is the second derivative at $x=0.2$?
Answer: Choose
$$f(x)=\frac{2e^2}{\sqrt17}\cdot e^{-1/(x+1/2)}$$
for $x>-1/2$ and $0$ else. Then any $c\leq -1/2$ satisfies the condition.
Comment: @MichaelHoppe:  but the values are not contained in $[-1,1]$
Comment: Nice, but this is another example of a function that satisfies the condition. I want a function such that doesn't exists $c\in\mathbb{R}$ for wich $f(c)+f''(c)=0$, to be a counterexample, or to prove that for every such function $f$ exists such $c$.
Comment: Guy, I think that you gave a counterexample. If we define the function to be symetric to $x=-1/2$ we have a function such that doesn't exists $c\in\mathbb{R}$ for wich  $f(c)+f′′(c)=0$
Comment: Easier: $f(x)=x^4/24+2$.
Comment: A possible duplicate target (with a positive answer to the question) has now been pointed out.

Property of functions like $\sin{2x}$


Using entity query build to apply conditions on all revisions

Question: Best practice deems that you should use EntityFieldQuery for queries that somehow involve fields and entities.
An example of query to look for nodes with a timestamp value set in the future would be the following code.
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_foo', 'value', REQUEST_TIME, '>')
  ->execute();

Is applying the conditions on all revisions, instead of only the active revision, possible?
A direct query on the database tables used to store the field revision values could eventually stop to work when Drupal changes some implementation details, such as the name of the used database tables, or the data stored in those database tables.
Answer: Yes. EntityFieldQuery has a method, EntityFieldQuery::age(), which is used to limit the revisions of the returned entities. It can be set to:

FIELD_LOAD_CURRENT (default)
It queries the most recent revisions for all entities.
FIELD_LOAD_REVISION
It queries all the revisions.

Support for this value ultimately depends on the query callback. The default query callback, field_sql_storage_field_storage_query(), which is the hook_field_storage_query() implementation done from the field storage module, uses it to query the appropriate revision tables.


What is the correct way to programatically set node type options?

Question: I learned yesterday that the correct way to create a node type is by implementing hook_node_info inside a .module file. Before I had been programatically creating node types in a .install file via node_type_save, like this:
// Create node type
$type = array(
  'type' => 'fruits',
  'name' => st('Fruits'),
  'base' => 'node_content',
  'description' => 'Contains information about fruits.',
  'custom' => 1,
  'modified' => 1,
  'locked' => 0,
);
$type = node_type_set_defaults($type);
node_type_save($type);

I had also been setting the node type options in the .install file, like this:
// Set 'fruit' options.
variable_set('node_preview_fruit', 0);                     // Set 'Preview before submitting' to 'Disabled'.
variable_set('node_options_fruit', array('status'));       // Set 'Default options' to 'Published'.
variable_set('node_submitted_fruit', 0);                   // Unset 'Display author and date information'.
variable_set('comment_fruit', COMMENT_NODE_CLOSED);        // Set 'Default comment setting for new content' to 'Closed'.
variable_set('menu_options_fruit', array('navigation'));   // Set 'Available menus' to 'Navigation'.
variable_set('menu_parent_fruit', 'navigation:0');         // Set 'Default parent item' to '<Navigation>'.

Is this the correct way to programatically set node type options: like this, inside the .install file, even though the node type itself is created inside the .module file?
Answer: Looking at the code for node_type_form_submit you can see that the variables are set before the node_type_save() function is called. Thinking about it a bit, it doesn't really matter as the node type info is saved into a different table than variables. So as long as the variables are being set synchronously with the creation of the node type, it shouldn't matter. Even then, the worst case scenario would be you'll have some redundant variables in the variables table. Which is not a big issue.
So to answer the question, yes that's the proper way. However I'd do it in the same function call in the .install file, maybe implement it in hook_install or hook_enable depending on what you need.
Comment: Okay, I'll stick with this approach then.
Comment: Me too. Until someone else tells different. Additional info to that issue on https://www.drupal.org/node/1169864
Answer: if you wanted to know the best way to create node on enabling the Drupal module

create a feature containing content type you want to create on module enable
check the code it generate
-> hook_field_info is defined in separate inc file and include it in .module by require once

as feature follows all the best drupal technique to code so i think this is the best way


If $p \equiv 1 \pmod{N!}$ prove there are no primitive roots $\pmod p$, $g$, that are less than $N$

Question: I've recently been looking at different questions and proofs in my book and one eludes me for the 2nd day in the row.

Let $N \geq 4$. Show that if $p$ is a prime such that $p \equiv 1 \pmod{N!}$ then none of the numbers $1, 2, \ldots, N$ are primitive roots modulo $p$.

I've tried using CRT, the fact that $\left(\frac{ab}{p}\right) = \left(\frac{a}{p}\right)\left(\frac{b}{p}\right)$ and Gaussian sum $G(p)$ properties, yet to no avail.
This proof has been really bugging me, could you please point me in the right direction?
Answer: We have $p \bmod N! = 1$ and $N > 3$ so we have $p \bmod 4 = 1$. Consider $q < N$ is a prime number we have $p \bmod q = 1$, so by quadratic reciprocity law we have $$\left(\frac{q}{p}\right) = \left(\frac{p}{q}\right) = \left(\frac{1}{q}\right) = 1$$ using $$\left(\frac{a}{p}\right)\left(\frac{b}{p}\right) = \left(\frac{ab}{p}\right)$$ we have $1, 2, \ldots, N$ are quadratic residue so they are not primitive roots.
Comment: thanks, I've just completely ignored the fact that pmodq=1 proceeded in the wrong direction. Thanks ali :)


The username used for a failed login attempt is not reported anymore

Question: Just completed a migration of a site from Drupal 7 to 10, and it's gone pretty smoothly after quite a bit of preparation.
One thing seems different in a frustrating way: In the prior site on Drupal7, failed login attempts would be logged as eg "Login attempt failed for admin." or "Login attempt failed for [mis-spelled name]".
Once upgraded, it appears that failed attempts only list a username if that username exists (and there is no user called admin), otherwise these just log an ip address.
Am I correct in interpreting this, and is there a simple way to replicate the old behaviour?
To be clear, I find it useful to be able to display the username: my clients use this day-to-day supporting users who are getting usernames wrong.
I'll probably find a relevant hook if there's no existing solution.
Answer: Yes, it is correct to say that the username is logged only when there is an account matching that username. That is what UserLoginForm::validateFinal() does.
// Use $form_state->getUserInput() in the error message to guarantee
// that we send exactly what the user typed in. The value from
// $form_state->getValue() may have been modified by validation
// handlers that ran earlier than this one.
$user_input = $form_state->getUserInput();
$query = isset($user_input['name']) ? ['name' => $user_input['name']] : [];
$form_state->setErrorByName('name', $this->t('Unrecognized username or password. Forgot your password?', [':password' => Url::fromRoute('user.pass', [], ['query' => $query])->toString()]));
$accounts = $this->userStorage->loadByProperties(['name' => $form_state->getValue('name')]);
if (!empty($accounts)) {
  $this->logger('user')
    ->notice('Login attempt failed for %user.', ['%user' => $form_state->getValue('name')]);
}
else {
  // If the username entered is not a valid user,
  // only store the IP address.
  $this->logger('user')
    ->notice('Login attempt failed from %ip.', ['%ip' => $this->getRequest()->getClientIp()]);
}

To log what has been entered in the login form as username, you can add a validation handler that contains code similar to the following one.
if (!$form_state->get('uid')) {
  // The login attempt failed.
  $user_input = $form_state->getUserInput();
  $ip = Drupal::request()->getClientIp();
  \Drupal::logger('mymodule')->notice('Login attempt failed (user: "%user", IP: %ip).', ['%user' => $user_input['name'] ?? '', '%ip' => $ip]);
}

I used $form_state->getUserInput() for the same reason given in the UserLoginForm::validateFinal() comment: $form_state->getUserInput() returns exactly what has been entered in the form, while the value returned by $form_state->getValue() could have been modified by any validation handler.
Comment: That looks fantastic thanks.


How can it be that $(P \rightarrow Q) \vee (Q \rightarrow P)$ is a tautology?

Question: I consider $(P \rightarrow Q) \vee (Q \rightarrow P)$, that is $(\neg P \vee Q) \vee (\neg Q \vee P)$ and so $\neg P \vee Q \vee \neg Q \vee P$, which is a tautology.
It seems strange to me that, given two arbitrary formulas, necessarily  one implies the other or viceversa. (I am thinking for example of this case: P stands for 'Ann loves animals' and Q 'Ann is a student')
Where is my mistake? Perhaps in the interpretation of $P$ and $Q$?
Any clarification will be much appreciated.
Comment: There is no mistake : it is a tautology. You can see also this [post](http://math.stackexchange.com/questions/1121987/show-that-p-to-q-lor-q-to-p-is-a-tautology).
Comment: Your mistake is in the interpretation of "implies". The logical symbol $\to$ has _nothing_ to do with causation.
Comment: I think your issue is actually in your interpretation of $\rightarrow$; as the decomposition $P\rightarrow Q = \neg P \vee Q$ indicates, $\rightarrow$ is *not* a causal implication, only a material implication.  $P$ and $Q$ need not have really anything in common for $P\rightarrow Q$ to be true.
Comment: I think almost everyone agrees that there are ways in which $\to$ is not a good model of implication, and that this demonstrates one of them. Wikipedia has an article on [paradoxes of material implication](https://en.wikipedia.org/wiki/Paradoxes_of_material_implication) that cites this example specifically. In intuitionistic logic, $\to$ has a different interpretation, and $(A\to B)\lor(B\to A)$ is *not* a tautology; some people prefer intuitionistic logic for this reason.
Comment: Your question could be generalized to "why is $(P \rightarrow A) \lor (B \rightarrow P)$ always true?"  $A=B$ is just a special case.
Comment: The left part is false only if $[P\wedge\neg{Q}]$, but that makes the right part true.
Comment: @MJD Thank you very much for the article:)
Comment: I am voting to reopen this question because it is *not* about the proof of the proposition, but rather about implication and how "unintuitive" it may seem to be.
Answer: The kicker is to remember that a true statement is implied by any statement, and that a false statement implies every statement. (This is one upshot of the fact that $A\to B\equiv\neg A\vee B.$ The other is that a true statement does not imply a false statement.) Hence, if P is true or P is false, then your compound statement is true.
To clarify that last sentence, let's consider your particular example statements, in light of the possibilities. Does Ann love animals? If so, then $Q\to P$ holds; if not, then $P\to Q$ holds. Regardless, one of the two implications is true, and so $(P\to Q)\vee(Q\to P)$ is necessarily true.
Answer: The proposition $(P \rightarrow Q) \vee (Q \rightarrow P)$ is always true.  This does not mean that either $P \rightarrow Q$ is always true or $Q \rightarrow P$ is always true.  Isn't that what you said?
Comment: Thank you...Oh ok, that was my problem!
Answer: Remember the definition of implication.
$P \rightarrow Q$ means $\lnot P \lor Q$ In words, either $P$ is false or $Q$ is true.
$Q\rightarrow P$ means $\lnot Q \lor P$ In words, either $Q$ is false or $P$ is true.
Putting it all together gives us $$(P\rightarrow Q) \lor (Q\rightarrow P) \equiv \lnot P \lor Q \lor \lnot Q \lor P \equiv P\lor \lnot P \lor Q \lor \lnot Q$$
The above cannot logically be false. Either $P$ is true or $\lnot P $ is true, not to mention we also have $Q \lor \lnot Q$.  You can verify the tautology by using a truth table.
Recall that material implication tells us nothing about the relevance of $P$ with respect to $Q$, nor that of $Q$ with respect to $P$.  That is, material implication does not necessarily signify any causal relation between one proposition and another.
This is what may seem very counter-intuitive because in natural language, we think of one event implying another event as being causal, or otherwise being based on some relevant relationship between one statement and another. In logic, we are not to take $P\rightarrow Q$ as saying anything more than "either $P$ is false, or $Q$ is true."
Comment: @Arthur: I am *interpreting* explicitly what implication says, and what it does not claim, which may seem counter-intuitive
Comment: I removed my comment after you added your content (it made my previous comment irrelevant), but here is why I said what I said: I feel it's very important in mathematics in general to gain intuition beyond merely what rules tell us. Your original answer was basically just a repeat of the OP's argument as a confirmation that there were indeed no mistakes. However, the OP didn't ask for that. They asked for an intuitive justification for why it is the way it is, in order to further understand the _moral_ of the story. Your original answer provided nothing of that.
Answer: Sometimes logical implication is not that intuitive.
For your $P$ and $Q$ we have the following:
Either Ann loves animals, or she doesn't. If she does, then $Q\to P$ is true.
If she doesn't, then $P\to Q$ is true.
Either way one of the components in the disjunction is true.
Answer: In your example, it means that either the statement

If Ann loves animals, then Ann is a student

Or the statement

If Ann is a student, then Ann loves animals.

(or both) is correct.
If Ann is, indeed, a student, then the first statement is true if she loves animals or not. If Ann is not a student, then any statement beginning with "If Ann is a student" is correct, so , in conclusion:

If Ann is a student, statement 1 is correct. Statement 2 may or may not be correct (it is correct if Ann indeed loves animals and incorrect if she does not), but that is irrelevant.
If Ann is not a student, then statement 2 is correct. Statement 1 may or may not be correct (it is correct iff Ann does not love animals), but again, that is irrelevant.


Como converter ícones .svg em uma fonte?

Question: Existe uma forma recomendável para converter e combinar vários ícones no formato .svg em um único arquivo de fonte (ttf, woff, etc)?
Quero definir uma @font-face e atribuir minha fonte, de modo que eu possa usar seus ícones da mesma forma que se usa por exemplo no "Font Awesome", atribuindo uma classe ao um elemento :

Comment: E por que se dar o trabalho? Por que não usar o SVG mesmo? Se for por compatibilidade, o suporte dos dois é mais ou menos o mesmo. Mas se quiser mesmo tem ferramentas online que fazem isso pra ti
Comment: @Costamilam Sei que posso usar direto todos `.svg`, mas gostaria de aprender como é feito isso.
Comment: @ThiagoKrempser eu prefiro utilizar como `font` do que imagem, eu utilizo o **IcoMoon** para gerar o `@font-face` dos `SVG's` os quais faço upload do mesmo. Caso você ache que a minha resposta foi adequada para a sua pergunta, é só marca-la com o "check verde".
Answer: Você pode utilizar uma maneira simples para isto, a qual é a seguinte:

Um sistema pronto para esta conversão denominado IcoMoon.

Sobre o IconMoon

A biblioteca de ícones do IcoMoon apresenta apenas os melhores ícones definidos lá. Todos os nossos ícones são projetados em uma grade de pixels precisa. O aplicativo IcoMoon permite que você crie e use seus próprios pacotes de ícones em diversos formatos, incluindo SVG, Polymer, PDF, XAML, CSH, fonte de ícone com ligaduras ou boas sprites PNG/CSS antigos.

Nota

Caso você queira criar um ícone personalizado e que o mesmo não existe na internet, utilize um software denominado Inkscape. Após criar a vetorização gráfica do ícone, você deve salvar em SVG e utilizar um sistema como o citado acima para fazer a conversão de SVG --> font + @fonte-face.
Comment: Sugiro remover essa parte da sua resposta, já que está errada, pra não confundir ninguém
Comment: Inkspace salva em TTF ou OTF ou coisa do tipo? Até onde sei ele não salva nem exporta fontes... https://inkscape.org/pt-br/aprender/faq/#quais-sao-os-formatos-que-o-inkscape-pode-importarexportar
Comment: Como criar uma fonte no Inkscape? Fiquei curioso, uso a ferramenta, mas não sabia que dava pra fazer isso
Comment: @Costamilam como você não citou que sabia criar os vetores e com o Inkscape, eu citei o mesmo para você, caso você quisesse criar algo personalizado. Por resumo o Inkscape só cria os vetores mesmo, ele não exporta/salva em fontes, você teria que criar os icones lá em SVG e converter em um sistema como o IconMoon.
Comment: @hugocsl Isto é verdade, eu respondi acima para ele.
Comment: @Costamilam alterei a resposta, para ficar mais clara e objetiva.


Prevent falsy request from React Router loader function

Question: I use React Router 6.4.2 and it's API - createBrowserRouter.
I have a default request that should be done only once when user reach main route ('/').
Request requires auth token (Amplify) so i use protected routes. No token - redirect to './auth/.
Router:
const router = createBrowserRouter([
  {
    element: (
      <RequireAuth>
        <AppLayout />
      </RequireAuth>
    ),
    children: [
      {
        path: '/',
        loader: getDefaultData,
        element: <MainPage />,
      },
    ],
  },
  { path: '/auth', element: <Authenticator /> },
  {
    path: '*',
    element: <NotFoundPage />,
  },
]);

export const AppRouter = () => {
  return <RouterProvider router={router} fallbackElement={<AppLoader centered />} />;
};

RequireAuth:
export const RequireAuth = ({ children }: Props) => {
  const location = useLocation();
  const { route } = useAuthenticator((context) => [context.route]);
  if (route !== 'authenticated') {
    return <Navigate to="/auth" state={{ from: location }} replace />;
  }
  return <>{children}</>;
};

GetDefaultData:
export const getDefaultData = async () => {
  store.dispatch(
    getData({
      someVariables,
    })
  );
};

What i faced: when not authenticated user try to reach main route ('/'), he reach it for a moment before he will be redirected to './auth/ and React Router run getDefaultData from loader that fails on getting-auth-toker step.
What i expect: React Router will skip getDefaultData for that case. Looking for a way how to tell React Router about that in a beautiful way.
P.S. I know that i can add auth check with return inside getDefaultData function (generally it happens but not from scratch but on getting-auth-token).
I know about shouldRevalidate but not sure that it can help me in that case.
UPD. provided a codesandbox for that
https://codesandbox.io/s/amazing-matsumoto-cdbtow?file=/src/index.tsx
Simply try remove '/auth' from url manually and check console.
UPD. created an issue about that https://github.com/remix-run/react-router/issues/9529
Comment: I suppose I was trying to imply that if the `getDefaultData` function has the capability to know whether or not it's in a state to make valid requests that it should do that check and only make valid requests. RRD doesn't conditionally call loaders AFAIK.
Comment: Can `getDefaultData` check for the authenticated user/token prior to making requests? Can you share all relevant code you are working with and trying to use as part of your [mcve]?
Comment: Yes, as i mentioned in P.S. section: i can do this in function, and generally it happens when i try to get token to add it to my request.
Like this function runs but crashes before the request is sent with the error: No current user (as expected).
And the question is - how to tell React router not to run this finction at all!
As we do not care about function itself or auth mechanic, i think that no more code evolved in this situation. But can you tell in what parts you are interested in?
Comment: Added `getDefaultData` shape.
So generally if i will do something like
```const session = await Auth.currentSession();
    if(!session) return;
```
in the very begining of a function - it will do one request to prevent another =)
That generally happens but a little bit later in middlewares when i'm adding token to headers.
Comment: But i declare if i expect that request should happen on a level above the loader declaration. Looks like ProtectedRoutes do not protect anymore ¯\_(ツ)_/¯
Answer: Got an answer from Matt Brophy in github:
Fetching is decoupled from rendering in 6.4, so loaders run before any rendering logic. You should lift your "requires authorization" logic out of the RequireAuth component and into your loaders and redirect from there. Redirecting during render is too late
Also note that all loaders for a matched route route run in parallel, so you should check in each loader for now (just like in Remix). We plan to make this easier to do in one place in the future.
Original answer:
https://github.com/remix-run/react-router/issues/9529
Comment: Thanks for posting this. I ran into this today and it is surprising behavior. Basically, you need to protect each loader/action function in addition to conditionally rendering a component. You can take care of conditionally rendering a component tree from the top of the tree only, so all child components won't render (expected), but then you need to protect each loader function (from the top of the route tree, to the leaf of the route tree) with an `if (isLoggedIn)` guard on protected routes. This is bc loaders run in parallel if the route matches, regardless if they end up being rendered.


Cannot add "Flash App" Run/Debug Configuration in IntelliJ IDEA

Question: I would like to run my flash project, but I cannot add "Flash App" Run/Debug Configuration in IntelliJ Idea
When I click on the plus sign, there's no Flash App in it:

But it appears in the Defaults, with an error:

Build configuration: [none]

I have Flash plugin and SDK installed
Answer: I was having the same issue, eventually I removed the "Flash/Flex Support" plugin by going to Preferences > Plugins, restarted IntelliJ, re-enabled the plugin and restarted again. It seemed to sort the issue after I re-imported my Maven project (which didn't resolve the issue before doing this).


How to find unused or old twig template files?

Question: There are times when fields are deleted from a Content type, but there is no way of knowing if there is a related field twig template without manually looking in our repository.
Other than looking for file names, are there any utilities or other methods to find twig templates that are not being used?
Answer: It's difficult to find a deterministic method, so you probably need some kind of usage statistics.
A simple statistical method would be to clear the twig php cache:
<code>\Drupal\Core\PhpStorage\PhpStorageFactory::get('twig')->deleteAll();
</code>
Then run the site for some time and check the twig php cache (/sites/default/files/php/twig) for twig files not having a compiled php template.
Comment: Checking the compiled templates did help find some fields. We will use this method moving forwards.
Answer: You could use drush twig:unused for this:
<code>drush twig:unused --field=template /var/www/project_name/docroot/modules/custom,/var/www/project_name/docroot/themes/custom
</code>
Crawl your site first. More information at the drush site here: https://www.drush.org/latest/commands/twig_unused/


How to get detailed error message using docker-compose up? I can only see "command returned non-zero code"

Question: I'm trying to run my docker-container on linux. During build I'm encountering an error after running this command:

sudo docker-compose -f docker-compose.yml up --build

docker-compose shows this message:
Step 10/19 : RUN dotnet restore "test/test.csproj"
 ---> Running in ea65364853f3
standard_init_linux.go:211: exec user process caused "exec format error"
ERROR: Service 'test' failed to build: The command '/bin/sh -c dotnet restore "test/test.csproj"' returned a non-zero code: 1

Is there any way I can see detailed error message?
Comment: You already got the detailed error message!
Answer: The error is occurring during the build process. You should see the same results when you run docker-compose build.
This error:
standard_init_linux.go:211: exec user process caused "exec format error"

means that Docker tried to run the dotnet executable inside the container, but it couldn't start because the dotnet binary in the image is incompatible with the environment in the container. Perhaps it is compiled for a different architecture, or something like that? If you show the rest of your build process (steps 1-9) we can probably spot the problem for you.
Comment: Yes, indeed, later I've discovered that there was a problem with architecture compatibility. Your answer is correct
Answer: Because RUN commands are said to work like this:
get an image, create a container ContainerA, run your command in this container, and generate a new image ImageB. delete ContainerA, create ContainerB...
Now it quits at one RUN, so it must leave a containerX behind. Therefore, you can see log like this:
docker build -t <yourname>:<tag>

quit on error

docker logs <yourname>

here is your detailed error log.
Comment: The `docker logs` command only deals with container logs, not build or image logs.


Assumption of dependent t-test

Question: Some sources (i.e. https://statistics.laerd.com/spss-tutorials/dependent-t-test-using-spss-statistics.php) include assumption about outliers. "There should be no significant outliers in the differences between the two related groups". However, the text book that I read, does not.
My question is, should I check for existence of outliers or normality test is enough to conduct dependent t-test? if yes, what does "significant" outliers mean here?
The number of outliers? Extreme outliers (outlier > IQR*3+Q3 / outlier < Q1 -
 IQR*3) ?
Can I still conduct t-test if my data are normally distributed but there are mild outliers? (not extreme)
If my data are not normally distributed I use Wilcoxon signed-rank test. Are mild outliers problem for this test as well?
Answer: In this context, outliers could be defined as any data point that makes the distribution deviate from normality. So, looking for outliers and checking for normality are both to satisfy the same assumption.
Exactly what constitutes and outlier is pretty subjective though.
Mild outliers might not be a problem for the t-test if you have a big enough sample size — the central limit theorem will allow you to do the test if your distribution is close to normal even without a huge sample size.
Outliers are not a problem for the Wilcoxon test because normality is not a necessary condition.

Assumption of dependent t-test


Hard exemplary problem sets to work through to solidify my understanding of statistical concepts?

Question: Over the years, I picked up many Statistics Concepts in by a variety of situations and means. I studied some Statistics maybe for a couple semesters almost 10 years back. But I also picked up concepts while doing Machine Learning work. I only understood things in a narrow scope - I always tried to get away knowing only what I need to know for a project etc.
Consequently, I do not have a big picture understanding of Statistics. For eg. I know vaguely what a t-test is and what a chi-square test is. But I can't relate both these concepts solidly in my head. And without relating each of these concepts I feel they are useless and not as powerful.
I have come to understand that the only way I understand anything is by working on hard problems chosen by experts. It should be hard so that I take some time to work it, also it should be chosen carefully by experts so that each problem contains a 'moral' which takes me one step closer to enlightenment.
So, help me assemble a set of problems to work through to seek out zen through statistics. Scope is all of statistics (regression, ANOVA, t-tests etc, Structural Equations of Latent Variables etc).
Comment: A large number of the questions posted on this very site provide problems ranging from easy to impossible.  The replies provide a richer set of answers than any problem set or textbook could possibly offer, because they often represent multiple different attempts at solutions.
Comment: I know two excellent series of exercises from Ecole Polytechnique: "Petites classes de statistique", the first one by Christian Robert and the second one by Olivier Cappé. But there are written in French. Type "Petites classes de statistique" in Google and you will find.
Comment: Looks like a good candidate for a Community-Wiki question.
Comment: @chl, that makes sense. Go ahed if you have the privileges.
Answer: Mathematical Statistics and Data Analysis, by John A. Rice, Third Edition
If you are struggling to understand how different things in statistical relate to each other, the "glue" that you are missing is an understanding of mathematical statistics.
Rice's textbook provides the theory that justifies most of the statistical tests and methods which are used in introductory statistical courses.    For example, it derives the $t$ and $\chi^2$ distributions and describes how they can be used to construct statistical tests.  By contrast, most introductory statistical texts list the different distributions and tests but do not derive them.
It is a standard textbook in mathematical statistics.  It does not assume much in the way of existing knowledge, but it does require some effort to work through the content (particularly if you are not comfortable in maths).  There are lots of  examples at the end of the chapters.
No doubt there are other statistical textbooks of equal quality.  My key point is that an understanding of mathematical statistics is the thing required in order to understand statistics at a non-superficial level and it is particularly useful if you come from a machine learning background as the basic logic is very different (i.e., proofs rather than learning by trial and error and bake-offs).
Comment: Could you provide a brief description of this textbook or indicate what it covers?
Comment: I have modified my answer.


sed break into lines (advanced)

Question: I'm looking to use sed (or combining it with another grep command)to convert the following string
John: Hi!,How are you,?,Dylan: Hey,OK

into
John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

If that's not possible I'm willing to compromise for
John: Hi!,How are you,?
Dylan: Hey,OK

Many thanks
Comment: Please provide a minimalistic code demo of what you have tried.
Comment: I tried too many things pretty messed the entire thing until you guys came to the rescue
Answer: sed can be used.
There is a great Sed - An Introduction and Tutorial by Bruce Barnett online page, which I always open aside when writing sed script.
Give a try to this:
printf 'John: Hi!,How are you,?,Dylan: Hey,OK\n' | sed -n '
:1
/./ {
  /^[^:,][^:,]*: / {
    h
    s/^\([^:,][^,:]*: \).*$/\1/
    x
    s/,/\n/
    P
    D
  }
  x
  /./ {
    x
    H
    x
    s/\n//g
    x
    s/.//g
    x
    b 1
  }
}'

The output is:
John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

Comment: Bravo! That is worth the UV just for the canny use of pattern and hold space and the lest oft used `D` to control the newline cycle.
Comment: From my point of view both `/./ {` and the corresponding closing bracket `}` can be omitted.
Comment: I am BLOWN away! Thank you so much!
Comment: @Cyrus This is true, this would give on one line:

    `printf 'John: Hi!,How are you,?,Dylan: Hey,OK\n' | sed -n ':1 ; /^[^:,][^:,]*: / { h ; s/^\([^:,][^,:]*: \).*$/\1/ ; x ; s/,/\n/ ; P ; D } ; H ; x ; s/\n//g ; x ; s/.//g ; x ; b 1'`
Answer: In awk:
$ awk 'BEGIN{RS=","}{if($1~/:$/)p=$1;print ($1==p?"":p " ") $0}' file
John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

There will be an extra empty line in the end. For some awks (at least GNU awk, mawk and Busybox awk) you can use RS="[,\n]".
Comment: I made the sed answer as correct because this didn't worked in my android in terms it made an extra line for "John" as part of "Dylan" line i.e. "John: Dylan: Hey"
Answer: With trand awk:
tr ',' '\n' <file | awk '/:/{name=$1; print; next}; {print name,$0}'

or shorter:
tr ',' '\n' <file | awk '/:/?name=$1:$0=name " " $0'

Output:

John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK
Answer: In single awk, considering that your Input_file is same as shown samples then following may help you here.
awk -F',' '
{
  for(i=1;i<=NF;i++){
    if($i~/:/){
      if($i ~ /: /){
        print $i
        split($i,array," ")
        val=array[1]
      }
      else{
        val=$i
      }
    }
    else{
      print val,$i
    }
  }
}'  Input_file

Answer: You may try to do something like this:
echo 'John: Hi!,How are you,?,Dylan: Hey,OK' | sed -E "s|(\w+:)|\n\1|g"

It will return:
John: Hi!,How are you,?,
Dylan: Hey,OK

sed break into lines (advanced)


How to access TypeUse annotation via AnnotationProcessor

Question: Question:

Is it possible to access elements annotated with a @Target(ElementType.TYPE_USE) annotation via an annotation processor?
Is it possible to access the annotated type bounds via an annotation processor?

Links to related documentation I missed are highly appreciated.
Context:
The annotation:
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.SOURCE)
public @interface TypeUseAnno {}

An example class:
public class SomeClass extends HashMap<@TypeUseAnno String, String> {}

The processor:
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("base.annotations.TypeUseAnno")
public class Processor extends AbstractProcessor {

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Initialized.");
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Invoked.");
        for (TypeElement annotation : annotations) {
            this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "" + roundEnv.getElementsAnnotatedWith(annotation));
        }
        return true;
    }
}

Compiling the above SomeClass with Processor on the classpath will show the "Intialized" message but the process(...) method is never invoked.
Adding another annotation to the processor with @Target(ElementType.PARAMETER) works fine when the annotation is present on a method parameter. If the method parameter is annotated with @TypeUseAnno the process will again ignore the element.
Answer: The TYPE_USE annotations are a bit tricky, because the compiler treats them differently, than the "old usage" annotations.
So as you correctly observed, they are not passed to annotation processor, and your process() method will never receive them.
So how to use them at compilation time?
In Java 8, where these annotations got introduced, there was also introduced new way to attach to java compilation. You can now attach listener to compilation tasks, and trigger your own traversal of the source code. So your task to access the annotation splits into two.

Hook to the compiler.
Implement your analyzer.

Ad 1.
There are 2 options to hook on the compiler in Java 8:

Using new compiler plugin API.
Using annotation processor.

I haven't used option #1 much, because it needs to be explicitely specified as javac parameter. So I'll describe option #1:
You have to attach TaskListener to the propper compilation phase. There are various phases. Following one is the only one, during which you have accessible syntax tree representing full source code including method bodies (remember, that TYPE_USE annotations can be used even on local variable declarations.
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class EndProcessor extends AbstractProcessor {

    @Override
    public synchronized void init(ProcessingEnvironment env) {
        super.init(env);
        Trees trees = Trees.instance(env);
        JavacTask.instance(env).addTaskListener(new TaskListener() {

            @Override
            public void started(TaskEvent taskEvent) {
                // Nothing to do on task started event.
            }

            @Override
            public void finished(TaskEvent taskEvent) {
                if(taskEvent.getKind() == ANALYZE) {
                    new MyTreeScanner(trees).scan(taskEvent.getCompilationUnit(), null);
                }
            }

        });
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        // We don't care about this method, as it will never be invoked for our annotation.
        return false;
    }
}

Ad 2.
Now the MyTreeScanner can scan the full source code, and find the annotations. That applies no matter if you used the Plugin or AnnotationProcessor approach. This is still tricky. You have to implement the TreeScanner, or typically extend the TreePathScanner.
This represents a visitor pattern, where you have to properly analyze, which elements are of your interest to be visited.
Let's give simple example, that can somehow react on local variable declaration (give me 5 minutes):
class MyTreeScanner extends TreePathScanner<Void, Void> {
    private final Trees trees;

    public MyTreeScanner(Trees trees) {
        this.trees = trees;
    }

    @Override
    public Void visitVariable(VariableTree tree, Void aVoid) {
        super.visitVariable(variableTree, aVoid);
        // This method might be invoked in case of
        //  1. method field definition
        //  2. method parameter
        //  3. local variable declaration
        // Therefore you have to filter out somehow what you don't need.
        if(tree.getKind() == Tree.Kind.VARIABLE) {
            Element variable = trees.getElement(trees.getPath(getCurrentPath().getCompilationUnit(), tree));
            MyUseAnnotation annotation = variable.getAnnotation(MyUseAnnotation.class);
            // Here you have your annotation.
            // You can process it now.
        }
        return aVoid;
    }
}

This is very brief introduction. For real examples you can have a look at following project source code:
https://github.com/c0stra/fluent-api-end-check/tree/master/src/main/java/fluent/api/processors
It's also very important to have good tests while developing such features, so you can debug, reverse engineer and solve all the tricky issues you'll face in this area ;)
For that you can also get inspired here:
https://github.com/c0stra/fluent-api-end-check/blob/master/src/test/java/fluent/api/EndProcessorTest.java
Maybe my last remark, as the annotations are really used differently by the javac, there are some limitations. E.g. it's not suitable for triggering java code generation, because the compiler doesn't pick files created during this phase for further compilation.
Comment: A note for java 8: Make sure the tools.jar is in the classpath since it is in a different location as the other libraries (jdk/lib vs jdk/jre/lib).
Although this seems more cumbersome, since the com.sun.source API seems more fine grained than the javax.lang.model API, it provides me with all the tools I need.
Comment: Yes, thanks for adding this point. Also note, that since java 9 this changes so, that tools.jar is not needed any more, and the `javax.lang.model` (public) api is available out of the box. On the other hand the internal `com.sun.source` api is not available in java 9 at all. Definitely the later is more flexible, but if you plan to migrate to java 9 or higher, rather stay with the public api.
Comment: This answer may mislead some to believe you cannot get access to TYPE_USE annotations with an annotation processor. You can but only through the `TypeMirror` (as it is annotated the type) and thus you cannot do a global search and claim for them like normal annotations. **You can however check to see if variable, field, etc has a TYPE_USE annotation on it** through `TypeMirror.getAnnotationMirrors()`


Slow logon only affecting one domain user account

Question: One domain user on our network takes up to 5 minutes to log on to one particular PC (the other domain users can log in in around 10 seconds, and local accounts take only a couple of seconds to sign in on this PC).
This is a well-known error- but what makes this unusual is that only 1 particular domain user account is affected, and only on one particular PC:

This is a clean install of Windows XP Professional, with almost no software installed. The only twist is that this is a remote computer connecting to the main site (where the domain controller is located) via a Hamachi VPN gateway network.
Once logged in, the user with the slow logon is also unable to browse network shares on the server at the main site (although pinging hosts on the central site is successful). Simply typing "\\server" does not show the network shares (as it should for a domain user), instead Windows asks for domain credentials as if a local (rather than a domain) user account is trying to access it.
Initially I suspected DNS to be the problem, however everything in DNS looks the same when logged in as either user- I am unable to find anything different in the problematic user account:

It's definitely not a corrupted profile- it was only created 2 days ago (signed in for the first time using that account this week). Also, I have just deleted and recreated the profile from scratch- and the issue still persists.
Both users are in the same OU in Active Directory, so I can't see how this would be related to Group Policy.
I can log in as any other user, and everything goes back to normal again. The issue is 100% repeatable.
Any ideas would be much appreciated. This has me stumped.
Comment: Can you clarify - is there one physical PC (remote), and the behaviour differs depending on which user ID is used to login from that PC?
Comment: That's correct. There is only one physical PC, and only *one* (of many) domain user accounts is getting stuck at the logon screen for a few minutes each time (sometimes as much as 5-10 minutes). Deleting the user profile on this PC (folder structure and registry key) did not make any difference.
Comment: What about the server profile? How big is it?
Comment: @krissi: server profile size? How do you mean? We don't have roaming profiles if that's what you're wondering.
Answer: It seems that your problem is SMB / CIFS: I suspect that this particular user has Network Shares mapped, which of course are being connected at logon - or at least, are being tried to be connected. Which fails, and the timeouts are quite high for this.
However, while this causes a slow logon, it is not necessarily the root of your problems; as you have reported, this user has problems to connect to shares at all. I'd recommend to investigate this issue. Don't exclude network problems yet; being able to ping does not mean you're able to mount shares. Confirm with a different, working account.
Comment: I think you could be onto something. At the main site, all users can log on to any PC and their drives get mapped. At the remote site, there is a very long delay and a failure for drives to be mapped (I saw it work once or twice, but it they fail to map 95% of the time). I just did a test, and the account took 105 seconds to log on when the user had access to a security group (causing a script to attempt drive mapping at logon). When the user was removed from this group, logon time went down to 35 seconds (not fast, but maybe that's all I can hope for over VPN).
Comment: I'm going to create a new OU in Active Directory for the remote site, and exclude this PC (and others as they are set up at that location) from the drive mapping script. Only 3 domain users need this PC, so manually mapping the drives isn't too bad. Something else I forgot to add: the remote site connects via 3G. It's a *very* remote site...
Comment: A well thought out investigation. It seems your client is starved for bandwidth. You should try to get a better connection if the users need to access the shares regularly.
Comment: As a non-profit organziation with a limited budget, they are probably stuck with this 3G connection at that remote site. Fortunately, thanks to some great answers to my follow-up question (regarding using Group Policy to selectively map drives only when users log on to computers in the main office) I now have an elegant solution: Group Policy loopback processing: http://serverfault.com/questions/521145/gpo-not-applying-to-an-ou


cant install php55 imagick on centos 6.8 php-devel installed but missing

Question: i´m right about f*ing up my whole running system just for adding imagick to php  so here is where i am at. i want to use yum to install, i have enabled remi55 and loaded all necessary
php version
$php -v
PHP 5.5.34 (cli) (built: Mar 29 2016 19:27:57)
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies

gcc is installed
Package gcc-4.4.7-18.el6.x86_64 already installed and latest version

imagemagick and imagemagick-devel is installed
Package ImageMagick-188.8.131.52-6.el6.x86_64 already installed and latest version
Package ImageMagick-devel-22.214.171.124-6.el6.x86_64 already installed and latest version

php-devel seems to be installed
Package php55-php-devel-5.5.38-7.el6.remi.x86_64 already installed and latest version

even more stuff i installed
Package php55-php-pecl-imagick-3.4.3-1.el6.remi.x86_64 already installed
php55-php-pecl-xdebug.x86_64 0:2.5.3-2.el6.remi already installed

i dont know tryed a lot but when it comes to
pecl install imagick

i get an error
Starting to download imagick-3.4.3.tgz (245,410 bytes)
............................done: 245,410 bytes
19 source files, building
running: phpize
Can't find PHP headers in /usr/include/php
The php-devel package is required for use of this command.
ERROR: `phpize' failed

so ok, i try to yum install php-devel even i know i have php-devel for my php version and i get the following error :
--> Finished Dependency Resolution
Error: Package: php-pecl-jsonc-1.3.10-2.el6.remi.5.5.x86_64 (remi-php55)
           Requires: php(zend-abi) = 20121212-64
           Removing: php-common-5.5.34-1.el6.remi.x86_64 (@remi-php55)
               php(zend-abi) = 20121212-64
           Updated By: php-common-5.6.30-2.el6.remi.x86_64 (remi-test)
               php(zend-abi) = 20131226-64
           Available: php-common-5.3.3-49.el6.x86_64 (base)
               php(zend-abi) = 20090626
           Available: php-common-5.4.45-13.el6.remi.x86_64 (remi)
               php(zend-abi) = 20100525-x86-64
           Available: php-common-5.5.38-6.el6.remi.x86_64 (remi-php55)
               php(zend-abi) = 20121212-64
           Available: php-common-5.5.38-7.el6.remi.x86_64 (remi-php55)
               php(zend-abi) = 20121212-64
           Available: php-common-5.6.30-0.1.RC1.el6.remi.x86_64 (remi-test)
               php(zend-abi) = 20131226-64
Error: Package: php-pecl-jsonc-1.3.10-2.el6.remi.5.5.x86_64 (remi-php55)
           Requires: php(api) = 20121113-64
           Removing: php-common-5.5.34-1.el6.remi.x86_64 (@remi-php55)
               php(api) = 20121113-64
           Updated By: php-common-5.6.30-2.el6.remi.x86_64 (remi-test)
               php(api) = 20131106-64
           Available: php-common-5.3.3-49.el6.x86_64 (base)
               php(api) = 20090626
           Available: php-common-5.4.45-13.el6.remi.x86_64 (remi)
               php(api) = 20100412-x86-64
           Available: php-common-5.5.38-6.el6.remi.x86_64 (remi-php55)
               php(api) = 20121113-64
           Available: php-common-5.5.38-7.el6.remi.x86_64 (remi-php55)
               php(api) = 20121113-64
           Available: php-common-5.6.30-0.1.RC1.el6.remi.x86_64 (remi-test)
               php(api) = 20131106-64
Error: Package: php-pecl-zip-1.14.0-1.el6.remi.5.5.x86_64 (remi-php55)
           Requires: php(zend-abi) = 20121212-64
           Removing: php-common-5.5.34-1.el6.remi.x86_64 (@remi-php55)
               php(zend-abi) = 20121212-64
           Updated By: php-common-5.6.30-2.el6.remi.x86_64 (remi-test)
               php(zend-abi) = 20131226-64
           Available: php-common-5.3.3-49.el6.x86_64 (base)
               php(zend-abi) = 20090626
           Available: php-common-5.4.45-13.el6.remi.x86_64 (remi)
               php(zend-abi) = 20100525-x86-64
           Available: php-common-5.5.38-6.el6.remi.x86_64 (remi-php55)
               php(zend-abi) = 20121212-64
           Available: php-common-5.5.38-7.el6.remi.x86_64 (remi-php55)
               php(zend-abi) = 20121212-64
           Available: php-common-5.6.30-0.1.RC1.el6.remi.x86_64 (remi-test)
               php(zend-abi) = 20131226-64
Error: Package: php-pecl-zip-1.14.0-1.el6.remi.5.5.x86_64 (remi-php55)
           Requires: php(api) = 20121113-64
           Removing: php-common-5.5.34-1.el6.remi.x86_64 (@remi-php55)
               php(api) = 20121113-64
           Updated By: php-common-5.6.30-2.el6.remi.x86_64 (remi-test)
               php(api) = 20131106-64
           Available: php-common-5.3.3-49.el6.x86_64 (base)
               php(api) = 20090626
           Available: php-common-5.4.45-13.el6.remi.x86_64 (remi)
               php(api) = 20100412-x86-64
           Available: php-common-5.5.38-6.el6.remi.x86_64 (remi-php55)
               php(api) = 20121113-64
           Available: php-common-5.5.38-7.el6.remi.x86_64 (remi-php55)
               php(api) = 20121113-64
           Available: php-common-5.6.30-0.1.RC1.el6.remi.x86_64 (remi-test)
               php(api) = 20131106-64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

so i really go crazy and i dont know what to do now ?!
the thing i dont want to the the most is "remove all and install from scratch" as i said i got a working system with lots of sites involved, so if you have any idea let me know, sure i tried restarting httpd
i know i probably did not provide all required information but i didnt want to tldr;
after all php -m | grep image
returns nothing
heres the full output of php -m
[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dom
ereg
exif
fileinfo
filter
ftp
gd
gettext
gmp
hash
iconv
imap
intl
json
ldap
libxml
mbstring
mcrypt
mhash
mysql
mysqli
mysqlnd
odbc
openssl
pcntl
pcre
PDO
pdo_mysql
PDO_ODBC
pdo_sqlite
Phar
posix
readline
recode
Reflection
session
shmop
SimpleXML
sockets
SPL
sqlite3
standard
sysvmsg
sysvsem
sysvshm
tidy
tokenizer
wddx
xml
xmlreader
xmlrpc
xmlwriter
xsl
zip
zlib

Comment: `Package php55-php-pecl-imagick-3.4.3-1.el6.remi.x86_64 already installed` -- that should do it. Run `php -m` and see if imagick is in the output.
Comment: nope, unfortunatly it is not :*( i added the output of php -m
Comment: Run `rpm -ql php55-php-pecl-imagick-3.4.3-1.el6.remi.x86_64` to get a list of files in that package. One of them should be `imagick.so`
Comment: absolutely right ! it´s at   `/opt/remi/php55/root/usr/lib64/php/modules/imagick.so`

do i have to  refference this into httpd.conf ?  what would be the exact name like 'LoadModule imagick {path} ' ?
Comment: Make sure your `php.ini` contains `extension = imagick.so`.
Comment: get this error: `PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/imagick.so' - /usr/lib64/php/modules/imagick.so: cannot open shared object file: No such file or directory in Unknown on line 0`
Comment: i try to just copy it there
Comment: Make sure the permissions are set so that it's world-readable.
Comment: okay thank you so much, its getting better now, but still got this error `Version warning: Imagick was compiled against Image Magick version 1687 but version 1688 is loaded. Imagick will run but may behave surprisingly in Unknown on line 0`
Answer: Just disable remi-test (which have some 5.6 packages, so create conflicts).
yum-config-manager --disable remi-test
yum install php-pecl-imagick

BTW 5.5 is now EOL, so I strongly recommend you update to a maintained version.
php55-php-pecl-imagick is an SCL package for multiple versions installed simultaneously, you probably don't need this.
See the Wizard instructions.
Comment: EOL ^^ you´re absolutely right and i thank you for pointing that out, will do so asap. Also i had remi-test enabled so this definetly is the answer to my question. Thanks a lot


How can I show $F$ is not monotonic in any subinterval?

Question: I'm trying to solve Problem 1(b) of [Fourier Analysis] by Stein. The problem is as follows:
Choose a countable dense sequence ${r_n}$ in $[0,1]$. Consider
$\displaystyle{F(x)=\sum_{n=1}^\infty3^{-n}g(x-r_n)}$,
where $g(x)=\sin(1/x)$ when $x\neq0$, and $g(0)=0$. Then $F$ fails to be monotonic in any subinterval of $[0,1]$.
The Author gives as a hint $3^{-k}>\sum_{n>k}3^{-n}$. But I cannot figure out how to use this hint. Since $F$ is a superposition of highly oscillating functions, it seems that $F$ is not monotonic.
Comment: The hint says that if one term $3^{-k}g(x-r_k)$ goes through a "full period" (that is, assumes both the values $\pm 3^{-k}$) on a given interval, then the sum $\sum_{n=k+1}^\infty 3^{-n}g(x-r_n)$ is too small to ruin the non-monotonicity of $3^{-k}g(x-r_k)$ in that interval.
Comment: Then what about $\sum_{n=1}^{k-1}3^{-n}g(x-r_n)$?
Answer: Let a small subinterval $I$ of $[0,1]$ be given, and let $k$ be the least number such that $r_k$ is in that interval. Now, $f_k(x)=\sum_{n=1}^{k-1}3^{-n}g(x-r_n)$ is continuous on $I$, so there exists a subinterval $[r_k,r_k+\varepsilon]$ of $I$ such that $f_k(x)$ varies by at most $3^{-k}/100$ on that interval. The function $3^{-k}g(x-r_k)$ however varies by $3^{-k}$ infinitely many times on this interval, and the remainder $\sum_{n=k+1}^\infty 3^{-n}g(x-r_n)$, by the hint in the book, is too small to destroy these variations. It follows that the full sum $\sum_1^\infty$ is non-monotonic on the interval $[r_k,r_k+\varepsilon]\subseteq I$.
Comment: What's the $3^{-k}/100$ mean?
Answer: It is sufficient to show that $F(x)$ is almost nowhere differentiable, since
a theorem of Lebesgue gives that a monotonic function over an interval $I$ is almost everywhere differentiable over $I$.


How can I prevent foundation watch from adding html  stuff to my file?

Question: Using foundation 6. When I have watch running, whenever I make changes to my index.html file, it puts a copy in the dist folder with an added  section. I already have a  and don't need this!
How can I prevent this behaviour?
<!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="assets/css/app.css">

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SoapMaker</title>
    <link rel="stylesheet" href="assets/css/app.css">

Comment: Please provide some info about your template file and setup.
Answer: Foundation site docs have great examples.
The Layouts folder contains a default.html file with the headers in it.
The Pages folder contains your pages with only content - no header stuff there.
If you look in default.html, you will see after the body tag several panini bracketed files to be included in every page including one called body.
I usually create  header, menu, and footer files that will show on every page.

{{> header}}
{{> mainMenu}}
{{> body}}
{{> footer}}

Comment: Thanks Bill. I'll have a look. Haven't tried panini before (I used to do something similar with php includes).


Calculadora Javascript

Question: Estou criando uma calculadora clone igual do iPhone, até a parte de digitar o primeiro valor da operação está ok, o problema é quando eu vou pra segunda parte (depois de escolher um operador, como +, -, /, *), eu preciso que pare de adicionar na variável valor1 e comece adicionar na variável de valor2, como faz isso?

let visor = document.querySelector(".calculadora__visor");
let calcular = document.querySelector(".calculadora__botao_cal");
let ac = document.querySelector(".calculadora__botao-AC");

let firstCLick = true
let secondClick = false
let valor1 = []
let valor2 = []
let operacao = []

for (let btn = 0; btn <= 9; btn++) {
  let botao = document.querySelector(`.calculadora__botao${btn}`)
  botao.addEventListener("click", () => {
    if (firstCLick) {
      visor.textContent = ""
      firstCLick = false
    }
    valor1 = visor.textContent += btn;
    for (let op = 1; op <= 4; op++) {
      let operador = document.querySelector(`.botao__op${op}`)
      operador.addEventListener("click", () => {
        visor.textContent = ""
        if (secondClick === false) {
          valor2 = visor.textContent += btn
        }
      })
    }
  })
}

ac.addEventListener("click", () => {
  firstCLick = true
  visor.textContent = 0
})
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./reset.css">
  <link rel="stylesheet" href="./style.css">
  <title>Calculadora</title>

    0

      <button class="calculadora__botao calculadora__botao-AC">AC</button>
      <button class="calculadora__botao calculadora__botao-mais-menos">+/-</button>
      <button class="calculadora__botao calculadora__botao-porc">%</button>
      <button class="calculadora__botao calculadora__botao-div botao__op4">/</button>
      <button class="calculadora__botao calculadora__botao7">7</button>
      <button class="calculadora__botao calculadora__botao8">8</button>
      <button class="calculadora__botao calculadora__botao9">9</button>
      <button class="calculadora__botao calculadora__botao-x botao__op3">x</button>
      <button class="calculadora__botao calculadora__botao4">4</button>
      <button class="calculadora__botao calculadora__botao5">5</button>
      <button class="calculadora__botao calculadora__botao6">6</button>
      <button class="calculadora__botao calculadora__botao-menos botao__op2">-</button>
      <button class="calculadora__botao calculadora__botao1">1</button>
      <button class="calculadora__botao calculadora__botao2">2</button>
      <button class="calculadora__botao calculadora__botao3">3</button>
      <button class="calculadora__botao calculadora__botao_somar botao__op1">+</button>
      <button class="calculadora__botao calculadora__botao0">0</button>
      <button class="calculadora__botao calculadora__botao3">,</button>
      <button class="calculadora__botao calculadora__botao_cal">=</button>

Comment: Adicione a parte do HTML também. Vá em [edit] a pergunta e pressione Ctrl+M
Answer: 1 - Inicialize as variáveis valor1, valor2 e operador com valores padrão. Por exemplo, valor1 = 0, valor2 = null e operador = null.
2 - Ao digitar um número, verifique o estado atual do operador:
3 - Se operador for null, significa que você ainda está na fase de entrada do primeiro valor da operação. Nesse caso, adicione o número digitado à variável valor1.

Se operador não for null, isso significa que você já selecionou um operador e está na fase de entrada do segundo valor da operação. Nesse caso, adicione o número digitado à variável valor2.
Quando o usuário selecionar um operador, atualize a variável operador com o operador escolhido.

4 - Ao realizar a operação matemática, verifique se valor1 e valor2 são válidos (ou seja, diferentes de null). Se ambos forem válidos, execute a operação desejada (por exemplo, adição, subtração, multiplicação ou divisão) usando os valores de valor1 e valor2. O resultado pode ser armazenado novamente em valor1 para continuar a operação, se necessário.
Essa abordagem permite que você alterne entre a entrada de valor1 e valor2 com base no estado do operador. Dessa forma, você pode separar as entradas dos dois valores e realizar a operação matemática correta.
Comment: cara, você me ajudou muito!!!

Eu estava "quase no caminho certo", tenho que treinar minha lógica...
Mas muito obrigado!!!!

Calculadora Javascript


Python Extract Value from Json

Question: I Need to Exact Value from Json response
Json Response:
{
"data": {
"plot": "Rudy has always been told that he was too small to play college football. But he is determined to overcome the odds and fulfill his dream of playing for Notre Dame.",
"name": "Rudy",
"rating": "7.5",
"genre": "Biography,Drama,Sport",
"poster_url": "https://images-na.ssl-images-amazon.com/images/M/MV5BZGUzMDU1YmQtMzBkOS00MTNmLTg5ZDQtZjY5Njk4Njk2MmRlXkEyXkFqcGdeQXVyNjc1NTYyMjg@._V1_UY268_CR5,0,182,268_AL_.jpg"
     }
}

Python Code:
response = requests.get(
    "http://theapache64.xyz:8080/movie_db/search?keyword=Titanic")
json_data = json.loads(response.text)

print(json_data["plot"])

Error:
KeyError: 'plot'

I need to extract "plot" value
Answer: plot is inside data:
print(json_data['data']['plot'])

Python Extract Value from Json


What is the best way to add a confirmation tooltip to the remove button of a managed_file field?

Question: Another Update
I'm trying to implement the solution found here: Intercept click event on a button, ask for confirmation, then proceed, but the remove button still submits normally. I know my JS is targeting the correct element, because I can change other attributes on it like the background color.
Here's my form:
function form_experiments_01() {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'form_experiments') . '/js/form_experiments.js',
  );

  $form['managed_files'] = array(
    '#type' => 'fieldset',
    '#title' => t('Managed Files'),
  );

  $num_docs = 3;
  for ($i = 1; $i <= $num_docs; $i++) {
    $form['managed_files'][$i] = array(
      '#type' => 'managed_file',
      '#title' => 'Managed File ' . $i,
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

Here's my javascript:
(function ($) {
  Drupal.behaviors.managedFileAutoUpload = {
    attach: function(context, settings) {
      $('.form-item input.form-submit[value=Upload]', context).hide();
      $('.form-item input.form-file', context).change(function() {
        $parent = $(this).closest('.form-item');

        //setTimeout to allow for validation
        //would prefer an event, but there isn't one
        setTimeout(function() {
          if(!$('.error', $parent).length) {
            $('input.form-submit[value=Upload]', $parent).mousedown();
          }
        }, 100);
      });
    }
  };

  Drupal.behaviors.managedFileConfirmRemove = {
    attach: function(context, settings) {
      var myButton = $('.form-item input.form-submit[value=Remove]', context);

      if (myButton.length > 0) {
        var myClick = null;

        //get a list of jQuery handlers bound to the click event
        var jQueryHandlers = myButton.data('events').click;

        console.log(jQueryHandlers);

        //grab the first jquery function bound to this event
        $.each(jQueryHandlers,function(i,f) {
          myClick = f.handler;
          return false;
        });

        //unbind the original
        myButton.unbind('click');

        //bind the modified one
        myButton.click(function(){
          if(window.confirm("Are You Sure?")){
            myClick();
          } else {
            return false;
          }
        });
      }
    }
  }
})(jQuery);

Update
After some more research I found this question. This is what I was trying to ask but didn't know how to word.
Intercept click event on a button, ask for confirmation, then proceed
I'll implement this solution and post a resolution once I've got it working.
Description
I would like to add a confirmation tooltip when the "remove" button is clicked on my managed_file field.
I would like to do something similar to this:

What is the best way to do that?
Possible Solution?
So far, I'm thinking I could probably use javascript to hide the remove button and instead display my own button. Then when my button is clicked, I can trigger a popup that contains a second custom button to cancel and the remove button that I originally hid.
I'm worried that this solution is a bit messy. Is there a more elegant way to do this? Can I get a similar behavior without hiding the original remove button?
Similar Questions
I'm not sure if these apply to my use-case since I'm working with a managed_file field. So far, I've been unable to implement similar solutions without the default behavior of the remove button interfering.

Confirm delete via AJAX
enter link description here

Resources

Bootstrap-Confirmation.js
Drupal Form API Reference - managed_file
Comment: There is no specific 'Drupal' way to do this, Your best best is to use javascript to prevent the submission when clicked, show your popup and on confirm trigger the original remove button with the JS.
Answer: Use this code to delay submit and display popup before submitting.
$("form").submit( function () {
   //display tooltip something
   return true;
 }

Something like this:
$('.form-item input.form-submit[value=Remove]').submit {
  if (window.confirm("Are You Sure?")) {
    myClick();
  } else {
    return false;
  }
}


Python - Como calcular o antecessor de um número?

Question: Elabore uma função chamada antecessor que receba como parâmetro único um número inteiro a  e que imprima o seu antecessor.
Entrada
A entrada consiste de uma única linha contendo o número inteiro da entrada a (10^-5<a<10^5).
Saída
Imprima em uma única linha o antecessor de a.
Eu fiz assim, mas não tá dando certo.
def antecessor(a):
    ant = a - 1
    print(ant)

a = int(input())
antecessor(a)

Comment: Eu executei o seu código, para mim funcionou. Qual a mensagem de erro que está recebendo?
Comment: Se enunciado é exatamente esse *...Elabore uma função chamada antecessor que receba como parâmetro único um número inteiro a e que imprima o seu antecessor....* não tem nada de errado com o seu código. Agora se o enunciado for algo levemente diferente, exemplo *...Elabore uma função chamada antecessor que receba como parâmetro único um número inteiro a e que retorne o seu antecessor....* ai então você tem um problema.
Answer: Fica difícil entender sem o código de erro, porém vou tentar ajudar:

Você poderia utilizar Loop While assim:

def read_input(num):
    while True:
        try:
            c = int(input(num))
        except (ValueError, TypeError):
            print("\033[31mERRO! Por favor digite um numero inteiro...\033[m")
            continue
        except (KeyboardInterrupt):
            print("\033[31mEntrada de valor interrompida, por favor, reinicie o programa\033[31m")
            break
        else:
            return c

while True:
    numero = read_input('Digite um numero: ')
    antecessor = numero - 1
    print(f'O antecessor de seu numero é {antecessor}')

Neste exemplo eu também utilizei a função criada para tratar erros caso o usuário digite uma variavel diferente de int, read_input(). Mas ela não precisa ser utlizada, como neste exemplo:
while True:
    numero = int(input('Digite um numero: '))
    antecessor = numero - 1
    print(f'O antecessor de seu numero é {antecessor}')

Basicamente o loop while está sendo utilizado apenas para manter o programa rodando, mas ele não é necessário:
numero = int(input('Digite um numero: '))
antecessor = numero - 1
print(f'O antecessor de seu numero é {antecessor}')

Utilizando a criação de funções

def calc_antecessor():
    numero = int(input('Digite um numero: '))
    antecessor = numero - 1
    print(f'O antecessor de seu numero é {antecessor}')

calc_antecessor()

Você também poderia utilizar aqui o loop while, o colocando antes de chamar a função
Você poderia juntar tudo, como a criação de funções, loop while e tratamento de erro desta forma:
def read_input(num):
    while True:
        try:
            c = int(input(num))
        except (ValueError, TypeError):
            print("\033[31mERRO! Por favor digite um numero inteiro...\033[m")
            continue
        except (KeyboardInterrupt):
            print("\033[31mEntrada de valor interrompida, por favor, reinicie o programa\033[31m")
            break
        else:
            return c

def calc_antecessor():
    numero = read_input('Digite um numero: ')
    antecessor = numero - 1
    print(f'O antecessor de seu numero é {antecessor}')

while True:
    calc_antecessor()

Answer: a = int(input('Digite um número: '))
b = a - 1
print('O antecessor de ', a, ' é ', b)

Seria isso?


Change product slug of a WooCommerce product - WPML

Question: I am using WPML and I want to change the slug of my product . basically I want to keep same slug for a product for all languages.When ever I change it , slug gets assigned with appended -en or -no as per language. I dont want this -en to get appended.
How to solve it?
Answer: check this URL please hope you will get some solution
https://wpml.org/forums/topic/how-can-i-change-product-and-shop-url-slug/


How to hide a sub level menu from being expanded?

Question: When a menu is active, drupal displays the sub-menus of the active menu, but because I use the sub-menus in a separate block via the "menu block" module, I don't want the sub-menu to be shown. How can I do it on server side?
Is there an easy drupal way to do it without touching the theme_menu_link? If not, Is there a way to do it in a module rather in template.php? beside, can some one show me how to write the code?
Answer: In the Add/Edit menu_block options, you can specify the Maximum depth of the menu tree to 1.
Comment: So you actually suggest to use menu_block also for the main menu. good idea
Comment: Yup. It makes working with menus easier.


Can I use a token within a custom token?

Question: I am trying to create a custom token that modifies another token.
$theDomainName = "[domain-name-raw]"; //Pull in the other token
$removeCounty = str_replace(" County", "", $theDomainName); //Replace " County" with nothing
$countyPlus = str_replace(" ", "+", $removeCounty); //Replace " " with "+"
return $countyPlus; //Return modified token as new custom token to be used through out site

If I use [domain-name-raw] for $theDomainName, my result is the original token (e.g. "Cerro Gordo County"). If I type what [domain-name-raw] should output for $theDomainName (e.g. "Cerro Gordo County"), my code works fine (it outputs "Cerro+Gordo"). What is going on?
I am using Drupal 6.
Answer: You could use something like token_replace() to get the other token value within your own token, but you shouldn't try to alter an already created token, as that will mess up when you really want to use that token.
You need to define you own token, and handle the output of that token. But in doing so, you will most likely find that it will be easier to get the raw values from the PHP values supplied instead of using token_replace() or something similar.
You need to look at hook_token_list() and hook_token_values() to define your custom token.


Javascript mouse event handlers not functioning properly on my android touch phone

Question: I am working on creating a scratch card script in javascript
mouse event handlers is working properly on pc but it is not on my touch phone.
on pc , i hold down the left mouse button and move it around to scratch the card.
on touch phone , It scratches only if i keep touching and releasing my finger on the phone screen.

;(function() {
  var global = this;
  function ScratchCard(element, options, ownerDocument) {

    // apply default arguments.
    var defaultOptions = {
      'color': 'gray',
      'radius': 20
    };
    if (options) {
      for (var key in defaultOptions) {
        if (!(key in options)) {
          options[key] = defaultOptions[key];
        }
      }
    } else {
      options = defaultOptions;
    }
    ownerDocument = ownerDocument || global.document;

    // canvas validate.
    var canvas = document.createElement('canvas');
    if (typeof canvas.getContext != 'function')
      return console.log('Canvas not supported.');

    // apply canvas offset & size of element
    var rect = element.getBoundingClientRect();
    canvas.width = rect.width || rect.right - rect.left
    canvas.height = rect.height || rect.bottom - rect.top;
    canvas.style.top = rect.top + 'px';
    canvas.style.left = rect.left + 'px';
    canvas.style.position = 'absolute';
    canvas.style.zIndex = +element.style.zIndex + 1;

    // fill the canvas
    var context = canvas.getContext('2d');
    context.fillStyle = options.color;
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.globalCompositeOperation = "destination-out";
    context.strokeStyle = "rgba(0,0,0,1)";

    // add mouse events to canvas
    // TODO: supply touch events
    // TODO: scratch from the outside
    function scratchStart(event) {
      if (event.button != 0) // not left button
        return;

      var x = event.offsetX || event.layerX;
      var y = event.offsetY || event.layerY;

      context.beginPath();
      context.arc(x, y, options.radius, 0, Math.PI * 2);
      context.fill();

      canvas.addEventListener('mousemove', scratchMove);
      canvas.addEventListener('touchmove', scratchMove);
      document.addEventListener('mouseup', scratchEnd);
      document.addEventListener('touchend', scratchEnd);
    }

    function scratchMove(event) {
      var x = event.offsetX || event.layerX;
      var y = event.offsetY || event.layerY;

      context.beginPath();
      context.arc(x, y, options.radius, 0, Math.PI * 2);
      context.fill();
    }

    function scratchEnd(event) {
      canvas.removeEventListener('mousemove', scratchMove);
      canvas.removeEventListener('touchmove', scratchMove);
      document.removeEventListener('mouseup', scratchEnd);
      document.removeEventListener('touchend', scratchEnd);

    }

    canvas.addEventListener('mousedown', scratchStart);
    canvas.addEventListener('touchstart', scratchStart);

    // disable element interaction
    ['MozUserSelect',
     'msUserSelect',
     'oUserSelect',
     'webkitUserSelect',
     'pointerEvents']
      .filter(function (cssProp) {
        return cssProp in element.style;
      }).forEach(function (cssProp) {
        element.style[cssProp] = 'none';
      });

    // append canvas to body.
    document.body.appendChild(canvas);
  }

  if (typeof module == 'object' && module.exports) {
    // Node.js module
    module.exports = ScratchCard;
  } else if (typeof define == 'function' && (define.amd || define.cmd)) {
    // AMD or CMD module
    define(ScratchCard);
  } else if (typeof jQuery == 'function' && typeof jQuery.extend == 'function') {
    // jQuery plugin
    jQuery.fn.extend({
      'ScratchCard': function (options) {
        return this.each(function (element) {
          ScratchCard(element, options);
        });
      }
    });
  } else if (typeof angular == 'object' && typeof angular.module == 'function') {
    // AngularJS module
    // TODO: modify it to a directive.
    angular.module('ScratchCard', [])
      .value('ScratchCard', ScratchCard);
  } else {
    // Apply to a global variable.
    if (global.ScratchCard) {
      (function (oldScratchCard) {
        ScratchCard.noConflict = function () {
          global.ScratchCard = oldScratchCard;
          return ScratchCard;
        };
      }) (global.ScratchCard);
    }
    global.ScratchCard = ScratchCard;
  }
}).call(this);
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

  <title>ScratchCard Demo</title>

I do not know what is wrong with this code but i really need help on that one.
Answer: To ensure you don't end up with unintended behavior, detect what device is being used and only add event listeners for that device. If you are using touchscreen, then do not add mouse event listeners, and vice-versa.
The rest looks technically correct, you are using touchstart to create the touchmove event listener, then on touchend you remove the touchmove listener. The touchmove would be the only event that contains the scratchMove code, so that should all be good.
I would mostly concentrate on the first paragraph here and only set up event listeners that are related to the device/environment.
In your javascript, you can add this assignment:
var isTouch = 'ontouchstart' in document.documentElement;

Then in each place you are assigning the events, do this:
   if(isTouch) {
      canvas.addEventListener('touchmove', scratchMove);
      document.addEventListener('touchend', scratchEnd);
   } else {
      canvas.addEventListener('mousemove', scratchMove);
      document.addEventListener('mouseup', scratchEnd);
   }

Comment: But i want to be able to use the code for both devices , PC and touch screen phone.
Comment: You could use it for both, it would detect at run-time which device is currently loading the page and only use the events appropriate for that device at run-time.
Comment: So the code here is correct ? if so , why it is not functioning properly ??
Comment: Because, like I said, the events could be getting crossed due to having both click and touch events. Some devices might register both and may be firing the events in an unpredictable way. See my edit above.
Comment: in var isTouch is documentElement here is canvas ??
Comment: It is checking to see if `ontouchstart` is an available event for the current instance. It is basically checking to see if you are loading the site on a device that has the `ontouchscreen` event available to it.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/113357/discussion-between-wfareed-and-gmiley).


Atualizar o primeiro input ao inserir

Question: Tenho este formulário:
<form name="form1" class="teste" class="form-validate" id="feedback_form1">

         <fieldset>

                <legend>

                        Esquecimento

 <fieldset class="grupo">

        Número de Esquecimento
        <input readonly="true" id="NumEsq" name="NumEsq" style="width:100px"
<?php
         $sql = "SELECT NumEsq FROM centrodb.Esquecimento ORDER BY NumEsq DESC LIMIT 1";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.($ln['NumEsq']+1).'"';
         }
      ?>>

            Data/Hora
            <input type="datetime" id="Data" name="Data" style="width:160px; height: 35px" value="<?php echo date("Y-m-d H:i:s");?>"/>

        Responsável
        <select id="Responsavel" name="Responsavel" style="width:150px">
       <option></option>
        <?php
         $sql = "SELECT * FROM centrodb.UtilizadoresDPO";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.$ln['Id'].'">'.$ln['Nível'].'</option>';
         }
      ?>

        Tipo de Atividade
        <select id="Atividade" name="Atividade" style="width:150px">
       <option></option>
        <?php
         $sql = "SELECT * FROM centrodb.AtividadesDPO";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.$ln['Id'].'">'.$ln['Atividade'].'</option>';
         }
      ?>
    </select>

        </fieldset>
        <fieldset class="grupo">

        Aplicação
        <select id="Aplicacao" name="Aplicacao" style="width:150px">
       <option></option>
        <?php
         $sql = "SELECT * FROM centrodb.TipoBDDPO";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.$ln['Id'].'">'.$ln['BaseDados'].'</option>';
         }
      ?>
    </select>

        Instituição
        <select id="Instituicao" name="Instituicao" style="width:400px">
       <option></option>
        <?php
         $sql = "SELECT * FROM centrodb.Instituicao";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.$ln['Id'].'">'.$ln['Instituicao'].'</option>';
         }
      ?>
    </select>

        Valência
    <select id="Valencia" name="Valencia" style="width:150px">
        <option></option>
        <?php
            $sql = "SELECT descricaovalencia  FROM centrodb.utentes GROUP BY descricaovalencia";
            $qr = mysqli_query($conn, $sql);
            while($ln = mysqli_fetch_assoc($qr)){
                echo '<option value="'.$ln['descricaovalencia'].'"> '.$ln['descricaovalencia'].'</option>';
            }
            ?>
    </select>

        </fieldset>
        <fieldset class="grupo">

      Funcionalidade
        <select id="Funcionalidade" name="Funcionalidade" style="width:400px">
       <option></option>
        <?php
         $sql = "SELECT * FROM centrodb.FuncionalidadeDPO";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.$ln['Id'].'">'.$ln['Funcionalidade'].'</option>';
         }
      ?>
    </select>

    Entidade
    <select id="Entidade" name="Entidade" style="width:150px">
        <option></option>
    </select>

 </fieldset>
 <fieldset class="grupo">

        Motivo do Esquecimento
        <textarea type="text" id="Observacoes" name="Observacoes" rows="3" cols="90"></textarea>

 </fieldset>
         <button class="btn btn-success btn_contact botao">Registo</button>

sucessso

erro

</form>

Nesta página tenho o seguinte script:
(function ($) {$(document).ready(function(){
$("#feedback_form1").submit(function(e){

e.preventDefault();

var Responsavel = form1.Responsavel.value;
var Atividade = form1.Atividade.value;
var Aplicacao = form1.Aplicacao.value;
var Instituicao = form1.Instituicao.value;
var Valencia = form1.Valencia.value;
var Funcionalidade = form1.Funcionalidade.value;
var Entidade = form1.Entidade.value;
var Observacoes = form1.Observacoes.value;

if (!Responsavel) {
alert('Preencha o campo com o Responsavel');
form1.Responsavel.focus();
return false;
}
if (!Atividade) {
alert('Preencha o campo com a Atividade');
form1.Atividade.focus();
return false;
}
if (!Aplicacao) {
alert('Preencha o campo com a Aplicacao');
form1.Aplicacao.focus();
return false;
}
if (!Instituicao) {
alert('Preencha o campo com a Instituicao');
form1.Instituicao.focus();
return false;
}
if (!Valencia) {
alert('Preencha o campo com a Valencia');
form1.Valencia.focus();
return false;
}
if (!Funcionalidade) {
alert('Preencha o campo com a Funcionalidade');
form1.Funcionalidade.focus();
return false;
}
if (!Entidade) {
alert('Preencha o campo com a Entidade');
form1.Entidade.focus();
return false;
}
if (!Observacoes) {
alert('Preencha o campo com a Observação');
form1.Observacoes.focus();
return false;
}
            $.ajax({
                    type: "POST",
                    url: "./Inserir40",
                    data: $("#feedback_form1").serialize(), // serializes the form's elements.
                    dataType: "json",
                    success: function (data)
                    {
                        $(".success_messages").removeClass('hide'); // success message
                        $("#NumEsq").val(data["numEsq"]);

                        },
                    error: function(data){
                            $(".error_message").removeClass('hide'); // error message
                        },
                    complete: function()
                    {
                         $('#Responsavel').val(''); //clear text
                         $('#Atividade').val(''); //clear text
                         $('#Aplicacao').val(''); //clear text
                         $('#Instituicao').val(''); //clear text
                         $('#Valencia').val(''); //clear text
                         $('#Funcionalidade').val(''); //clear text
                         $('#Entidade').val(''); //clear text
                         $('#Observacoes').val(''); //clear text
                    }

                });

            });
 });
 })(jQuery);

Depois tenho outro arquivo php onde faço a inserção dos  dados:
<?php
$NumEsq = isset($_POST["NumEsq"]) ? $_POST["NumEsq"] : '';
$Data = isset($_POST["Data"]) ? $_POST["Data"] : '';
$Responsavel = isset($_POST["Responsavel"]) ? $_POST["Responsavel"] : '';
$Atividade = isset($_POST["Atividade"]) ? $_POST["Atividade"] : '';
$Aplicacao = isset($_POST["Aplicacao"]) ? $_POST["Aplicacao"] : '';
$Instituicao = isset($_POST["Instituicao"]) ? $_POST["Instituicao"] : '';
$Valencia = isset($_POST["Valencia"]) ? $_POST["Valencia"] : '';
$Funcionalidade = isset($_POST["Funcionalidade"]) ? $_POST["Funcionalidade"] : '';
$Entidade = isset($_POST["Entidade"]) ? $_POST["Entidade"] : '';
$Observacoes = isset($_POST["Observacoes"]) ? $_POST["Observacoes"] : '';

$sql = "INSERT INTO centrodb.Esquecimento (`NumEsq`,`Data`,`Responsavel`,`Atividade`,`Aplicacao`,`Instituicao`,`Valencia`,`Funcionalidade`,`Entidade`,`Observacoes`)
VALUES ('$NumEsq','$Data','$Responsavel','$Atividade','$Aplicacao','$Instituicao','$Valencia','$Funcionalidade','$Entidade','$Observacoes')";
$qr = mysqli_query($conn, $sql);

$conn->close();

$success["NumEsq"]=(int)$NumEsq + 1;
echo json_encode($success);
?>

Tudo funciona bem, como inserir os dados e como limpar o formulário.
Este é o formulário:

O problema que tenho é que ao inserir pretendo atualizar o input que está rodeado a vermelho no formulário automaticamente.
Esse input soma 1 ao último registo inserido na tabela da base de dados.
Comment: Qual erro que da?
Answer: Acredito que o erro esteja aqui:
success: function (data)
{
    $(".success_messages").removeClass('hide');
    $("#NumEsq").val(data["numEsq"]);

},

O retorno do data está sendo objeto e não array, o correto seria:
$("#NumEsq").val(data.numEsq);

ou
data = JSON.parse(data);
$("#NumEsq").val(data.numEsq);

E não:
$("#NumEsq").val(data["numEsq"]);

Atualizar o primeiro input ao inserir


Will records in a particular match be discarded if the bowler is called for throwing?

Question: A Bowler is called for throwing while he took 4 wickets and a hat trick.
Will it be neglected and the records he made in that match are discarded if he is declared throwing?
Answer: I am struggling to find a reference but the answer would be no.  The statistics would remain, the logic would be that those must have been legitimate deliveries as the umpire/s did not no ball them.
Looking at the evidence this is supported by Muralis statistics from the match where he was called for throwing.


Example of a finite commutative ring $R$ and an ideal $I$ where $I$ is maximal but not prime?

Question: Example of a finite commutative ring $R$ whose maximal ideal $I$ is not prime?
Is it possible? I am not able to find such example.
Comment: You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: Right after I answered I noticed a very good duplicate in the items to the right. Among the solutions is the one I offered ($2\mathbb Z/4\mathbb Z$), plus more.
Comment: @hardmath I came up with a compromise, considering the asker's difficulty seeing the connection.
Comment: @Kangmin If you had read the solutions at the duplicates, you would have noticed that [this solution](https://math.stackexchange.com/a/452698/29335) already does what you want. So indeed, your question is already answered elsewhere.  Therefore a duplicate link is useful.
Answer: This is only possible if you ring lacks an identity.
Perhaps you didn't notice, but this is trivially derived from this solution, where
$R=2\mathbb Z$ and $M=4\mathbb Z$ is given as an example, but obviously in the quotient $R/M$ has order $2$ and its zero ideal is maximal and nonprime.
Similarly this question can be adapted by saying $R=6\mathbb Z/12\mathbb Z$ has a maximal nonprime zero ideal (it is isomorphic to the ring above, as a matter of fact.)
And in fact this solution is exactly what you're asking for.  So remember when you are reading duplicates, check their solutions too, because sometimes they do more than what the question asks of them.
Answer: No, it's not possible. For any commutative ring with $1$, any maximal ideal is prime.
Hint. use characterization of prime/maximal ideals in terms of quotient rings