Cowboy/Ranch kills handler process when client closes connection

Question: I have Phoenix application with complex business logic behind HTTP endpoint. This logic includes interaction with database and few external services and once request processing has been started it must not be interrupted till all operations will be done.
But it seems like Cowboy or Ranch kills request handler process (Phoenix controller) if client suddenly closes connection, which leads to partially executed business process. To debug this I have following code in controller action:
Process.flag(:trap_exit, true)

receive do
  msg -> Logger.info("Message: #{inspect msg}")
after
  10_000 -> Logger.info("Timeout")
end

And to simulate connection closing I set timeout: curl --request POST 'http://localhost:4003' --max-time 3.
After 3 seconds in IEx console I see that process is about to exit: Message: {:EXIT, #PID<0.4196.0>, :shutdown}.
So I need to make controller complete its job and reply to client if it is still there or do nothing if connection is lost. Which will be the best way to achieve this:

trap exits in controller action and ignore exit messages;
spawn not linked Task in controller action and wait for its results;
somehow configure Cowboy/Ranch so it will not kill handler process, if it is possible (tried exit_on_close with no luck)?
Answer: Handling processes will be killed after the request end, that is their purpose. If you want to process some data in the background, then start additional process. The simplest way to do so would be 2nd method you have proposed, but with slight modification of using Task.Supervisor.
So in your application supervisor you start Task.Supervisor with name of your choice:
children = [
  {Task.Supervisor, name: MyApp.TaskSupervisor}
]

Supervisor.start_link(children, strategy: :one_for_one)

And then in your request handler:
parent = self()
ref = make_ref()

Task.Supervisor.start_child(MyApp.TaskSupervisor, fn() ->
  send(parent, {ref, do_long_running_stuff()})
end)

receive do
  {^ref, result} -> notify_user(result)
end

That way you do not need to worry about handling situation when user is no longer there to receive message.


SQL query where column is value or null

Question: I'm trying to write dynamic query which should work for all scenario. where it has to pick 1 record if the param value is not null. I'm trying something like below but still it's picking all records, instead of picking 4th record.
table
idex    column1 column2 column3 column4
1       HG      null    null    null
2       HG      HD      null    null
3       HG      H9      null    null
4       HG      HD      H9      null

declare v1 varchar(10) = 'HG'
declare v2 varchar(10) = 'HD'
declare v3 varchar(10) = 'H9'
declare v4 varchar(10) = null

select * from table
where   (column1 is null or column1 = v1)
    and (column2 is null or column1 = v2)
    and (column3 is null or column1 = v3)
    and (column4 is null or column1 = v4)

Comment: Your  logic here seems to be flawed. You are checking the value of column1 all for times...I have a feeling that is part of the problem. But your question is just unclear what you want as output.
Comment: I removed the conflicting mysql and sql server tags. Please edit your question and put in the tag for the DBMS you are actually using.
Comment: MySQL is a totally different product to SQL Server - please correct your tags so the right experts look at your post.
Comment: And if this is SQL Server your variables should begin `@`
Comment: Ideally provide the DDL+DML to create the sample data so people can test.
Comment: I believe the logic you are looking for is `where (@v1 is null or column1 = @v1) and ...`. If a filter parameter is null, any column value is accepted.  If a filter value is not null, the associated column value must match.
Comment: How did you get on?
Answer: You need to check that both the column value and the variable value are null or equal e.g.
select *
from MyTable
where ((column1 is null and @v1 is null) or column1 = @v1)
and ((column2 is null and @v2 is null) or column2 = @v2)
and ((column3 is null and @v3 is null) or column3 = @v3)
and ((column4 is null and @v4 is null) or column4 = @v4)

And you need to correct your column names which were all column1 in the compare, and assuming SQL Server your variable definitions.
DBFiddle - note providing this in future makes it much easier for people to answer.

SQL query where column is value or null


Store Images in App_Data and address them absolute make errors

Question: I've generated an image tag like below:

and the result is somrthing like this:

The problem is I only see blank space and no image at all(in firefox I only see alt text). the path is correct. I copied the img tag itself into another html file and I see the image crystal clear.
somrthing that might help: I opened the source with firefox and when I clicked on source of image I got following error:

Firefox doesn't know how to open this address, because the protocol
  (c) isn't associated with any program.

and sorry for terrible english by the way.
Edit: I Edited the title. It is make more sence now!
Comment: where does `SourceAddress` come from and how is it set?
Comment: It is stored in database. It shows the path to the image. I've stored the images in App_Data folder and their paths in database.
Answer: This may be due to you providing a local path name (i.e. a directory in C:) rather than a relative path via Razr.  If you start debug in Firefox then the console output sometimes eludes to this.
You could try something similar to:

And check that SourceAddress is in the format of:
~/MyImages/Photos/test.jpg

Also worth checking all the obvious things like double quotes over single quotes etc.
Comment: Edited because I really wasn't being helpful!
Answer: Finally found out what is the problem!

First of all I used App_Data Folder to store files. this folder is special purpose and is used to store some special database files and IIS wont give direct access to this folder. and I had to make another folder like Image and store files there.

Second problem is I gave the path directly from Root (C:\...). The Web Browser doesen't have access to the Server File System Directly (Due to some security reasons). Because of this I had to gave the path relative address. The absolut path should be used by Server Code only and not in html source.
I managed to convert absolute path to relative like below:

`public static class HttpServerUtilityExtensions
{
    public static string RelativePath( this HttpServerUtilityBase utility, string path, HttpRequestBase context )
    {
        return path.Replace( context.ServerVariables[ "APPL_PHYSICAL_PATH" ], "/" ).Replace( @"\", "/" );
    }
}`

and:

    ``
Comment: I don't know why I can't Format It and why half of my writing is vanished!


jquery pqgrid syntax error - missing semicolon

Question: I hate to post a question regarding syntax,  but this is driving me crazy.  I'm getting an error; missing semicolon.  It's pointing to obj.dataModel: {.
I'm just getting started with pqgrid, so take it easy.

Comment: `obj.dataModel:` should be `obj.dataModel = `
Comment: Not seeing any errors in the (slightly-reformatted) version of the edited code, here: http://codepen.io/paulroub/pen/PwzpzW.
Comment: I edited the code.  Now I'm getting SyntaxError: missing } after property list.  I just don't see it.
Comment: I pasted your code and the errors went away.  AND, the grid popped up. Thank you both for taking on a question that so many others just ignore on principle.
Answer: I've started using this tool not so long ago, but you could use syntax checkers like JSLint or JSHint, the latter being a less picky about formatting errors. Online version can be found here, and you can find plugins for many text editors and IDEs.
Pasting your original code indeed produces several missing semicolon errors, but the original error is the first found by the tool: Expected an assignment or function call and instead saw an expression.


Ubuntu 20.04 myslq-server-8 mysqld fails with any other than bind-address = 0.0.0.0

Question: As per subject.
I wanted to limit the servers listening to local lan in 192.168.1.0/29 by
bind-address = 192.168.1.1,192.168.1.2,192.168.1.3
but this always leads to
<code>"Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"
</code>
As I understood, one should be able to limit the accepted addresses by a list?
Comment: Do you notice anything in particular that's different between `192.168.1.1`, `192.168.1.2`, `192.168.1.3` and the value `/var/run/mysqld/mysqld.sock` that you are apparently trying to connect to?
Comment: @andrewe-henle
Not sure what you are after here...
How to check the value of the socket?
Now that I have the bind address on the 0.0.0.0:

    sudo find / -type s | grep sql

I get:

    /run/mysqld/mysqld.sock
    /run/mysqld/mysqlx.sock
Answer: I fixed it by putting bind_address=0.0.0.0 , but limiting connections to mysql port from local net only by firewall rules:
sudo ufw allow from 192.168.1.0/24 to any port 3306


How to remove the name of the language? Menu Language Icons

Question: How to remove the name of the language? Use the module Language Icon, I want to make only the flags.
Answer: On the configuration page of the Language Icons module, admin/config/regional/language/icons, you should set the option 'Icon placement' to 'Replace link'. If I'm not mistaken, choosing this option ensures only the flags are shown.


Como envia os values dentro do formData via POST?

Question: Pessoal gostaria de entender como seria o POST desses dados. Estou utilizando a dependência "react-hooks-helper", Onde capturo dos os dados através de um formulário que tenho vários steps. Onde tudo fica armazenado no formData. Agraço por dicas.

Segue o console.log(formData)
const { firstName, lastName, email, phone, bankID, agency, accountNumber, pixAddress, cpf, cep, street, streetNumber, neighborhood, state, city, } = formData;
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Você primeiro precisa criar o formData para armazenar os dados:
const myForm = new FormData()

Depois de instanciado, você pode extrair os pares valor/chave do seu objeto utilizando o método entries da classe Object.

O método Object.entries() retorna uma array dos próprios pares  [key, value] enumeráveis de um dado objeto, na mesma ordem dos objetos providos através do loop for...in (sendo a diferença que o for-in loop enumera também propriedades dispostas na cadeia de prototipagem - prototype chain).
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

const formKeyValuePair = Object.entries(formObject)

E a partir disso pode usar um forEach para adicionar a chave e o valor ao formData utilizando o método append
formKeyValuePair.forEach((keyValue)=> {
    myForm.append(keyValue[0],keyValue[1])
})

Depois disso é só enviar pro seu endpoint
axios.post('/endpoint', myForm)

Comment: Grato pela as dicas : )
Comment: Massa, não sabia que seria possível. Obrigado
Answer: Você já tem todos os dados dentro de um objeto formData, agora basta você fazer sua chamada POST utilizando algum http client.
Exemplo com axios:
axios.post('/api/seu-endpoint', formData)
  .then(res => console.log(res))
  .catch(err => console.log(err));

Comment: Obrigado man, tinha essa dúvida sobre o que fazer com o objeto. Vlw : )


What's the correct way to visualize discrete variables?

Question: For example, when visualizing the GDP or GDP per capita of different countries, I often see a line plot (or a radar chart), where the x-axis (or the angular direction) is for countries and the y-axis (or the radial direction) is for the values of GDP or GDP per capita. I don't think this is perfect because the values between two countries make no sense. So what are better ways to visualize data like in this case?
Update: example data, source
Comment: It may be useful if you provided a small set of data on which suggested vizualizations might be shown.
Comment: Per capita GDP (GDP divided by population) would be my first guess.
Answer: There's not 'one correct way'; there are some good ways.
The obvious one to my mind would be a Cleveland dot-chart; it's for displaying numeric data on a factor.

Some people would use a bar chart for this purpose instead. If you have a useful classification (such as by region), you'd split by that classification.
With GDPs (whether raw or per capita), the variable covers several orders of magnitude, so it might make a great deal more sense to look on the log-scale (this also obviates any concerns some people might have with 0 not being on the scale above).
There are several uses in such a plot. 1. explicit comparison between countries (is A larger than B?). 2. extracting a data value (what is A's GDP?).
The Cleveland dotchart (or Cleveland dot plot) is based on research[1] into the kinds of comparisons that people are good at or less good at. We're very good at comparison of position along common scales, slightly less good with relative lengths and quite bad at relative areas or angles. In respect of 1. above this comparison is between the values represented by the points (which point is further to the right). In 2. this comparison is between the point and the parallel axis, both comparisons we're good at. The plot eliminates almost all ink that doesn't serve to directly aid these comparisons.
Quick, which is bigger, lemon or lime?

Very thin bars would make for a very similar sort of plot to a Cleveland dot-chart and can sometimes do well (particularly when both plots include 0), but dotcharts have an advantage when you want to plot several numbers for each country, since they can be represented by different symbols. This advantage is even larger if you're only able to use black and white. You also can't really use a log-scale on bar charts (where does the bottom of the bar start and what does the bar-length represent?) and so it's less suitable for data that spans several orders of magnitude.
[1]: Cleveland W.S. and McGill, R. (1984),
"Graphical Perception: Theory, Experimentation, and Application to the Development of Graphical Methods,"
Journal of the American Statistical Association, 79:387 (Sep.), 531-554.
Comment: To obtain a normalization to 0 you could also plot GDP over/under country X's GDP (per capita).  So if you chose the US for example, you could plot each countries GDP over/under that of the USA or even percentage points over/under the US. Alternatively you can express each country's GDP as % of country X's GDP.
Comment: +1 for the "There's not one 'correct' way" portion of your answer.
Comment: @Alexis I mean when lines are used, the values between two "knots" make no sense, which is misleading.
Comment: ziyuang -- I have since included an explicit reference to some of the relevant research.
Comment: I considered this but I think the dots are less "visible" than the lines (though the usage of lines is improper).
Comment: @ziyuang The lines are not "improper." They are a stylistic *choice* used to facilitate legibility, much the the dots used to link a page number with a subject in a TOC or an index.
Comment: And thanks for mentioning the research in the update.


mac Swift multiple keyDown events

Question: I am in the process of creating a 2D tile-based platform game for Mac OSX in swift. I have come across problems with the controls when more than one key is pushed at a time. For example; if 'D' makes the character move to the right, and 'W' makes him jump; if I hold 'D' to make the character run, then tap 'W' to make him jump, he will stop once he lands. The only way for him to continue to move to the right is to retouch 'D' again, which is certainly undesirable. It appears as though when the 'W' key is pressed, it cancels the 'D' keyDown event. If anyone has any suggestions on how I can make it so that multiple keys can be pressed without canceling other similar events I sure would appreciate it.
This is how my KeyDown events looks:
 func returnChar(theEvent: NSEvent!) -> Character?{
        let s: String = theEvent.characters!
        for char in s {
            return char}
        return nil
}

override func keyDown(theEvent: NSEvent) {
                let s: String = String(self.returnChar(theEvent)!)
                switch(s){
    case "w":
        player.jump()
    case "s":
        // nothing yet
    case "d":
        player.moveLeftOrRight(CGVector(dx: 1.0, dy: 0.0))
    case "a":
        player.moveLeftOrRight(CGVector(dx: -1.0, dy: 0.0))

    default:
            println("default")
        }
}

Comment: That seems to be how the hardware works.  I get the same behavior on a PC with a USB keyboard.
Answer: The repeated keydown events that occur when a key is held down are generated by the keyboard hardware.  On the PC, the protocol definition says:

If you press a key, its make code is sent to the computer.  When you press and hold down a key, that key becomes typematic, which means the keyboard will keep sending that key's make code until the key is released or another key is pressed.  To verify this, open a text editor and hold down the "A" key. ... Typematic data is not buffered within the keyboard.  In the case where more than one key is held down, only the last key pressed becomes typematic.  Typematic repeat then stops when that key is released, even though other keys may be held down.

Since both PCs and Macs can use the same USB keyboards (modulo some key remapping), I'm pretty sure they both use the same protocol.
In the case you describe, the problem occurs because even though you're holding down D, when you hit W, the keyboard stops repeating the D key. The sequence of events is:
Keydown D
Keydown D
...
Keydown W
Keyup   W

and at this point the keyboard events stop.  Notice that the Keyup D has not occurred, so you actually know that the D key is still down, but now it is up to you to simulate the repeated keypresses.
I suggest you research how to disable autorepeat altogether in the keyboard hardware (or just ignore the key repeat events) and generate the desired game behavior yourself.  You could easily do this by tracking the state of each key using Keydown and Keyup events, ignoring repeated Keydown.
Answer: Jim Garrison's answer seems correct.  A workaround in this case, could be to have the character move right when you press the D key down, and continue to move right using a loop until the D key is released, which you can check using the func keyUp(theEvent: NSEvent)
If using SpritKit, you can do the character movement in the update method while using a bool that is set in the keyDown and keyUp method.

mac Swift multiple keyDown events


Field with content entries from a content type

Question: I want to add a field (List text) to a content type, using as values the entries of another content type.
Should I use the References module?
Answer: No.
Fields can be reused between any content type. In node's field administration page, use the existing field and values you attributes you set to that field will be available in both node types. But you can have different field labels and descriptions.
Answer: If you mean you have already created a field in another content type, and you want to add the same field (a List(text)) in another content type :

Just search for "Add existing field" in the "manage fields" section of your new content type.
In the machine name list, select the one you've created. Name it, select the same widget.
Add-it the same way.

Normally the values will be copied.


file upload in JSF

Question: I am using tomahawk 1.1.9 fileupload component t:inputFileUpload
It displays a placeholder for the file that gets uploaded and a button that has label "Browse".
I want to hide that Place holder and want to give my own label to the button instead of "Browse".
Answer: I don't think this is going to be possible without some fairly ugly CSS hacking. The file input box is there for a good reason: security. If it could be controlled (or removed) using JavaScript, users could potentially have sensitive files uploaded without their knowledge or consent.
The input file box is a way of them having some confidence that what they are uploading is only the file they actually want to upload.
The only thing I have seen done successfully with input file boxes is styling them - have a look at this and this for examples.
Comment: Thanks for your reply. I have seen the link. But I need to use only JSF tag not html. And my requirement is to display only Button. Is there any other tag which can accomplish this.I can use rich faces component also.
Comment: Then just do so. They have a file upload component as well: http://livedemo.exadel.com/richfaces-demo/richfaces/fileUpload.jsf
Comment: Hi BalusC,
    Thanks for ur reply....am using richFaces 3.1.6 But in this version there is no rich:fileupload component.What should i do?
Comment: is there  any way to change the label of fileupload component button "Browse" to label of our own and to hide the place holder of file upload component of tomahawk 1.1.9..... Also, is there any component for file upload in richfaces 3.1.6...
Comment: Either upgrade richfaces, or create a custom component.
Comment: Thanks for your reply...How to create custom component?

file upload in JSF


Does $\lim_{k\to\infty} \sum_{n=1}^{k} f(n)$ converge?

Question: I am wondering if there is a rigourous way to show the following series converges:
$$ f(x) = \begin{cases}
\dfrac{1}{x^2} & x \in \mathbb{N} \\[1ex]
g(x) & x \not\in \mathbb{N}\in \mathbb{R}
\end{cases}$$
Here, $g(x)$ could be anything, but for interest, wouldn't converge on its own.
When we do the following:
$$\lim_{k\to\infty}\sum_{n=1}^{k}f(n).$$
Do we get a limit that exists?
Intuitively we would, because summation is only defined on the natural numbers (unless we redefined it here, doing some interpolation between points). However, I am not certain this function is integrable, which would suggest the function does not converge (unless my understanding of the Integral Test is wrong, after all, it says nothing of whether the integral exists, just if it converges the sum converges and vice-versa).
Comment: The notation $x \not\in\mathbb{N} \in \mathbb{R}$ is nonsense.  Do you mean to say $x \in \mathbb{R}\setminus\mathbb{N}$?
Comment: The $\Sigma$ notation is usually used to iterate over integers.  If so, the value of $f(x)$ outside $\mathbb{N}$ is irrelevant.
Comment: After reading in more detail, I am confused about your question.  Are you confused about the convergence of $\sum 1/x^2$?  Or are you confused about the integral test?  If the latter, please edit your question to indicate what you mean by "the integral test"---be as precise as possible, and do not leave out hypotheses.
Comment: @XanderHenderson What I am asking is does the given series converge. Re: notation, perhaps so, I wasn't sure of how to write what I meant to denote (a number outside the set of natural numbers). The expression does not seem to have an elementary antiderivative, or any integral at all, and so as a potential follow up I mentioned that that may impact some notion of the convergence of the function.
Comment: @XanderHenderson Specifically, the confusion arises because the series is not well behaved in some sense of the word, and yet for the set of natural numbers it is, so does this allow for convergence?
Comment: The series $\sum_{k=1}^{\infty} f(k)$ converges.  There are many arguments [here](https://math.stackexchange.com/questions/8337/different-methods-to-compute-sum-limits-k-1-infty-frac1k2-basel-pro?noredirect=1&lq=1).
Comment: The summand of the series only needs to be defined, let along "well behaved", on the naturals.  The business about $f(x) = g(x)$ for $x\not\in\mathbb{N}$ is a red herring.  Even if your goal is to use the integral test, you need to be more careful---in order for the integral test to apply, $g$ cannot be arbitrary,  Check the hypotheses.
Comment: Right -- if you were to add some variation of your first two sentences (about $g(x)$ being irrelevant), I would be able to accept that answer as it properly addresses the question.
Answer: To address your confusion, we note that the integral test requires that $f(x)$ must be monotone decreasing over the interval $\left[1, \infty\right)$ to be applicable.
Check this link: https://en.wikipedia.org/wiki/Integral_test_for_convergence
Hence, if we have
$$f(n) = \frac{1}{n^2}$$
for all $n \in \mathbb{N}$, and you want to extend it to $\mathbb{R}$ by setting $f(x) = g(x)$ for all $x \in \mathbb{R} \setminus \mathbb{N}$, then you have to make sure that the selection of $g(x)$ keeps $f(x)$ monotone decreasing over the interval $\left[1, \infty\right)$ so that the integral test can kick in.
If the ultimate goal of extending $f(n)$ to the domain $\mathbb{R}$ as $f(x)$ is to hopefully construct $f(x)$ so that we can use the integral test to prove that the series
$$\sum_{n = 1}^{\infty} f(n) = \lim_{k \to \infty} \sum_{n = 1}^{k} f(n)$$
converges, then in this case, the way you extend $f(n)$ to $f(x)$ matters. If you can prove that there exists at least one way to extend $f(n)$ to $f(x)$ such that $f(x)$ is monotone decreasing over the interval $\left[1, \infty\right)$, then this is sufficient to invoke the integral test to prove that
$$\sum_{n = 1}^{\infty} f(n) < \infty$$
For instance, you can trivially take $g(x) = 1/x^2$ for $x \in \mathbb{R} \setminus \mathbb{N}$ so we have $f(x) = x^2$ for all $x \in \mathbb{R}$ which is monotone decreasing.
But if you just just want to know if the limit exists, then you can do so without extending $f(n)$ to $\mathbb{R}$. I mean, you can do so without invoking the integral test. Evaluating this sum is known as the Basel problem and the result is $\pi^2/6$.
Check this link: https://en.wikipedia.org/wiki/Basel_problem
Answer: About the series,
$$\sum_{n\ge 1} f(n)=\sum_{n\ge 1}\frac{1}{n^2}$$
converges as a Riemann series $(2>1)$.
As an integral, we can say nothing. It depends on the expression of $ f(x).$
Take for example $ f(x)=1$ if $ x\notin \Bbb N$, then
$$\int_1^{+\infty}f(x)dx \;\; diverges$$
and If $$(\forall x\ge 1)\;\; f(x)=\frac{1}{x^2}\; $$
the integral $$\int_1^{+\infty}f(x)dx\;\; converges$$
Comment: It is not entirely clear to me *what* the asker's question is:  are they really interested in the series, or are they trying to understand the "integral test".  Since the *question* is not entirely clear, it seems premature to provide an answer.


various weighted values as a percentage of 100

Question: If I have various values, $x,\, y,\, z,\, t$. And I want to give each of these values a weight such as $x(30),\,y(10),\,z(40),\,t(20)$. This weight relates to that values part off $100\%$, so if each value was the most it could be and we added all values it would be 100. How can I make this type of equation ? for example in the event that $x$ was $50\% x = 30$, y was $100\%y = 10$, and $z$ and $t$ are $50\%$ I could get a score of $80$.
So basically I want the answer to be a value less or equal to $100$ were the values that are added to get the score are weighted and take up different portions of the overall score.
Answer: If you split a number $s$ into 4 parts with relative proportions $x:y:z:t$ you get $\frac{xs}{x+y+z+t}$,  $\frac{ys}{x+y+z+t}$,  $\frac{zs}{x+y+z+t}$,  and $\frac{ts}{x+y+z+t}$.
Let's check this is correct:
It is obvious that these numbers are simply $x,y,z,t$ multiplied by $\frac{s}{x+y+z+t}$, so they have the right proportions. Their sum is $\frac{xs+ys+zs+ts}{x+y+z+t} = \frac{(x+y+z+t)s}{x+y+z+t} = s$ as required.
Comment: I think this is a bit different to what I need ill try to explain better. I have four independent values, I want to add these values and get a final value from 0 - 100. But I want the different values to have different weightings. So I want for instance the first value to make up 30% of the final value, the second to make up 20% and so on.
Comment: @dmnte Are these four independent values also in the range 0-100? If so, just take their weighted average: $(w_1x+w_2y+w_3z+w_4t)/(w_1+w_2+w_3+w_4)$. If not, you'll have to scale those independent values first to make them fall in that 0-100 range before taking the weighted average..
Comment: After a little searching ive found the softmax function which seems like I could use. It is not weighted but I assume I could add this. Does anyone know anyreasons why this wouldnt be good ?


How can I hide the username on a custom user-profile.tpl.php page?

Question: I'm making a custom user-profile.tpl.php page and want to put the "business name" field where the Title/Username normally occurs and print the username elsewhere.
The username doesn't appear in the list at:
Administration » Configuration » People » Account settings » Manage Display so I can't remove it there.
My guess is that I need to add some logic to page.tpl.php to not print it on user profiles and then I need to know the variable to add it to user-profile.tpl.php.
Can anyone help me with this?
Answer: You can do it by disable field display property using form_alter
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
  $form['account']['your_field_name']['#access'] = FALSE;
    }
  }

Answer: 1) Create a custom  module
2) Put this code:
function formalter_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'user_profile_form':
        hide($form['account']['name']);
       //dpm($form['#user']->field_full_name);
        $form['account']['name']["#attributes"]['placeholder']=t('Bussiness  Name');
  }

Answer: Thanks for the responses. I approached it differently.
I first created a custom page--user.tpl.php file in which I removed the section that prints the title.
I then found the username variable and wrote a little snippet to print it under the business name (except in cases where the business name doesn't exist) in user-profile.tpl.php.
<?php

$user_username = $variables['elements']['#account']->name;

if (isset($user_profile['field_business_name']) || array_key_exists('field_business_name', $user_profile)) {

$user_business_name = $user_profile['field_business_name']['#items'][0]['safe_value'];
print "
$user_business_name
";
print "$user_username";
print "
";
}

else

print "
$user_username
";
print "
";

?>


customizing flask error handlers for json returning api

Question: I have a flask app which has two types of routes :
(1). routes for website, like /home, /user/, /news_feed
(2). json returning apis for mobile app, like /api/user, /api/weather etc.
I am using custom error pages for common errors like 404 and 500 via @app.errorhandler decorator provided by flask - for my website
@app_instance.errorhandler(404)
def page_note_found_error(err):
  return render_template("err_404.html"), 404

@app_instance.errorhandler(500)
def internal_server_error(err):
  db_instance.session.rollback()
  return render_template("err_500.html"), 500

I do not want my mobile apis to return these error pages if say i get a 500 error via the mobile api.
Is there a way to bypass or customize the error handler for some routes(api) so that it returns json response instead of my custom error pages
Answer: You can dig into the details of the request to determine the URL path. If the path is prefixed by /api/ then you can treat it as an API request and return a JSON response.
from flask import request, jsonify

API_PATH_PREFIX = '/api/'

@app_instance.errorhandler(404)
def page_not_found_error(error):
    if request.path.startswith(API_PATH_PREFIX):
        return jsonify({'error': True, 'msg': 'API endpoint {!r} does not exist on this server'.format(request.path)}), error.code
    return render_template('err_{}.html'.format(error.code)), error.code

This is not ideal. I thought that you might have been able to handle this with Flask blueprints, but the blueprint specific error handler does not work for 404, instead the app level handler is invoked.
Comment: Thanks, this solves my problem. Its a small project prototype so I am not using blueprints for now, good to know though.


How to work around pointer casting in C to avoid unaligned memory access?

Question: I recently learned that pointer casting could trigger unaligned memory access, such as in
void test_func(uint8_t *data) {
        /*The rest of the code removed for clarity*/
    uint32_t value = *((uint32_t *) data);
}

But how can I work around it, if I really need to cast pointers? In the example above, what if I have to access data as an uint32_t but still want to avoid unaligned memory access?
Comment: `uint32_t value; memcpy(&value, data, sizeof value);`
Comment: simple do not use pointer punning.
Answer:
How to work around pointer casting ... to avoid unaligned memory access?

Use memcpy(&value, data, sizeof value); to transfer the data instead of *((uint32_t *) data).  A good compiler will emit efficient code.
uint8_t data[4] = { 1,2,3,4};
uint32_t value;
memcpy(&value, data, sizeof value);

... or insure the uint8_t value[] is aligned with a union,  alignas via *alloc()
union {
  uint8_t data[4];
  uint32_t d32;
} x;
...
test_func(x.data) {

#include <stdalign.h>
alignas(uint32_t) uint8_t data[4] = { 1,2,3,4};
test_func(data);

uint8_t *data = malloc(sizeof *data * 4);
...
test_func(data);
free(data);

Comment: When targeting platforms that enforce alignment requirements, code which efficiently processes 32-bit data won't work with unaligned addresses, and code which works correctly with unaligned addresses will be sub-optimal when addresses happen to be aligned.  When using clang, if arguments to `memcpy` are pointers to types that require 32-bit alignment, it will generate code that efficiently handles aligned arguments, but fails with unaligned arguments.
Answer:
How to work around pointer casting in C to avoid unaligned memory access?

You can't (e.g. on x86-64 unaligned memory access are possible, but slow; it might also be the case on Arduino-s).
See also _Alignas and _Alignof operators of C11.
On many implementations, a pointer can be casted back and forth from intptr_t and you could then play bitwise tricks.

In the example above, what if I have to access data as an uint32_t but still want to avoid unaligned memory access?

You need to ensure that the caller of test_func is passing a well aligned pointer.
You could be helped by tools like Frama-C, the Clang static analyzer, or perhaps, at end of spring 2021, Bismon
You might #include <assert.h> and add, as the first statement of your test_func : assert((intptr_t)data % sizeof(uint32_t) == 0); ; see e.g. assert(3).
Comment: The last assertion: `(intptr_t)data % sizeof(uint32_t) == 0` can be overly restrictive.  An implementation could have alignment requirements for `uint32_t` of only 2 or 1.  Consider a 16-bit or 8-bit embedded processor.  I do not see "bitwise tricks" leading to a good alignment test.  Noel.
Comment: Thanks for the answer. Could I conclude that pointer casting in C is inherently problematic and should be avoided to ensure code portability and reliability?
Comment: @zell: One of the strengths of C is that almost all implementations can support a wide range of constructs that might not be practical to support on 100% of implementations and are thus not mandated by the Standard.  Some compiler writers who aren't interested in selling compilers treat the Standard's failure to mandate support for a construct as an intention to characterize as "broken" any code that would use it, but the authors of the Standard have expressly said that they used the phrase "Undefined Behavior" to identify "areas of conforming language extension".


Crack between fretboard and guitar neck

Question: I recently adjusted the truss rod in my guitar, nothing uncommon. I increased the relief a little bit when I noticed the following crack around the 7th fret. It is, perhaps difficult to see, but I am referring to the part where it is possible to see some wood between the painting of the neck and the fretboard. The crack goes further to almost the 10th fret.

My question is, is it normal to happen when adding relief to the truss rod? What might have caused this issue? Is there anything I can do to prevent this from getting worse or should I look for a professional?
Thanks in advance.
Comment: I see a light colored line in the left center of the neck, is that what you're talking about? It looks very straight, is it a crack in the wood or did the fingerboard become partially unglued from the neck?
Comment: @JohnBelzaguy That is it. I can't figure out if the fingerboard became apart from the neck. It seems it did not, but I don't know for sure.
Comment: Disclaimer, I'm not a repair person but it's possible that it's just a minor surface separation due to different types of woods that are glued together expanding and contracting at different rates. Best to have it looked at by a pro to be sure. Does the fingerboard feel solidly attached to the neck at that point?
Comment: It does. When I press the fingerboard, it does not seem to move. Looking very closely, it seems thtat there is wood there, and the crack is just in the paint/finishing.
Answer: This is not at all normal, and chances are the problem has been there for a long time, and it wasn't caused by a small change in the truss rod. Either you didn't notice it earlier, or a little change in the truss rod acted like the proverbial last straw. The root cause is a construction defect, something went wrong when the neck was built, either in materials or handiwork. If something like this happens to a guitar which is still under warranty, it's a clear case for replacement or full repairs.
In any case, unfortunately, some major repairs are going to be needed, and they're not going to be cheap. The fretboard will have to be taken out from the neck, truss rod checked, parts cleaned up and sanded down, cracks filled up, and then the fretboard will be glued back to the neck properly. Alternatively, it may cost less to buy a new neck.
Perhaps an attempt can be made at a quick-and-dirty fix, i.e. put some glue in there and keep the fretboard pressed hard on the neck until settled. As I said, quick-and-dirty. But it may be worth a shot if the guitar's value isn't too much and it doesn't make sense to spend a lot of money on repairs.
And if you don't do anything, I reckon that there's no telling of how the problem may evolve. It's possible that nothing else will happen. If there was a gap in the surfaces at that point, or glue was applied badly at that point, but everywhere else things are OK, you may still be fine, it's possible that things won't get any worse, and if the crack is felt during playing, a little wood filler can fix. On the other hand, if the underlying damage is more extensive, the crack may get worse, maybe a little, maybe a lot. That's impossible to know without knowing what's going on inside.
If the instrument were mine, and if it were not very expensive to start with, I'd do nothing at first, but keep a close look all the time, and if the crack expanded by even a millimeter, I'd take the strings off, loosen the truss rod, and take it to a pro. I the crack didn't change at all for a long time, I might decide to let it be. On the other hand, if the guitar was valuable, I'd take it to a pro right away.
Comment: 'May cost less to buy a new neck' - agree if it's a bolt-on. Not otherwise!
Comment: It is a Washburn Oscar Schmidt (https://cdn3.volusion.com/4n9y2.qupg5/v/vspfiles/photos/OS-OE30B-3.jpg?v-cache=1413472200), and the neck is bolt-on. I think I won't take any action and observe closely what happens. Thanks!
Answer: If it were mine, I'd undo whatever I did and take it to a pro.

Crack between fretboard and guitar neck


Dendrograms using clustergram vs traditional ways in Matlab

Question: By comparing the dendrograms produced by the clustergram object and the "manual" approach i.e. pdist -> linkage -> dendrogram I found they are different, but cannot find an explanation for that difference.
Clustergram documentation says that the default distance used is 'Euclidean' and the default linkage method is 'Average', same parameters I used for pdist and linkage functions.
I thought it might be related to the standardization performed by clustergram, so I used z-score for standardizing first my matrix and then each column separately, but the dendrograms are still different as compared with the one produced by clustergram.
Can somebody explain the reason behind that difference, and how can I use the "manual" approach for getting the same dendrogram?
Many thanks in advance.
Edit: I compared the results obtained by the "manual" approach with the SPSS results and they are the same.
Also, I tested all different ' data processing' options with clustergram but the dendrogram keeps being different.
Answer: pdist -> linkage -> dendrogram is also used in clustergram, just open the clustergram code:
<code>dist = pdist(data, pdistArgs{:});
Z = linkage(dist, linkageArgs);

...

[lineH, T, Perm] = dendrogram(Z,0,dendroArgs{:},'Orientation', dendroLoc);
</code>
So the only difference can be in data preprocessing or parameters for pdist/linkage/dendrogram.
I suggest you go over the clustergram parameters one by one. You can also look through the code although it is pretty long.
Comment: @Diego Make sure you are clustering only by rows/columns, not by both (default is by both).
Comment: Yeap I print it out 40 pages!!! I'm studying it but honestly is my first time working with a Class in Matlab, so it's kind of messy for me to follow it. I found couple of things more that can make a difference like OptimalLeafOrder, Log2 Transform Data, and the Computation of the dendogram along both directions. However the only way I can imagine for evaluating this Class is by building it up step by step... and that seems to be a huge work... So any ideas are very much welcome.
Comment: Yes, I've thought about that and performed some tests: `c = clustergram(A,'Cluster','column');` and `c = clustergram(A,'Cluster','all');`. However both lines return the same "column" dendrogram and same heat map with different order in the heat map.


$\exists E\in\mathcal{X}$ such that $\mu(E)<\infty$ and $\int_X|f|d\mu<\int_E|f|d\mu + \epsilon$

Question: If $f$ is integrable on space X, then $\forall \epsilon >0$ $\exists E\in\mathcal{X}$ such that $\mu(E)<\infty$ and $\int_X|f|d\mu<\int_E|f|d\mu + \epsilon$
To prove this somehow I need to show $lim\int_X|f|d\mu -\int_{E_n}|f|d\mu=0$ where $E_n$ increases to $E$ I guess. But how to define $E_n$. Or there is another way better?
Answer: $$E_n=\{x\in X\mid |f(x)|\leqslant n\}$$
Comment: Except that you choose $E=E_n$ for *a single specific* $n$, not the limit of $E_n$ when $n\to\infty$.
Comment: But then $lim E_n = X$ so 0 or small measured sets will be included also. I think that what is asked or maybe I am interpreting the statement wrong?
Comment: why does En has finite measure?


Why is Klein bottle non-orientable?

Question: I am doing the homework of differential geometry and encounter this problem:

The Klein bottle $K^2$ is defined to be the identification space
  $$[0, 1] \times [0, 1]/{\sim}, \text{ where the identification is }
(x, 0)\sim (1-x, 1) \text{ and } (0, y) \sim (1, y).$$
i) Prove that $K^2$ is non-orientable.
  ii) For a submanifold $M$ on $K^2$ defined by $1/4\leq x\leq3/4, 0\leq y\leq1,$ is $M$ orientatble?

I already know that I need to check the orientation of the tangent space along some curve. But I am not quite sure how I can write down the proof in a formal way.
Could anyone help? Any comment? Thanks!

Edit: I have done the first part. Can anyone help me with the second? I have a feeling that the submanifold $M$ is isomorphic to the Möbius strip. But I don't have good reasons.
Edit: Yes, $M$ is indeed the Möbius strip.
Comment: A formal proof of this requires a formal definition of orientation (of which there are a few).
Comment: I think the best way to see that it's non-orient able is to look at a photo of one, but I'm guessing you have to proof it formally?
Comment: Try a horizontal (under your identification) circle.
Comment: @columbus8myhw Yes, I want a formal proof. Any idea?
Comment: I think there's a theorem: "a manifold is orientable iff it does not contain an embedded copy of the Mobius strip." So if you can find a Mobius strip somewhere in your Klein bottle, that might be a fruitful approach.
Comment: @PVAL Sure. But what can I say about the orientation on the tangent space?
Comment: @Vald : You wrote "some curve".  So ask yourself which curve. ${}\qquad{}$
Comment: When you write $A\sim B$, you automatically get a certain amount of space before and after "$\sim$" because it's a binary relation symbol (just as with "$=$", "$\equiv$", "$\approx$", etc., and just as with binary operation symbols like "$+$", "$\times$", etc.).  But in something like "$A/{\sim}$", the space shouldn't be there.  So code that as A/{\sim}.  (I already changed it in the posted question.)
Comment: @goblin $\Bbb R^3$ is a counterexample to your theorem.
Comment: @PVAL, right. I think the correct theorem is "a 2-manifold is orientable iff it does not contain a copy the Mobius strip."
Comment: @goblin Thank you, though I have no idea how to prove it.
Comment: For the second half of your question, just try parallel transporting a tangent frame along the loop $x=1/2$.
Answer: Here is a possible proof (credit to user pappus here):
Recall that a manifold is orientable iff there exists a volume form on it. So in order to show that $K^2$ is non-orientable, it is enough to show that any $2$-form $\omega$ on $K^2$ must vanish at some point.
Let $K^2$ be defined here as the quotient of $\mathbb{R}^2$ by the subgroup of diffeomorphisms of $\mathbb{R}^2$ generated by $\tau : (x,y) \mapsto (x+1, y)$ and $\sigma : (x,y) \mapsto (1-x, y+1)$1.
So let $\omega$ be a $2$-form on $K^2$and $\tilde{\omega}$ be the pull-back to $\mathbb{R}^2$ (by the canonical projection $\mathbb{R}^2 \to K^2$). There exists a smooth function $f :\mathbb{R}^2 \to \mathbb{R}$ such that $\tilde{\omega} = f(x,y) \,\omega_0$, where $\omega_0 = \det = dx \wedge dy$2. Then $\tilde{\omega}$ must be invariant under $\sigma$ (and $\tau$): $\sigma^* \tilde{\omega} = \tilde{\omega}$. You can check that $\sigma^* \omega_0 = -\omega_0$, so $f$ must satisfy $\sigma^* f = -f$, i.e. $f(1-x, y+1) = -f(x,y)$. It follows that $f$ must vanish (by continuity of $f$ and connectedness of $\mathbb{R}^2$), hence $\tilde{\omega}$ must vanish, hence $\omega$ must vanish.
$$
$$
Edit: for the second part, you can produce the same proof. Replace $\mathbb{R^2}$ with the band $\{1/4 \leqslant x \leqslant 3/4\}$ and forget about $\tau$.

1 This is clearly equivalent to your definition, and is a good way to define $K^2$ together with its smooth structure.
2 This is because the top exterior power of a finite-dimensional vector space is one-dimensional, which implies that any $n$-form on a orientable $n$-manifold is proportional to a given volume form.
Answer: Here are three ways to look at it.
The Klein bottle is the quotient space of the torus by the action of an orientation reversing involution. So it is not orientable.

One can choose this involution to be rotation by 180 degrees along one generating circle followed by reflection along the second.

The top Z homology of the Klein bottle is zero so it is not orientable.

One can define orientability for a triangulated manifold to be the existence of a top dimensional Z-cycle. If you triangulate a Klein bottle you will find that there is no two dimensional Z-cycle.

The Klein bottle is covered by the Euclidean plane. The group of covering transformations can be taken to be the standard lattice (points with integer coordinates) of pure translations together with the affine transformation,
T: (x,y) -> (x + 1/2, -y).
T is orientation reversing since its matrix part has determinant -1.

One checks that this means that the coordinate transition functions are not all orientation preserving.

Why is Klein bottle non-orientable?


Distinct coset representative and stabilizing an element.

Question: Let $G < S_n$ be a permutation group of degree $n$, and let $G^{(i)},0 < i\leq  n$, be the pointwise stabilizer of $\{1,2.., i\}$ in $G$. We set $G^{(0)}= G$. For $0 < i\leq  n$, let $U_i$ be a complete right transveral  for $G^{(i)}$  in $G^{(i-1)}$. If $\psi$ and  $\psi'$  are distinct coset representatives in $U_i$, then
$i^{\psi} \neq i^{\psi'}$
But $\psi,  \psi'$ both fix $\{1,..i-1\}$. If $i^{\psi} = i^{\psi'}$, still $\psi$ and  $\psi'$  can be in distinct coset representatives in $U_i$.
Would anyone eplain why  being $\psi$ and  $\psi'$  in  distinct coset representatives in $U_i$ infers   $i^{\psi} \neq i^{\psi'}$?
Answer: Suppose $i^{\psi} = i^{\psi'}$, with $\psi, \psi' \in G^{(i-1)}$.
Then $i^{\psi' \psi^{-1}} = i$, so $\psi' \psi^{-1}  \in G^{(i-1)}$ fixes also $i$, and thus $\psi' \psi^{-1}  \in G^{(i)}$.
It follows that $G^{(i)} \psi = G^{(i)} \psi'$.


Android Camera2: CONTROL_AF_STATE always 0 for CONTROL_AF_MODE_MACRO

Question: I am trying to detect when camera has focused (or has stopped trying to) so I am calling result.get(CaptureResult.CONTROL_AF_STATE)in onCaptureCompleted method of callback.
It kind of works for mode AF_MODE_CONTINUOUS_PICTURE, camera reports CONTROL_AF_STATE 1 or 2 (CONTROL_AF_STATE_PASSIVE_SCAN or CONTROL_AF_STATE_PASSIVE_LOCKED), which is nice.
However when camera is switched to AF_MODE_MACRO, then reported CONTROL_AF_STATE is always 0 (INNACTIVE) no matter what happens. I was trying to refer to 1 but probably I do not get it right.
Further info: when changing modes between AF_MODE_MACRO and AF_MODE_CONTINUOUS_PICTURE I always start new capture session like this:
private void configCaptureSession(boolean macroModeNew) {
this.macroMode = macroModeNew;
try {
  // Wanna macro?
  if (macroMode) {
    LOGGER.d( "MACRO ON","");
    previewRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_MACRO);
    }

  else {
    // Continuous AF
    LOGGER.d( "MACRO OFF","");
    previewRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

  }

  // Finally, we start displaying the camera preview.
  previewRequest = previewRequestBuilder.build();
  LOGGER.d( "SETTING NEW SESSION","");

  captureSession.setRepeatingRequest(
      previewRequest, captureCallback, backgroundHandler);

} catch (final CameraAccessException e) {
  LOGGER.e(e, "Exception!");
}

}
captureCallback:
 private final CameraCaptureSession.CaptureCallback captureCallback =
  new CameraCaptureSession.CaptureCallback() {
    @Override
    public void onCaptureProgressed(
        final CameraCaptureSession session,
        final CaptureRequest request,
        final CaptureResult partialResult) {}

    @Override
    public void onCaptureCompleted(
        final CameraCaptureSession session,
        final CaptureRequest request,
        final TotalCaptureResult result) {

        afState = result.get(CaptureResult.CONTROL_AF_STATE);

        LOGGER.i("FOKKUS-MODE:"+result.get(CaptureResult.CONTROL_AF_MODE));
        LOGGER.i("FOKKUS:"+result.get(CaptureResult.CONTROL_AF_STATE));

    }

  };

Answer: Does your device list support for AF_MODE_MACRO in https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.html#CONTROL_AF_AVAILABLE_MODES ?
If not, then this is expected as you're trying to use a non-supported focusing mode.
If it is supported, the next issue is that I don't see you issuing an AF trigger command anywhere.  Have you looked at the state transition tables for AF_STATE here:
https://developer.android.com/reference/android/hardware/camera2/CaptureResult.html#CONTROL_AF_STATE ?
For AF_AUTO and AF_MACRO, you have to trigger AF when you want a focus pass, and then wait for AF_STATE_FOCUSED_LOCKED or NOT_FOCUSED_LOCKED.
The continuous modes don't require a trigger to focus, which is why you're seeing something happening with them.
Comment: You can take a look at the Camera2Basic sample from Google: https://github.com/googlesamples/android-Camera2Basic
Comment: Thank you Eddy for the answer! I was not aware of the fact that I have to issue AF Triger. Because autofocus seems to be working anyway. Actually i cannot find any kind of good description/tutorial how to that and work with Camera2 Api in general. Based on the code snippets in my post, could you please suggest good aproach?


How to open the web configuration of Pfsense

Question: I installed Pfsense on VMWare Player and I set IP adresses for wan interface and Lan interface.

When I write the adress https://192.168.40.1 on the address bar of my browser I got a time out and I could not open the web configurations.
Any idea ?
Thank you
Comment: Make sure your local computer (where you're running the browser) is in the subnet 192.168.40.x, and/or that the LAN IP address is routable from your computer?
Comment: This address 192.168.40.1 is the address of VMNET1 host only of WMWare and My virtuale machine is connected to that network by the Network Adapter. I can ping it too in my local computer.
Answer: First, have you tried putting the WAN address in your browser? That probably won't work though.
I think I dealt with this problem once by making an ssh tunnel to the open ssh port on the WAN address (ssh -D 8000 root@pfsense-wan-ip), then set up the browser (make localhost:8000 your browsers socks proxy) to use the tunnel  to load the web configuratator.
You could additionally probably make a second interface in VMWare that represents that LAN interface and setup NAT forwarding to allow you to connect from your desktop to the web configurator.
Lastly, I seem to remember that you can make the web configurator run on the WAN ip by editing a file somewhere.
Comment: I tried it I get the same thing, I cannot access. and as you see in the picture the OS is asking to open the LAN address.
Comment: Oh right, by default it's only bound to the LAN ip. I know windows doesn't have a native ssh client but the ssh thing totally works. I used to have a job that used virtualized pfsense to run dev environments, and that was an easy alternative to making a VPN connection to the pfsense wan (which will also work btw, its just a ton of work to setup)
Comment: Hey, I have an idea. Why don't you install another virtual machine that's a desktop, bridge it to the same virtual network as the pfsense lan, and just run the browser from the desktop vm?
Comment: I will try it ..
Comment: Hey that worked ! Thank you, I opened another virtual machine on CentOS and bridge it to the same network.


using JOIN and subquery in mysql

Question: I posted a question about 2 weeks ago about 'one to many' relation between SQL tables. Now I have a bit of a different scenario. Basically, there are two tables - coffee_users and coffee_product_registrations. The latter is connected to coffee_users table with 'uid' column. So basically coffee_users.uid = coffee_product_registrations.uid
A single user can have multiple products registered.
What I want to do is to display some product information (from coffee_product_registrations) along with some user information (from coffee_users), BUT retrieve only those rows that have more than 1 product registrations.
So to simplify, here are the steps I need to take:

Join two tables
Select users that have multiple products registered
Display all their products along with their names and stuff

My current SQL query looks like this:
SELECT c.uid, c.name, cpr.model
FROM coffee_users c
JOIN coffee_product_registrations cpr on c.uid = cpr.uid
GROUP BY c.uid
HAVING COUNT(cpr.uid) > 1

This joins the two tables on 'uid' column but displays only 1 row for each user. It selects just users that have multiple products registered.
Now I need to take these IDs and select ALL the products from coffee_product_registrations based on them.
I cannot figure out how to put this in one query.
Answer: Replace cpr.*, c.* with columns which you want to extract feom the query
Try this:
SELECT cpr.*, c.*
FROM coffee_product_registrations cpr
INNER JOIN coffee_users c ON c.uid = cpr.uid
INNER JOIN (SELECT cpr.uid
            FROM coffee_product_registrations cpr
            GROUP BY cpr.uid
            HAVING COUNT(DISTINCT cpr.productId) > 1
           ) AS A ON c.uid = A.uid;

Comment: Returns an empty result. So should I have 2 inner joins then? Can I not have one?
Comment: http://sqlfiddle.com/#!2/59078 is the sqlfiddle. I've created 2 usernames - user1 and user2. user1 has 2 products registered under coffee_product_registrations and user2 has only 1. So the query should select all the products of user1 and display both products in addition to the email and ID of user1.
Comment: I'm not sure what you mean by table format but what I'm trying to achieve is this: Display all products of users who have more than 1 product registered and each product should have the user's email and ID alongside.
Comment: One user can have as many products registered as they want. I want to select only those users that have more than 1 product registered and then I want to display product details for each product that these selected users have.

using JOIN and subquery in mysql


How do I create a variable that my page.tpl.php file can access?

Question: In Drupal 7, I have a module that implements hook_node_load. It creates a variable that I'd like to make use of in my page.tpl.php file. Let's pretend it is the count of nodes that are of the same type as the currently loaded node. As of now, I'm just making the variable global, like so:
global $node_count;
$node_count = db_query("SELECT count FROM {node} WHERE type = :type", array(":type" => $node->type"))->fetchAll()[0]->count;

Then, within my page.tpl.php file, I have to do something like the following:
global $node_count;
echo "
$node_count
";

I know that there is a way to make my $node_count variable in scope, in the same way that $node or $user are. The tutorials I find on the subject seem to involve rewriting the entire theme function - I'm not trying to do anything that complicated. Is there a simple way to just make this variable in scope in my .tpl.php files? Something like a function?
Answer: In Drupal theming, template preprocess functions are the functions that prepare the variables that can be used in a certain template. Template preprocess functions are executed one after another and they pass around an array with all variables. You can add your own in your theme's template.php, in the form of function THEMENAME_preprocess_TEMPLATENAME(&$variables) { // Your code here. }.
If you're adding a value to a node object in a hook_node_load implementation, that probably looks something like this:
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->myvariable = 'somevalue';
  }
}

Now you want to access $node->myvariable in your page.tpl.php. For this, you don't even need to write a preprocess function, because Drupal already adds the current node object to the variables by default. (This happens in template_prepocess_page.) This means that you can simply add this to your page.tpl.php:
<?php if ($node->myvariable): ?>

    <?php print $node->myvariable; ?>

<?php endif; ?>

Comment: I may not be understanding this correctly, but I am not quite sure this is what I want. The thing is, I want to create the variable within a hook_node_load() function. This would live within my module, not my theme. Am I able to do this with themename_preprocess_page? If so, any chance you could give an example? Thanks.
Comment: OK, I see, I'll update my answer.
Comment: Answer updated. Hope that helps!
Answer: Variables that are accessible from a template file can be set in its preprocess function, which can be implemented in a module too.
In your case, your module should implement code similar to the following one (replace "mymodule" with the short name of your module):
function mymodule_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['node_count'] = db_query("SELECT count FROM {node} WHERE type = :type", array(":type" => $variables['node']->type"))->fetchField();
  }
}

I verify $variables['node'] is not empty because the page template is also used for pages that are not associated with a node.
In page.tpl.php, you access the same variable set from the preprocess function using $node_count.


Print mailing address labels from a view

Question: We have a site built with Drupal Commerce and are looking for a way to print address labels from a view
So far I have been able to make a grid view of addresses and use the printer friendly version module to create a print view, but i can't seem to get the CSS right to line up the labels correctly.
I have seen this module for Drupal 6 - http://drupal.org/project/mailing_label, but nothing for Drupal 7. I was wondering if someone had any insight.
Thanks.
Comment: The module is really simple, you can take a stab at porting it to 7.
Comment: OK, I will give it a shot and comment back, thanks!
Comment: I am working with the coder module now, and I have Drupal 7 recognizing the module, but I getting the message of Invalid display id mailing_1. Do you think that this module is compatible with Drupal Commerce and/or entities other than nodes?
Comment: There is a D7 version of the mailing-label module. But, it is a [sandbox project](http://drupal.org/sandbox/clydefrog/1328782).
Answer: Our warehouse team needed the ability to print address labels on the Avery 5163 template for every Commerce Order that is set to the status as Pending
I consider this to be a jury rig more than a Drupalish answer, but it got us through just the same.
Here is how we did it.
We created a page with a table view that shows all orders that are pending.
We created a view of Commerce Profiles that showed only the customer addresses in a grid format.
We used the Printer, e-mail and PDF versions module to create printer friendly versions of the views Here is the module - http://drupal.org/project/print
We altered the print.css file in the modules folder so that the address labels lined up with the template. (Later we ended up adding print.css file in our theme to override the one in the module folder and protect it from updates – Here are the instructions on how to add a style sheet - http://drupal.org/node/171209)
We created an html button in the header of view of pending Commerce Orders. It linked to the print version of the address label view.  (you can add the word print before any relative url to get it's print view)
We altered the browser settings of the guys at our warehouse to exclude all the extra information that comes when the browser prints – Here are some instructions – http://lifehacker.com/5603815/how-can-i-get-rid-of-the-url-and-other-text-when-i-print-from-web-pages
We also altered the margins in the browser.
We will be looking for a better solution as time and money for work permits , but I thought that someone else might find our experience helpful


Is it possible to make a patch that modifies a module's composer.json?

Question: I want to confirm some behavior of Composer to see if this is a limitation of Composer or something I did wrong.
This is based on an issue in the Markdown module queue.
Basically, here's the issue.

The Markdown module requires ^0.15 of a library.
I wrote a patch to require ~0.15 of the library. (to allow 0.16, 0.17, etc.)

But, when I apply this patch via Composer, and then try to update the library, I still get a drupal/markdown  1.2.0  requires  league/commonmark (^0.15.0) even though the module's (patched) code on my site requires ~0.15.
So, is there no way to "patch" a composer.json so that it will be picked up for composer update?  Am I reliant on the module maintainer to commit the patch?
Answer: This issue is actually addressed in the composer-patches documentation:

Because patching occurs after Composer calculates dependencies and installs packages, changes to an underlying dependency's composer.json file introduced in a patch will have no effect on installed packages.
If you need to modify a dependency's composer.json or its underlying dependencies, you cannot use this plugin. Instead, you must do one of the following:

Work to get the underlying issue resolved in the upstream package.
Fork the package and specify your fork as the package repository in your root composer.json
Specify compatible package version requirements in your root composer.json

If you want to follow option #2, you can fork the project's git repo, modify it, and add the forked repo to your project's repositories property:
    {
        "type":"git",
        "url": "https://github.com/vendor/module"
    }

So you can reference that dependency until the upstream has resolved the issue.
Comment: Worth mentioning that when doing so the branch [must be prefixed `dev-`](https://getcomposer.org/doc/05-repositories.md#vcs). No matter how its actual name is. After you added the repository your custom branch should appear prefixed with `dev-` prefix when executing `$ composer show "vendor/module" --all`.


What do I need to get SEEK_HOLE to work with sparse files?

Question: I am trying to work more efficiant with sparse files. I have read about the SEEK_HOLE functionallity in newer Linux Kernels. According to other people, this should be in Kernel version 3.1 and later.
However, as seen bellow, there must be something else to it as well.
I am on kernel 3.2+ and working with sparse files are still slow.
Doing a "cp" or "tar" on this (completely empty) sparse file should take less than 1 sec.
Any idea what I am missing? How can I check if SEEK_HOLE is supported/activated?
They discuss the same thing here, but for some reason I cannot post comments there that it does not work:
Copying a 1TB sparse file
(root@r1)-(/nbd/test)# uname -a
Linux r1.exice.com 3.2.0-33-generic #52-Ubuntu SMP Thu Oct 18 16:29:15 UTC 2012 x86_64  x86_64 x86_64 GNU/Linux
(root@r1)-(/nbd/test)# dd if=/dev/zero of=10g.img seek=10G bs=1 count=1
1+0 records in
1+0 records out
1 byte (1 B) copied, 0.000271811 s, 3.7 kB/s
(root@r1)-(/nbd/test)# time cp 10g.img new.img

real    0m15.370s
user    0m1.544s
sys     0m13.405s
(root@r1)-(/nbd/test)# time bsdtar cvfz new.tar.gz 10g.img
a 10g.img

real    1m59.898s
user    1m43.938s
sys     0m15.769s
(root@r1)-(/nbd/test)# time tar cvfz new2.tar.gz 10g.img
10g.img

real    1m58.584s
user    1m51.275s
sys     0m30.382s

Comment: Yes, I have also noticed this. I was using reiserfs and it refuses to work with it. Switching to ext4 makes it work if I am on 3.5+ kernel. Still does not work on my 3.2 kernel though. Still investigating.
Comment: Ok, seems like bsdtar 3.0.3 does NOT support this at all. Updating to 3.0.4 does work for ext4, but not reiserfs. Same goes for the other tools as well. "cp" version 8.5 does NOT work, but 8.13 do etc.
Comment: Possible duplicate of [Copying a 1TB sparse file](http://stackoverflow.com/questions/13252682/copying-a-1tb-sparse-file)
Answer: Make sure you are using a tool that supports SEEK_HOLE.
bsdtar >=3.0.4

cp >=8.13

Also make sure you run a filesystem that supports it. Works fine with ext4. Does not work with reiserfs.


How do I print the display name?

Question: I have a view with multiple pages. In the Views interface, I can set a display name for each display.

Is there anyway I can print this name in the view itself, for example adding a Global Text field to the views header?
Answer: In Drupal 7, the "Global: Result summary" field in Views header gives you a few tokens to get access to some of the view information (e.g. it has a token named @name -- the human-readable name of the view  to print the View name).
For fetching the View display name, though, you need to create a custom Views handler to define your own tokens:

Create a new module. In your my_module_name.info file, add the lines :

    dependencies[] = views

    files[] = handlers/views_handler_my_custom_handler.inc

In your my_module.module file, add a hook_views_data():

    function my_module_views_data() {
        // Definition of your custom handler
        $data['views']['my_module_custom_handler'] = array(
            'title' => t('My custom handler'),
            'help' => t('Custom tokens to access View information'),
            'area' => array(
                'handler' => 'views_handler_my_custom_handler',
            ),
        );
        return $data;
    }

Finally, create the handlers/views_handler_my_custom_handler.inc file. The most basic content based on your needs would be something like:

/**
 * @file
 * Definition of views_handler_area.
 */

/**
 * Views area handler to display some configurable result summary.
 *
 * @ingroup views_area_handlers
 */
class views_handler_my_custom_handler extends views_handler_area {

    function option_definition() {
        $options = parent::option_definition();
        $options['content'] = array(
            'default' => 'Displaying view tokens',
            'translatable' => TRUE,
        );
        return $options;
    }

    function options_form(&$form, &$form_state) {
        parent::options_form($form, $form_state);

        $variables = array(
            'items' => array(
                '@display_name -- the name of the View display'
            ),
        );
        $list = theme('item_list', $variables);
        $form['content'] = array(
            '#title' => t('Display'),
            '#type' => 'textarea',
            '#rows' => 3,
            '#default_value' => $this->options['content'],
            '#description' => t('You may use HTML code in this field. The following tokens are supported:') . $list,
        );
    }

    /**
     * Find out the information to render.
     */
    function render($empty = FALSE) {
        $format = $this->options['content'];
        // Replace "@display_name" with view current display value
        $output = filter_xss_admin(str_replace("@display_name", $this->view->current_display, $format));
        return $output;
    }

That's it. Your custom views handler should now be available in any View.
I recommend you to have a look at view_handler_area_result.inc file (code for "Global: Result summary" field) in Views module if you wish to extend it to have its tokens available in your custom handler.
Comment: Thanks! That seems to print the name of the View, rather than the display name of the page. E.g. A view is called "Indexes". And in that view, you create multiple pages, each which have a different display name. `@name` prints `Indexes` rather than the display name of the page.
Comment: My bad, you are absolutely right! Basic Views tokens are not enough for what you need.  Please see my edited answer.

How do I print the display name?


https://sessions.bugsnag.com": x509: certificate signed by unknown authority

Question: I have integrated bugsnag with my go-service, and it was working good on my local machine;
but when I deployed it on server it giving the above error whenever bugsnag try to notify error.
I am deploying it on ec2 with docker container.
after exploring Internet I have added below command to my docker file
RUN apk add --no-cache ca-certificates

but this also did not work for me
Below is simplified version of code I am using
package main

import (
    "fmt"
    "github.com/bugsnag/bugsnag-go/v2"
    "time"
)

func init() {
    ConfigureBugsnag()
}

func ConfigureBugsnag() {
    bugsnag.Configure(bugsnag.Configuration{
        APIKey:          "bugsnagKey",
        ReleaseStage:    "stage",
        ProjectPackages: []string{"main", "github.com/myapp"},
    })
}

func main() {

    bugsnag.Notify(fmt.Errorf("Test error"))

    time.Sleep(time.Hour)
}

this is working on local machine but giving the error on server
Comment: Can you also add the contents of you Dockerfile?
Comment: Is your server behind a proxy? If that's the case it's possible you haven't set up the $HTTP_PROXY environment variable on your server, so the transport being used by the notifier isn't correctly configured:
https://docs.bugsnag.com/platforms/go/other/configuration-options/#transport

It may be worth experimenting with the transport configuration to try and isolate the issue.

If the above doesn't help please write into firstname.lastname@example.com and we can try investigate this in more detail.Thanks!"
Answer: I don't have much explanation:
but adding following in the Dockerfile, solved the issue
RUN apk add -U --no-cache ca-certificates
FROM scratch as final
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


What does it mean for a Vector field to be tangent at every point of S?

Question: As background, I am in Vector Calculus. My question is giving me some "short cuts" to use to help with evaluating flux integrals. The hint says "If F (Vector Field) is tangent at every pointof S, then the integral of S of F dot dA =0. What does this mean exactly? How can I know if this vector field is tangent?
The second hint is "If F is perpendicular at every point of S and has a constant magnitude on S, then the integral of S of F dot dA = +/- ||F|| dot Area of the Surface (choose the positive sign if F points in the same direction s the orientation of S, Choose negative if F points in the direction opposite the orientation of S)
I am having trouble understand what these hints mean and when/ how to use them.
The Flux integral I have to solve is: F=e^(y^2+z^2)i through the disk of radius 2 in the yz-plane, centered at the origin and oriented in the positive x direction
Comment: What is it you find confusing? The concept of a vector field? The concepts of being "tangent" or "perpendicular" to a surface at a point? The concept of "magnitude" of a vector? The dot product? The concept of the normal to a surface? If you understand all of those, then this is straight-forward, so obviously you are weak on some of them, but which?
Answer: Presumably, you learned in your class about the normal vector to a surface at a point. Saying the vector field is "tangent to the surface" means that the vector field is perpendicular to the normal vector of the surface. Geometrically/visually, this means the vector points in a direction within the tangent plane at that point.
So if $F$ is the vector field, and $dA$ is the normal to the surface, then $F \cdot dA = 0$, because they are perpendicular. If you integrate zero, you get zero.
The second hint is similar. Saying the vector field is "perpendicular to the surface" means that it points in the same (or opposite) direction of the normal vector everywhere. I guess the notation you are using probably means $dA$ is the unit normal vector. Then $F \cdot dA = \pm |F|$. Remember that if two vectors $v$ and $w$ are parallel, then $|v \cdot w| = |v| |w|$.
So if $|F|$ is the same length everywhere, then $F \cdot dA = \pm |F|$ is a constant function on the surface (it's the same at every point). Integrating a constant function is that constant times the area (this is just a basic principle about double integrals).


Problems with laravel between localhost and hosting

Question: I have the next problem, I have a project in Laravel 5.7 in my localhost computer and I upload this project to my Hosting on Bluehost, the problem is:
I have the file viewcustomers.blade.php in my localhost works ok without problems, but in my hosting this file Dont works...
This is the code:
@foreach($prendas as $prenda)
                            @if($clientes->id == $prenda->idcliente)

                                    nombre}} {{$clientes->apellido}}/{{$prenda->fotoprenda1}}" width="150">
                                    {{$prenda->prenda}}
                                    {{$prenda->marca}}
                                    {{$prenda->modelo}}
                                    {{$prenda->anio}}
                                    $  {{$prenda->limitcredit}}
                                    @if($prenda->status == "Sin Prestamos")
                                        Sin Prestamos
                                        idcliente."/".$prenda->id)}}" class="btn btn-danger">Agregar Prestamo
                                    @elseif ($prenda->status == "En Empeño" and $prenda->restcredit < $prenda->limitcredit)
                                        Empeñada
                                        idcliente."/".$prenda->id)}}" class="btn btn-danger">Agregar Prestamo
                                    @elseif ($prenda->status == "En Empeño" and $prenda->restcredit >= $prenda->limitcredit)
                                        Empeñada
                                        Sin Limite de Credito
                                    @endif

                            @endif
                        @endforeach

Prestamos Actuales

                        @if($prenda->status == "Sin Prestamos" and $clientes->id == $prenda->idcliente)
                           idcliente."/".$prenda->id)}}" class="btn btn-danger">Agregar Prestamo
                        @elseif ($prenda->status == "En Empeño" and $prenda->restcredit < $prenda->limitcredit and $clientes->id == $prenda->idcliente)

                           idcliente."/".$prenda->id)}}" class="btn btn-danger">Agregar Prestamo

                        @elseif ($prenda->status == "En Empeño" and $prenda->restcredit >= $prenda->limitcredit and $clientes->id == $prenda->idcliente)

Sin Limite de Credito

                        @endif

And this is the problem in the Hosting

  status == "Sin Prestamos" and $clientes->id ==
  $prenda->idcliente): ?>
                             idcliente."/".$prenda->id)); ?>" class="btn
  btn-danger">Agregar Prestamo
                          status == "En Empeño" and $prenda->restcredit limitcredit and $clientes->id ==
  $prenda->idcliente): ?>

                       <a href="<?php echo e(url('/addmorepawn/'.$prenda->idcliente."/".$prenda->id)); ?>"

class="btn btn-danger">Agregar Prestamo
                    <?php elseif($prenda->status == "En Empeño" and $prenda->restcredit >= $prenda->limitcredit and $clientes->id ==

$prenda->idcliente): ?>
                              Sin Limite de Credito

                              Fecha Prestamo
                              Cantidad Prestada
                              Plazo
                              Interes
                              Pago Quincenal
                              Fecha Primer Pago
                              Total a Pagar Prestamo
                              Status
                              Boleta de Empeño Arguments "Undefined variable: prenda (View:
  /home/thealmfc/public_html/lonchedeadobada.xyz/resources/views/viewcustomers.blade.php)"

Any idea? thanks
Comment: Check your code, You closed `@foreach` wrongly
Answer: Your error level is diferent between your localhost and your hosting.
Set

error_reporting(E_ALL);
ini_set('display_errors', 1);

on your localhost and you will see the same problem
Answer: Check your code, you closed @foreach wrongly

Prestamos Actuales

    @if($prenda->status == "Sin Prestamos" and $clientes->id == $prenda->idcliente)
        idcliente."/".$prenda->id)}}" class="btn btn-danger">Agregar Prestamo
    @elseif ($prenda->status == "En Empeño" and $prenda->restcredit < $prenda->limitcredit and $clientes->id == $prenda->idcliente)

        idcliente."/".$prenda->id)}}" class="btn btn-danger">Agregar Prestamo

    @elseif ($prenda->status == "En Empeño" and $prenda->restcredit >= $prenda->limitcredit and $clientes->id == $prenda->idcliente)

Sin Limite de Credito

    @endif

Here variable $prenda is out of scope. You closed @foreach before this code snippet.
Comment: Please explain me more


Chord progression notation

Question: from here
At the top - right under  "The perfect authentic cadence. V (dominant) - I (tonic)", in second measure,
they have "6 over 4 over V" on first two beats and then "7" on 3rd beat...
What happens in this measure?? Why is not there Roman numeral under 7??
Answer: In figured bass notation thirds and fifths are implicit in root position chords. Therefore, if you just see a "7", this means R, 3, 5 and 7.
Answer: It is because the 7 concerns also the dominant. You have two different chords for the same function.
Answer: I understand your question. I think this is indeed a mistake in the notation, if my music theory isn't too rusty.
The first two beats of the second measure are indeed clearly a tonic (I 6over4), considering that the notes are dbdg. And only on the third beat it becomes the dominant (be it dominant seven). The V should indeed be on the third beat under the 7.
I think the correct notation would be:
1..2..3..|1..2..3..|1..2..3..||
I..6..ii6|I64...V7.|I........||

Chord progression notation


Android Google auth wierd issue

Question: I implemented google sign in in my app and it works perfectly on debug mode, but in release mode i get an error like this:
<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.e.trackitapp, PID: 23159
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=421, result=-1, data=Intent { (has extras) }} to activity {com.e.trackitapp/com.e.trackitapp.Activities.LoginActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'c.e.u0.a.a.c.a c.e.u0.a.a.b.l()' on a null object reference
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4453)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4495)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6820)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
 Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'c.e.u0.a.a.c.a c.e.u0.a.a.b.l()' on a null object reference
    at com.e.trackitapp.Activities.LoginActivity.a(:86)
    at com.e.trackitapp.Activities.LoginActivity.onActivityResult(:108)
    at android.app.Activity.dispatchActivityResult(Activity.java:7590)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4446)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4495)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6820)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
</code>
The google accounts dialog comes up, it asks me to allow "my app" to use my datas them it shuts down when i clock allow.
Any ideas?
Answer: Did you add production SHA1 key to Firebase settings? I think you may missed it.
https://stackoverflow.com/a/39144864/3614334
Comment: Yes, i did add it, and also replaced the google-services.json

Android Google auth wierd issue


Setting REST value to $scope.value on POST is NULL but accepts hard value

Question: I have a simple form that posts to my REST backend. I have a total of 2 fields on the form, but three values I want to populate.
Using the following form, I have users enter in the articletitle and articlesummary

<form ng-submit="createTask()">
    <input type="text" ng-model="newTask.articletitle"
           placeholder="add new task here">
    <input type="text" ng-model="newTask.articlesummary"
           placeholder="add summary">
    <input type="submit" value="create">
</form>

However, I also want to set a value in my DB for the articlelink to be the articletitle (later, I will adapt this to be the title without spaces, etc.).
Here is my controller:
    pfcControllers.controller('pfcPost', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {

    $scope.newTask = new pfcArticles(
        {
        articletitle: $scope.articletitle,
        articlesummary: $scope.articlesummary,
        articlelink: $scope.articletitle
        });
    $scope.createTask = function () {
        // call the service
        $scope.newTask.$save(function () {
            // when saved, reload the list and recreate a new task
        });
    }
}]);

Currently, it does not post the value of $scope.articletitle to articlelink, but shows it as null
However, if I change it to a hard value, such as follows, it works.
        $scope.newTask = new pfcArticles(
        {
        articletitle: $scope.articletitle,
        articlesummary: $scope.articlesummary,
        articlelink: "hard value"
        });

Here is the backend factory:
    var pfcServices = angular.module('pfcServices', ['ngResource'])

pfcServices.factory('pfcArticles', ['$resource', function ($resource) {
    return $resource('https://myrestcall.net/articles/:articleID', { articleID: '@id' },
    {
        'update': { method:'PATCH'}
    }
    );
}]);

Any clues why it is not taking the scope item as the value? The other values populate without issue.
Comment: implementation og pfcArticles?
Comment: I don't see $scope.articletitle or $scope.articlesummary defined anywhere. I'm surprised they are getting values at all with the code that is posted here.
Comment: I have edited my post to include the factory. I believe that since the controller is tied to the form, $scope is being passed. If this is not correct, please guide.
Comment: I have also tried it this way, but it doesn't save anything unless its hard coded. Scope issue?:     pfcControllers.controller('pfcPost', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {

        var artentry = new pfcArticles;

                artentry.articletitle = $scope.articletitle;
                artentry.articlesummary = $scope.articlesummary;

        $scope.createTask = function () {
            // call the service
            artentry.$save();
        }
    }]);
Answer: I have it working via the following:
Inputs:

<form ng-submit="createTask()">
    <input type="text" ng-model="articletitle"
           placeholder="add new task here">
    <input type="text" ng-model="articlesummary"
           placeholder="add summary">
    <input type="submit" value="create">
</form>

Controller:
    pfcControllers.controller('pfcPost', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {

    var articleentry = new pfcArticles;

    $scope.createTask = function () {

        articleentry.articletitle = $scope.articletitle;
        articleentry.articlesummary = $scope.articlesummary;
        articleentry.articlelink = $scope.articletitle;

        articleentry.$save();
    }
}]);


Sublime Text 3 - Autocomplete de headers no diretorio

Question: Após o insucesso na procura por um plugin no sublime text 3, venho pedir ajuda.
Preciso reconhecer as libs instaladas no sistema, para isso procuro um plugin capaz de fornecer um autocomple na hora do #include das headers (ex. # include < exibir as opções de inclusão aqui>)
Alguem conhece um plugin no sublime text 3 que forneça essa feature, como no Netbeans abaixo?
sistema operacional de uso do editor será o linux.
Answer: EasyClangComplete
Plugin autocomplete para linguagem  C++. Você encontrará o que deseja na configuração include_dirs Que irá buscar por bibliotecas externas como por exemplo Boost, Ros, Eigen, OpenCV, etc.
Onde clang deve procurar pelas bibliotecas:
    "include_dirs" : [
                        "/usr/include",
                        "$project_base_path/src",
                        "/workspace/$project_name/src",
                        "/usr/lib/clang/3.8/include"  // example for Ubuntu 16.04
],

Aqui você pode configurar.
Sem mais delongas acesse a página do plugin no Github e faça o download para testar.
Comment: O plugin localiza para a compilação pelo proprio sublime, mais não faz o drop down das libs que tenho nesses diretorios.


Problems with wamp configuration after installation

Question: I recently installed wamp2.5 and I am having a series of problems with it.

I get the error "Access denied for user: 'dante ' @ ' @ localhost' (password : YES )"
(think the first issue here is why there are two @ signs)
When i try to click on a web project on my localhost interface, instead of the url leading to, for example, localhost/mysite ... it instead points to www.mysite.com

Any help will be highly appreciated
Comment: See [this post for how to configure Apache correctly](http://stackoverflow.com/questions/23665064/project-links-do-not-work-on-wamp-server/23990618#23990618) with Virtual Hosts
Answer: For the second issue you can go to wamp/www/index.php.
And change:
$suppress_localhost = true;

To :
$suppress_localhost = false;

I'll see what I can do about the first problem.
Comment: This is a quick fix that will potentially lead to problems moving projects to a LIVE server. See [this post](http://stackoverflow.com/questions/23665064/project-links-do-not-work-on-wamp-server/23990618#23990618) for a better more realiable solution using Virtual Hosts
Answer: By default WAMPServer like most MYSQL deliveries comes with only one account set in MYSQL.
This is root and comes out of the box with no password set.
So to login to phpMyAdmin for example you should use :
Username = root
Password = (leave it blank)

As to your second point, you should consider setting up Virtual Hosts in Apache for all your projects. See this post for how to configure Apache correctly with Virtual Hosts


Fail Java UDF in finish() function

Question: I'm trying to overwrite a UDF's finish() method where I check if the division of two instance variables exceed a certain threshold.
public void finish() {
    if (errors / total > threshold) {
        throw new IOException("QA failed").
    }
}

My IDE keeps wanting me to surround it with a try/catch block. How do I achieve my original goal of failing within the UDF?
Answer: I think an IllegalStateException or an IOError might be more suitable for your needs as they are unchecked exception and they might resemble your IOException more closely than other unchecked exceptions.
Unchecked exceptions, such as RuntimeException, Error and their subclasses (IllegalStateException and IOError included), do not require a throws clause and will make your code compile.
If you want you can wrap yourIOException in one of the above (using the constructor that takes a Throwable) and retrieve it later with Throwable.getCause()

Fail Java UDF in finish() function


Can anyone explain intuitively why increasing the circumference by 1 meter always increases the radius by 15.9cm?

Question: I found the mathematical proof, and it is obviously correct. But how can the increase in radius be constant regardless of the starting circumference? With a very small circle, the increase should be huge but with a massive circle, the difference should end up miniscule shouldnt it? After all, the 1 m is getting distributed over a much larger circumference
Let the radius of the sphere be R and the new radius be R', hence
$2\pi R' = 2 \pi R + 1$
or,
$2\pi(R'-R) = 1$
or, the height $R' - R$ is $1/{2\pi} = 15.9 cms.$
Comment: I think the physical reasoning will still be mathematical!
Comment: Yeah, I'm not entirely sure if this is appropriate for Physics.SE. It seems to be asking for intuitive mathematical reasoning (!= physical reasoning)
Comment: @Ali I was coming from the POV that this would be related to Newtonian Physics. But yeah, math does make more sense
Answer: With a small circle, the increase is huge with respect to the small circle. Basically, for a circle of radius 1cm, the 15.9cm increase is a lot ... with respect to the original circle.
To convince yourself, consider this: When you increase the radius of a 1m radius circle by 1m, the radius doubles, but if you do it to a 100m circle, it just increases by a tiny amount relative to the original radius. So in the case of the larger circle, the increase seems much less because the relative increase is less, but in both cases the actual increase is the same.
It's a similar situation with the 15.9 cm increase. The absolute increase is the same, but the relative increase (which is what our brains find easier to imagine) is much smaller
Comment: Relative vs absolute resolved 80% of my doubt. the remaining 20% is just me not being able to visualise how, adding a constant amount of circumference to any  circumference increases the radius by a constant amount
Answer: The radius of a circle is directly related to its circumference. The radius is in proportion to the diameter, which is in proportion to the circumference. Radius multiplied by $2$ gives the diameter, which when multiplied by $π$, gives the circumference, or $2πr$.
Answer: Because a circle with a circumference of 1m has a radius of 15.92cm.
So whenever you add 15.9cm to the radius of a circle you add 1m to the circumference.
Or whenever you add 1m to the circumference, you add 15,9cm to the radius.
Because $2\pi \times 0.159155 \approx 1$.
Comment: Welcome on the MathSE! See, how beautiful formulas I made for you. :-)


Can I disable Windows Event Logging for a certain service?

Question: We have a legacy application running on a Windows Server 2008 VM from Azure that is spamming our windows event log every minute or so. I do not have access to the source for the bit of code that is writing to the event log, only the dll file. I cannot rewrite it either as it's a massive piece of software, as much as I'd like to.
So my question is... Is there anyway for me to block the event source for certain messages? Obviously, I don't want to block the whole event source from logging as it does log helpful stuff when it goes wrong, it's just this one particular message is clogging up our server log and getting quite annoying!
Comment: I tried it on win 10 with the guid `{54849625-5478-4994-A5BA-3E3B0328C30D}`. I created a new key `[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WMI\Autologger\EventLog-Security\{9580d7dd-0379-4658-9870-d5be7d52d6de}]`. Then I added the `Enabled` DWORD with `0` value and the `LoggerName` string as `EventLog-Security`, but it's not blocked.
Answer: You can't stop logging for a specific event ID with the means of Windows, however you can change event viewer filter settings so that some items are not displayed if you want to, i.e. to create Custom View.
Comment: This is great, thanks! I've actually created a custom view for just the service that spams excluding 'Information' logs which will be fine for now. The Application Log still will be spammed though.
Comment: Yes, it will be, but you won't see it in your Custom View.
Comment: I've got 10k items per day with that particular ID `1054` (Dell Command | Monitor) and it effectively reduces my log length to 3 days (20MB). What can I do other than increase the size to get meaningful logs? Can I write an automated task to remove that record?
Answer: yes you can...i'm gonna use the WLAN-AutoConfig event id 4001 warning
first, double click on the error/warning in event viewer and click on the details tab and write down the guid  ({9580D7DD-0379-4658-9870-D5BE7D52D6DE})
now open up regedit and go to
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WMI\Autologger\EventLog-System \ {9580d7dd-0379-4658-9870-d5be7d52d6de}]
on the right where the registry entries are, look for "Enabled" which will be set to one, change that to 0.  reboot two times for the entry to take effect.
this has worked for me for three errors/warnings that can be ignored
this should work for windows vista, 7 and 8 and their respective windows server counterparts.  i don't know about windows 10, but you can try
Comment: didn't test for a prolonged period but it seems to work on windows 10 1809. It helped me to stop annoying messages which had been coming each second from WHEA-Logger about corrected hardware error.
Comment: I have also verified that this can be done on Windows 10 (as of 2020-12-04). I used this simple process to turn off several logs that were not essential and loading up the event viewer with thousands of lines over several days. It helped considerably because I can now focus on real issues instead of faux warnings. Much appreciated.
Comment: Mine doesn't list a guid. I was still able to find it by `Provider Name` field, but it was under `CurrentControlSet\Services\EventLog\System\Dell Command | Monitor`. Still no `guid` listed there, like other entries there do though. What now?
Comment: On a Windows Server 2022 I successfully disabled DCOM from spamming System Event Log with errors. The Registry key is "HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\EventLog-System\{1b562e86-b7aa-4131-badc-b6f3a001407e}".
Answer: Use Server Manager, or Perfomance MSC.
Under (Performance)->Data Collector Sets->Event Trace Sessions, select EventLog-Application and press [ENTER].
Under Trace Providers tab (default), look at the Properties list. Here you will find a Level property, which enables you to define (filter) the level of logging as you would expect.
Comment: But does that physically prevent the logs from being recorded and stored in the file, taking up the space?