MediaWiki User Action Logging

Question: Is there a way in a default MediaWiki installation to tell the following:

When a user has logged in or out of the system
I've found this extension for future use http://www.mediawiki.org/wiki/Extension:StalkerLog
To see which pages a user has viewed/reviewed.
Answer: The Special:Log page lists all special actions (Move, Block, Patrol, etc...) and can be viewed by user. Similarly, the Special:Contributions page lists all edits by user/IP. I'm not aware of any way of getting the list of user log on/off times or even the last log on time in the default installation of MediaWiki.
If looking at extensions there are likely a few existing options or making your own. Just a quick search revealed LastLoginTime, SpecialLastUserLoginEx, and UserLoginLog. How well these work or not is another matter.

MediaWiki User Action Logging


Measuring performance drop-off of solid state drives with IOmeter

Question: I would like to measure the performance drop-off in solid state drives when the drives are getting close to full capacity. In particular, I would like to benchmark random and sequential read/writes.
Is this possible in IOmeter? How should I configure IOmeter to run a test like this?
Answer: Anandtech had a really, really great article on SSD's, benchmarking, and what they're good for. They used IOmeter to run their benchmarks, and gave some tips as to what kinds of problems they ran in to.
http://www.anandtech.com/storage/showdoc.aspx?i=3531
page 12 describes how they simulated a 'used' drive that has been hammered on a lot. They did this in order to benchmark how much performance would degrade over the life of the drive.
Comment: Thanks! I had read that article earlier, but didn't read that particular page in detail. I'll update this page with detailed instructions.
Answer: Be prepared to do a lot of testing. I spent a great deal of time trying to understand the relationship between number of writes and write performance of the generally excellent FusionIO devices. The vendor wasn't too helpful in understanding the situation at first.
Remember that the definition of a "free" block can vary. For example, if you wrote to it ever, the storage can't consider it free. Perhaps if you later write to it with all 0's or all 1's, it can flag it as a free block although I have not seen this in practice. I found shocking performance artifacts by creating a logical volume that was only a small portion of the overall storage. Then, creating a logical volume that contained the rest of the storage, writing to it heavily for a half-hour, and deleting the logical volume. To the SSD, these blocks are of course not free. But I had forever destroyed the write performance by doing this test.
By formatting the device with extra "reserved" blocks, the reality of the performance impact was made irrelevant. The FusionIO devices support fast writes because they erase the reserved blocks in the background, and use them for new writes. (The block you overwrote is flagged as free, and later gets erased).
Comment: Good points, but it's worth mentioning that this very situation is what the ATA TRIM command will avoid - it'll allow the filesystem/OS to tell the SSD which blocks are actually free, and the SSD can then go through and delete them pre-emptively.


Can one create a rule in iptables for google's servers only?

Question: I want to allow gmail (and only gmail or other Google properties, not other IPs) to access my pop3 server.
Is there a way to setup iptables to allow all IPs controlled by Google through my firewall?
Answer: You need to have a list of the IPs owned by google.  That list will change over time, so you will need to maintain it, but the process for obtaining the list is at least reasonably clear.
https://support.google.com/a/answer/60764?hl=en gives the process, and you can translate that into a one-liner like so:
dig +short TXT @18.104.22.168 _spf.google.com  | perl -ne 'print join "\n",m/'nclude:([^ ]*)/g' | xargs -n 1 dig +short TXT @188.8.131.52 | perl -ne 'print join "\n", m/ip[46]:([^ ]*)/g'

Now you need just a little more munging to turn that into firewall rules, and you'll have something you can run from cron to maintain your firewall as google's IPs occasionally change.  There's room for a bit of variation in how to do that though.  Do you manipulate iptables directly, or do you go via a more friendly firewall configuration tool? (e.g. I mostly use ferm).
Comment: iptables directly


Ideal of polynomials that vanish on the image of some other set of polynomials

Question: Let $G = \{g_1, g_2, \ldots, g_n\}$ be a finite set of polynomials in $\mathbb{F}[x_1, x_2, \ldots, x_m]$. I'm interested in polynomial dependencies among these polynomials. More specifically, polynomials $f \in \mathbb{F}[G]$ such that $f(g_1, g_2, \ldots, g_n) = 0$. Are there any well known results relating to this kind of thing? Really I'm just looking for directions on things to google. I suspect this might be related to Algebraic Geometry, but I don't know Algebraic Geometry so I'm kind of lost. Thanks for any help!
Comment: Look into syzygies.
Comment: [Gröbner basis](https://en.wikipedia.org/wiki/Gröbner_basis).
Answer: The topic you describe belongs to the area called elimination theory. If you want to find all the relations as described in your post, you're looking for the intersection of the ideal $(y_i-g_i)\subset \Bbb F[x_1,\cdots,x_m,y_1,\cdots,y_n]$ with the subring $\Bbb F[y_1,\cdots,y_n]$. This is called computing an elimination ideal, and the main approach to compute this uses Grobner bases, which is a more sophisticated way of doing polynomial long division in the multivariate setting by playing around with the idea of "leading terms".
This can be somewhat computationally intensive, so frequently it's in your best interest to get a computer to do it for you. Many computer algebra systems have an implementation of this algorithm - for instance, Sage will, with online cell here and documentation about elimination ideals here.
Comment: Thank you! I'll look into it.


Find expression for PDF given range.

Question: I am trying to solve the following problem:
The random variable $Y$ has a negative exponential distribution with pdf as follows:
$ f(y) = λe^{−λy} , y > 0 $
Find an expression for the pdf of $Y$, assuming that $Y ≤ 200$.
I am aware that the integral of the pdf over its range (0-200 in this case) must sum to 1 but trying this method I end up with the following:
$ -e^{-200λ} + 1 = 1 $
Thus $ e^{-200λ} = 0 $
which quite plainly cannot be solved.
I am confused as to why my method isn't working, any explanation would be greatly appreciated.
Answer: I'm presuming what you mean is that $f$ is the density function, and you want the conditional density given the event that $Y\le200$.
$$
\int_0^{200} \lambda e^{-\lambda y} \, dy = \left. -e^{-\lambda y} \vphantom{\frac\int\int} \, \right|_0^{200} = -e^{-200\lambda} - (-1) = 1-e^{-200\lambda}.
$$
So the conditional density is
$$
f(y) = \begin{cases} \dfrac{\lambda e^{-\lambda y}}{1-e^{-200\lambda}} & \text{if }0<y<200 \\[10pt] 0 & \text{otherwise.} \end{cases}
$$
The integral of that function from $0$ to $200$ is
$$
\int_0^{200} \frac{\lambda e^{-\lambda y}}{1-e^{-200\lambda}} \, dy = \frac 1 {1-e^{-200\lambda}} \int_0^{200} \lambda e^{-\lambda y} \, dy = 1.
$$
Comment: Thank you for your solution. I was mistakenly trying to solve for a value of $λ$ which evidently was incorrect, thank you for clearing this up for me.

Find expression for PDF given range.


Leaflet library not avaliable even though it's in sites/all/libraries

Question: I've seen people talking about hook_library() etc., but I'm not creating a custom module, I'm trying to use Leaflet. In the browser I get the error message:
L is not defined

From leaflet.drupal.js in my sites/all/modules folder. I've got the Leaflet and Libraries modules installed and enabled, and the Leaflet files are extracted under sites/all/libraries/leaflet.
Anyone have any idea what I'm doing wrong?
Answer: Looks to me like the library hasn't been installed correctly, the path should be sites/all/libraries/leaflet/leaflet.js you should be able to append this to your sites URL to load the file.
Have you looked through https://www.drupal.org/node/1954942 to see whether anything helps?
Comment: Appending that to the site loads the file (at least I've not screwed up 100% then I guess!). I want to use the library at www.mywebaddress.com/map, so maybe that's the problem? But the libraries folder is under sites/all, so that shouldn't be the case I guess, hmm
Comment: Anything helpful in the console?
Comment: When I access the js file from browser? The only thing I get is
"The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature."
Comment: No when trying to access a page and you get L is not defined
Comment: Ah, no, that's all I get, unfortunately! I tried replacing my leaflet.js (which is the dist version) with the source code version, but I got the same error message!
Comment: I think the problem might be that the leaflet files doesn't actually get LOADED into the site, even though they're in the sites/all/libraries folder. Any idea how I can make that happen?
Comment: The leaflet module gets loaded, but not the leaflet.js from sites/all/libraries (according to the Network tab of the Firefox dev tools)! How can I fix that?
Comment: Can you add `drupal_add_js('sites/all/libraries/leaflet/leaflet.js');`?
Comment: To where? All I've done for the site is strictly through Drupal and it's already made functionality, so I haven't written any code for it (hence I don't know where I should put it)
Comment: OK let's take a step back, how have you added the Leaflet map to your site? What mechanism are you using to display a map?
Comment: A view with an attachment that is of the format "Map (Leaflet API, via IPGV&M)". I've followed this guide quite thoroughly http://www.chenhuijing.com/blog/drupal-101-mapping-with-leaflet-and-ipgeoloc/
Comment: I'm not sure what's wrong, on the status report of a site where I have it installed says Leaflet 0.7.3 The Leaflet Javascript library is installed correctly. One map available.
Comment: Might it have something to do with the installation of the Libraries module?
Comment: In my working site I have the format set to Leaflet Map rather than Map (Leaflet API, via IPGV&M) does that help?
Comment: When I change it to that I get "$menu.on is not a function" from sites/all/themes/multipurpose/js/plugins.js
Comment: If I just put it to Geofield Map I get a standard google maps map to show, so that's something! But I guess that doesn't let me show the nodes I want to show on it!
Comment: Now after changing it back I just get the "$menu.on is not a function" from sites/all/themes/multipurpose/js/plugins.js error message!


Display full webform submission on submission page

Question: I'm using Drupal 7 and I'm learning PHP at the same time.
I'm using the webform module and when users submit a webform on my site, they can see their submission answers on the submission page but they can't see the whole webform with all the components.
I've read the THEMING.txt file in the webform module and I've copied webform-submission.tpl.php to my theme folder and have been trying to edit it but I can't figure out the code I need to use. I think it's probably quite a simple snippet but I'm not advanced enough yet to work it out.
Could someone help me out please?
Answer: It's the webform-confirmation.tpl.php that you'd want to edit.
There's an article here explaining exactly what you want to achieve. https://www.drupal.org/node/1515548
Comment: Thanks for the reply but maybe I should have been clearer.

My clients can only submit a webform once which means that after they have submitted it, all they can see is their submission answers. In this case, the answers on their own have no meaning without the context of the components. In other words, they need to be able to click on the results tab and see the entire webform with the answers that they submitted.

Thanks for any help :)


Incremental adjustments of $\alpha$ for multiple hypothesis testing?

Question: Given a nominal significance level of $\alpha$ for a single hypothesis test, I understand that if you do multiple tests, $i = 1$ to $m$, then according to Dunn's Bonferroni correction, the significance level $\alpha(m)$ of the last test $m$ should be reduced to $\alpha/m$.
Now my question is, what should the significance level be for the preceding tests, $i = 1$ to $m-1$?
According to Bonferroni, $\alpha(i) = \alpha/i$ is applied to the p-value from each successive test - or is it $\alpha(i) = \alpha/m$ for all tests?
But according to Benjamini-Hochberg (1995), $\alpha(i) = \alpha*i/m$ is effectively applied to the ranked p-values once all the results are in.
But these approaches are apparently inconsistent, as Bonferroni gives a curved progression of $\alpha(i)$ to $\alpha(m)$, while Benjamini-Hochberg (1995) gives a straight line progression.
So which is the correct approach?  And what if you don't even know how many tests $m$ you will end up doing?  Or what if you think you know, but decide anyway to add more tests later? How should $\alpha(i)$ change with each successive test?
In particular, if you apply Benjamini-Hochberg's linear progression, and decide to add more tests later, does that mean you have to go back and recalibrate the significance of all of your earlier tests?  And if that is the case, is it statistically correct to take a decision on whether or not to perform additional tests, given that you can already calculate how that will impact the significance of your earlier tests?
Something doesn't seem quite right about this.
Comment: This question somehow confuses the order in which the experiments are performed and p-values are computed (you talk about "preceding" and "succesive" tests and about "incremental" adjustments) and the *ranked* order of the p-values that one needs for the BH procedure. Certainly the p-values from any actual sequence of experiments will not be ordered!
Comment: Yes, hence the question whether the p-values from earlier experiments would then have to be re-ranked as more experiments are added.
Answer: The Bonferroni correction tests each individual hypothesis at the level of $\alpha/m$, where $m$ is the number of tests. There is no difference in this limit based on the order of doing the tests, as your question seems to suggest. This is an attempt to control the family-wise error rate (FWER). At FWER of 0.05, you expect to make some false-positive error in one out of 20 repetitions of the entire sampling and hypothesis-testing process. There are less conservative ways to control FWER, as the pages linked here indicate.
Benjamini and Hochberg propose a way to control something different, the false discovery rate (FDR). That's the expected fraction of total positive calls that are false-positives. That's a different goal than controlling the FWER, with control of the FDR intended to miss fewer true-positives than FWER.
Thinking about the difference between FWER and FDR can be difficult at first, but it's worth the effort.
If you have a small number of pre-specified hypotheses to test, then there may need to be no multiple-correction test at all. Control for FWER or FDR is typically used in cases where all reasonable hypotheses are being tested at once; for example, which of 20,000 genes is more highly expressed in some experimental than in a control condition.
Safest approach would be to consider all the hypotheses you want to test and testing them together with FWER or FDR control. Doing a few tests first and then devising more tests on the same data based on the results of the initial tests runs a risk of data dredging. In your significance testing you would then need somehow to take into account that the generation of the subsequent hypotheses depended on finding the initial hypotheses to be true, not an easy thing for which to correct.
Answer: Congratulations, you are learning that these issues are not simple and there is not a single answer that covers everything.
You need to be careful in interpreting significant results when the researcher has unlimited degrees of freedom in the tests that they can do.  There are arguments that you should adjust for the potential number of tests that could have been done, not just the number that actually were done.
If you keep adding tests, then eventually you will find some analysis that is significant, even if there is no real relationship.  This is easy to see by using your favorite statistical package to generate 20 columns of random data with no planned relationship (generate each column independently of the others), now compute all the pairwise correlations and test if they are equal to 0.  The truth is that the population or process correlations are all 0, but it would be very unlikely to not find at least one significant when looking at each test.  So the adjustment idea is to take into account the number of tests.  Now consider, what if you don't do all the tests, but first do a scatterplot matrix (look at all the pairwise scatterplots) and find the pair that looks to have the strongest relationship and only test that one pair.  Now I have only done one actual test, but since I could have done all the others, the most accurate result would still adjust for all the tests that I could have done, but did not do.
A realistic concern is that if I am the manufacturer of Drug A and want to compare it to drug B, so I do a large randomized trial where patients are randomized to drug and at the end I see no significant difference between the 2 groups, but I still want to sell my drug, so I start looking at subgroups, is drug A more effective in Males? Females?, Older Patients? Younger Patients? Red Haired Patients? Green Eyed Patients? etc.  If I analyze enough subgroups, I will eventually find something significant by chance alone, akin to the random example above.  If I look at plots of the data, or other summaries, I can reduce the number of actual tests (and therefore how many I adjust for).
On the other hand, if I am now looking at side effects and my initial test shows that there are more deaths in the group receiving drug A than in the group receiving drug B, with a p-value of 0.02 (assuming traditional alpha of 0.05), but I don't want to share that.  So I start adding some more tests and find that the rate of drowsiness is not significantly different between the 2 groups and the rate of rashes is not significantly different.  So now I combine all 3 tests and adjust for multiple comparisons and report no significant differences in side effects now.  Here the adjustment has benefited me as an unethical advertiser.
One approach to deal with both of the above problems is to preregister all planned analyses and to not do anything that was not planned ahead of time.  More realistically we state the planned comparisons and report on those, but then also do exploratory analyses beyond those, but those results are dubbed "Exploratory" and used to generate new studies, not as final answers.
But what if death was not one of my planned outcomes, but the data safety monitoring board points out that there are significantly fewer deaths in the treatment group than the control group?  This would be an exploratory outcome, but do we have the equipoise to start a new study looking at death as the outcome and randomize subjects to control?
You can see a lot more discussion on some of these ideas by doing an internet search (google or other) on "Andrew Gelman garden of forking paths".


2GB mysql import

Question: I am running wamp on my local host, the question is, how do I import 2GB mysql database backup file into phpmyadmin.
I tried this command in mysql command line
mysql -u root -p databasename > D:/database.sql
but didn't work, is their any other way to do it?
Answer: Try reversing the redirection:
mysql -u root -p databasename < D:/database.sql

'>' means to redirect the stdout; '<' redirects stdin
If you are indeed using phpMyAdmin, as you say you are, you can log in to it with your same credentials and go to the "Import" tab (one before the last one) and upload the file.
Comment: I am typing this in mysql.exe command prompt, but still its not working
Comment: check d:/database.sql. might have been overwritten by your previous efforts.
Comment: no its still their
Comment: you mentioned mysql.exe command prompt, are you in the mysql shell or a regular command prompt? this needs to be done from a regular command prompt.
Comment: from regular command prompt it shows as C directory, how can I bring shell?
Comment: I think the file should still be there, but its contents should have been overwritten by your previous efforts, as you were redirecting the output of mysql to it. Probably its empty or has something like `Ctrl-C -- exit!` Try opening it with a text editor; replace it with a fresh copy and try again if it's not right.
Comment: in command prompt how to bring the shell??
Answer: Restoring of mysql db from dump file:
mysql -u root -p databasename < D:/database.sql

Answer: Did you try Bigdump? This has nothing to do with PhpMyadmin but will stagger import a local file and tries to execute each set of lines in a session.

2GB mysql import


How to manage the sites name for a django app when deployed?

Question: I'm currently building a Django site that is in essence a type of content management system. However, the type of system is unimportant, but lets call it "CrappyPress - the crappy Django Wordpress-clone".
What I would like is for various people to be able to download the CrappyPress source and run their blogs. Which means that they need to be able to easily configure their site, such as the name of the blog, description, content for the front page, and lots of site-wide individual data.
So far I have come up with 2 approaches neither of which are suitable:

Put all the configuration information in a static configuration file, and have them edit this on the server - which isn't very user friendly.
Make a "site" object, have the user able to edit all of the information there, then restrict the site to having only 1 of these. The issue it this means there is an entry in the admin section, then the user has to go and open the site from the list of 'sites'. Again, not perfect UI-wise.

I've had a look at the "sites framework" and this is more for managing multiple sites hosted through the same django server, which doesn't help me.
Additionally, for what its worth, I'm using South and Grappelli if that influences people.
So how can I make it easy for an admin user to change site wide details of a django app, without odd proxy objects or having the user have to edit HTML or configuration files?
Answer: There are a whole set of apps which can help you save settings to the database called live-settings.
Comment: Thats pretty much straight what I was looking for, but I just didn't know the term. You rock, arocks!


What's the advantage of splitting a mysql table into smaller ones without physical distribution?

Question: I've seen such design in my company.
A big mysql table is split into tens of smaller ones of identical schema on the same server in the same db, without any physical distribution, no innodb_file_per_table, no partitioning, etc. The data is distributed evenly and the read/write access pattern is uniform across all tables.
What's advantage of doing so performance-wise?
Answer: If your reads/writes are distributed evenly, I think there's no performance advantage. If you were write heavy and writing to, for example, just 2-3 of the tables - then you could benefit (see slides 28-34 of this presentation).
A few ideas about operational benefits:

It'll be easier to scale out/shard once there's too much data or too much traffic.
Depending on how your backups are made, it might be quicker to recover something if you can determine in which of the tables lost data was located.

Edit: one more thought: if the queries are executed in parallel, there might be performance benefits - you can get more IOPS from your RAID, and better localisation of multi-core system if the working set fits in the memory.
Comment: i got one more idea - i've edited the answer.
Comment: One more to add; locks (say, from an `ALTER TABLE`) will be more localized.
Comment: Thanks pQd, I see several operational benefits too. One of my colleague suggests that splitting can make the index B-tree smaller and make query cache last longer. But I think the saving is too trivial to make a difference. On the other hand, more tables also add more overheads.
Comment: Not to mention complicating every single query.


jQuery function is resetting dropdown selection

Question: I have a drop-down menu in my page, it's something like this:
   <select id="my_dropdown" name="my_dropdown">
       <option value="one">ONE</option>
       <option value="two">TWO</option>
       <option value="three">THREE</option>
   </select>
   <input type="text" size="10" id="foobar" value="0" />

And my jQuery code is:
   $('#foobar').keyup(function(){
       notOptionOne();
   }

   function notOptionOne() {
       if ( !$('#my_dropdown').val('one') ) {
           alert('Option ONE was not selected');
       }
   }

No matter what is the selection on my dropdown, when I enter any text on the input box, it will show up the alert box and will reset my dropdown selection back to one. I want to keep my selection on where I leave when I close the alert box or do anything else. What is causing this behaviour?
Answer:    function notOptionOne() {
   if ( $('#my_dropdown').val()!='one' ) {
       alert('Option ONE was not selected');
   }
   }

The val() function in jQuery can both get a value or set a value. when you pass a parameter to it, what jQuery do is to set the value of the control. If no parameter, get value.
Answer: Try this:
$('#my_dropdown').val() !== 'one'

$('#my_dropdown').val('one') is jquery wrapper, array-like object. That is why !$('#my_dropdown').val('one') is always false and you don't get an alert.
Answer: try this:
$('#my_dropdown').change(function(){
   if ($(this).val() != 'one') {
      alert('Option ONE was not selected');
   }
})

Answer: $('#my_dropdown').val('one') will set #my_dropdown's value as one (even in if construction).
You should get the value of #my_dropdown element and compare it with string one:
function notOptionOne() {
    if ($('#my_dropdown').val() != "one") {
       alert('Option ONE was not selected');
    }
}


Evaluation of Trigonometric Limit Having $3$ variables

Question:
Evaluation of $$\lim_{(u,v,w)\rightarrow (0,0,0)}\frac{\sin(u^2+v^2+w^2)}{u^2+v^2+w^2}$$
Also How can i justify that the following limit exists.

What i Try
IF $u=v=w=k$. Then $$\lim_{k\rightarrow 0}\frac{\sin(3k^2)}{3k^2}=1$$
But i did not understand what will happen If any two are equal or all three are Different.
Could some Help me to solve it, Thanks
Comment: $z:=u^2+v^2+w^2,$ $\lim_{(u,v,w) \rightarrow (0,0,0)} z=0$. Then $\lim_{z \rightarrow 0^+}\frac{\sin z}{z}=1.$
Comment: Thanks Peter. I have a doubt How can i justify that original limit exists
Comment: To show that the limit exists, you can't escape the $\epsilon-\delta$ mess.
Answer: The distinctness of the variables doesn't matter as long as they all tend to a common value. Let $u^2 + v^2 + w^2 = t$. Then as $u,v,w \to 0$ , $ \,t \to 0$. Then the limit simply reduces to
$$\lim_{t \to 0} \frac{\sin t}{t} = 1$$
Comment: Can we prove it By using $\sin(x)<x<\tan(x)$ and applying sequeeze Theorem
Comment: Thanks Tavish. I have a question How can i justify that original limit exists
Comment: @jacky After doing the substitution, you may show that $\lim_{t \to 0^+} \frac{\sin t}{t} = \lim_{t \to 0^-} \frac {\sin t}{t}$. It can also be shown graphically.
Comment: Yes, that is another neat way to do it.
Answer: You may consider the spherical coordinates. Indeed, one has
\begin{align*}
\begin{cases}
u = r\cos(\theta)\sin(\varphi)\\\\
v = r\sin(\theta)\sin(\varphi)\\\\
w = r\cos(\varphi)
\end{cases} \Longrightarrow u^{2} + v^{2} + w^{2} = r^{2}
\end{align*}
Therefore the given limit can be rewritten as
\begin{align*}
\lim_{(u,v,w)\rightarrow(0,0,0)}\frac{\sin(u^{2} + v^{2} + w^{2})}{u^{2} + v^{2} + w^{2}} = \lim_{r\rightarrow 0}\frac{\sin(r^{2})}{r^{2}} = 1
\end{align*}
Hopefully this helps.
Answer: The function $f(x)=\sin(x)$ is defined as the one that solves the differential equation
$$f'' = -f $$
with $f(0)=0$ , $f′(0)=1$.
From the definition it is direct that
$$\lim\limits_{x\rightarrow 0} \frac{\sin(x)}x =\lim\limits_{x\rightarrow 0} \frac{f(x)-f(0)}{x-0}=f'(0)=1$$
Of course, this is deeply unsatisfactory, because by what right do we take as a definition that the sine solves precisely that differential equation?
Well, that has to do with the fact that $f^2 + (f′)^2$ is a constant function (that is demonstrated by deriving with the chain rule and checking that the derivative is zero everywhere); and evaluating it at 0 it is determined that the constant is 1. Therefore, $f(x)$ and $f'(x)$ are the lengths (signed) of the legs of a right triangle whose hypotenuse measures 1. On the other hand, with many others accounts it can be shown that $f$ meets the identity of the "sum of angles"
$$f(x+y)=f(x)f'(y)+f'(x)f(y)$$
which gives the idea that x is precisely the angle that makes $f(x)$ the length of the leg opposite x, and $f'(x)$ the length of the leg adjacent to x. With that, the definition above allows to recover the geometric definition, being f the sine function and $f'$ the cosine function.


Criando um conjunto de variaveis no PHP

Question: Sou novato em PHP, e estou com algumas duvidas. Notei que quando as variáveis são criadas, os tipos não são especificados.
Sendo assim:

como faço para criar as variáveis do tipo short int, int e char? Ele cria o tipo de variável na inicialização da mesma?
e como eu poderia verificar o tamanho da varivel em bytes?
Além disso, é possivel criar um conjunto de variáveis no PHP, e a partir de um identificar desse conjunto, atribuir valores a essas variáveis?
Comment: Acho que "Vista de olhos" em Portugual é "dar uma olhada" no Nrasil
Comment: Dá um vista de olhos em http://php.net/manual/en/language.oop5.typehinting.php
Comment: Não entendi ....
Comment: Nao entendi o conteudo do link passado ... Não consegui relacionar com minha pergunta
Answer: O PHP é uma linguagem de tipagem fraca. Isso significa que não é necessário definir um tipo para a variável.
Então é como você disse:

ele cria o tipo da variável na inicialização da mesma

Exemplo:
 $int = 1;

 $float = 1.44;

 $string = 'stackoverflow';

 $boolean = false;

 $array = array();

 $object = new stdClass;

Você pode testar os tipos dessas variáveis através de funções como is_string, is_float, is_int e is_boolean.
É possível também obter o nome do tipo de variável através da função gettype.
Exemplo:
$array = array(1, 2, 3);

gettype($array); // array

Indução de Tipos
No PHP é possível "induzir tipos" específicos (não todos) para parâmetros passados em funções.
Podemos checar se um determinado objeto é de uma determinada instância ou subinstância. Se ele implementa uma interface, se é um callback, ou se é um array.
Exemplos de indução de tipo para classes:
class X{
   public function get(){}
}

function usa_x(X $x){
    return $x->get();
}

usa_x(new X);

Exemplos de indução de tipo para arrays:
function usa_array(array $array){
  foreach($array as $key => $value);
}

usa_array(1); // gera um erro!

Exemplos de indução de tipo para callbacks (a partir do php 5.4):
function usa_callback(callable $callback)
{
     return $callback(1, 2, 3);
}
usa_callback('var_dump');

usa_callback(function ($a, $b, $c){
   var_dump($a, $b, $c);
});

usa_callback('nao_existe'); // gera um erro

SplType
Há uma extensão chamada Spl Type, onde é possível simular a definição de tipos através de instâncias de classes específicas para cada tipo.
Exemplo:
$int = new SplInt(94);

try {
    $int = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

echo $int . PHP_EOL; // Value is not integer

Se  isso for necessário (creio que na maioria dos casos não é), aqui está o link para SplType
Comment: Interessante... Outra coisa, esse array em PHP, é semelhante a struct do C? por que pelo que eu pesquisei, no array, podemos criar variáveis que são chamadas de "chaves" e atribuir valores para elas a partir da instancia do array, certo?
Comment: Sim. No PHP o `array` (atualmente -  como diz a documentação) é uma matriz ordenada. Não é simplesmente uma lista onde começa do 0 e vai até aonde você parar de adicionar elementos nessa lista!
Comment: O que eu pretendo fazer, é um conjunto de dados em um array, enviar esse array via socket para um programa em C, e esse programa C deve mover o bloco de memoria desse array para cima de uma struct que contem o mesmo conjunto de dados. Seria possivel? Se não, pq?
Comment: @Vynstus, nesse caso já muda muito o foco da pergunta. Sugiro que crie nova pergunta ou modifique a atual.
Comment: Eu criei, http://pt.stackoverflow.com/questions/76845/criando-buffers-em-php

Criando um conjunto de variaveis no PHP


Is it possible to create & access a minix file system from Fedora 15?

Question: Due to some, ah... legacy requirements, I find myself needing to create and access minuxfs partitions from a modern distribution (specifically Fedora 15). Unfortunately, there appears to be no documentation available to help me accomplish this task and I am operating almost completely in the dark.
Should it be possible to create and access minuxfs partitions from Fedora 15?
If it is possible, what steps do I need to take to allow the following:
1) Creation of minux file system partitions (e.g. mkfs.minix /dev/whatever or mkfs -T minix /dev/whatever)
2) Mounting of those partitions (e.g. mount -t minix /dev/whatever)
Answer: To mount a minix filesystem, you'll need to load the minix driver with modprobe minix. mkfs.minix is a part of util-linux, but Fedora deletes it before creating their package, see https://bugzilla.redhat.com/show_bug.cgi?id=248293. You can download the source code from http://www.kernel.org/pub/linux/utils/util-linux/ and compile it yourself.
Comment: This answer got me closest to what I needed to do. The specific steps that were necessary in my case (or at least the ones that worked for me) were: 1) Rebuild the kernel (using the information from http://fedoraproject.org/wiki/Building_a_custom_kernel). 2) Download and build util-linux. 3) Set SELinux to permissive mode (without which I couldn't create certain folders necessary on the media after mounting it).
Answer: You will need minix kernel driver and minixfs user space tools. You have to check if the minix kernel driver is still included in your kernel. There is also a FUSE based implementation: http://code.google.com/p/fuse-minix/
Comment: For anyone coming along later who, like me, thought the FUSE implementation had value, the project appears to have been moved or abandoned. The SVN repository at code.google.com is empty and there is no indication of the new location.


Criar pastas no KCFinder

Question: Há alguma maneira/configuração para criar pastas pelo KCFinder no diretório de uploads dele?
Ex: O diretório padrão é /images, dentro dele gostaria de criar outras pastas pelo próprio KCFinder, porém não achei esta opção.

Sei que poderia usar o php para criar as pastas, mas seria melhor (principalmente para o cliente) se pudesse fazer isso pelo próprio KCFinder.
Answer: Dentro do arquivo config.php na raiz do CKFinder você indica um local com a cadeia de pastas a serem carregadas no bloco "Backends":
<code>    $config['backends'][] = array(
    'name'         => 'default',
    'adapter'      => 'local',
    'baseUrl'      => '../../../../home/SEU DIRETÓRIO/',
    'root'         => '', // Can be used to explicitly set the CKFinder user files directory.
    'chmodFiles'   => 0777,
    'chmodFolders' => 0755,
    'filesystemEncoding' => 'UTF-8',
);
</code>
E no bloco logo abaixo, você indica as pastas raiz desse apontamento no bloco "Resource Types":
<code>$config['resourceTypes'][] = array(
    'name'              => 'Caixa',
    'directory'         => 'CAIXA',
    'maxSize'           => 0,
    'allowedExtensions' => '7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip',
    'deniedExtensions'  => '',
    'backend'           => 'default'
);
</code>

Criar pastas no KCFinder


How to put a link in my route title?

Question: In my custom module amap, I have amap.routing.yml with (among others) this route:
amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title: 'Update Planning'
  requirements:
    _permission: 'edit distribution inscription entities'

I'd like to have a link in the title of the route, something like
Update Planning Click here
Drupal 8 API documentation says in Structure of routes

_title: The page title for the route. It may differ from the menu link title.
  _title_arguments: Additional arguments for the title text passed along to t().
  _title_context: Additional context information for the title text passed along to t().
  _title_callback: A PHP callable (typically classname::method) returning the page title for the route.

but I don't know how to use it...
How can I do that?
Answer: In you routing.yml change _title to _title_callback as below:
amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title_callback: '\Drupal\amap\Controller\TitleController::title'
  requirements:
    _permission: 'edit distribution inscription entities'

Create a "TitleController" controller in you amap module unser "src/Controller"
TitleController.php
<?php

namespace Drupal\amap\Controller;

use Drupal\Core\Controller\ControllerBase;

class TitleController extends ControllerBase {

  public function title() {
    return t('Update Planning Click here');
  }

}

Now your title will be callable from the controller and you can give whatever that likes you here.
Comment: I tried something like `return t('Update Planning') . ' ' . t('Click here');`
and it doesn't work! Any idea why?
Comment: IMO you have to use only one t() to render proper URL.

How to put a link in my route title?


Convert a Char Matrix to Numeric, avoiding display in scientific notation

Question: I have a pretty large dataset of coordinates. When I imported them, R turned them into characters. When I try converting my matrix into a numeric one, R turns my longitudinal values into scientific notation.
As an example,
head(locations)

        Long         Lat
[1,] "-120.5215"  "34.5318"
[2,] "-120.86726" "35.36824"
[3,] "-120.86726" "35.36824"
[4,] "-120.86726" "35.36824"

using the as.numeric function R returns my longitudinal values to scientific notation.
locations <- apply(locations,  c(1, 2),as.numeric)
head(locations)

         Long       Lat
  [1,] -1.205215e+02 34.53180
  [2,] -1.208673e+02 35.36824
  [3,] -1.208673e+02 35.36824
  [4,] -1.208673e+02 35.36824

How can I get R to turn this non-numeric matrix into a numeric one WITHOUT it screwing up the coordinate format?
Comment: Can you show a sampling of what R returns?
Comment: `mode(test) <- "numeric"`
Comment: @BrianO'Donnell, Hello, I have edited my question and added more details. Thank you for taking time to help. As you can see, using the as.numeric function will mess up the format of my longitudinal values. And for mapping purposes, the package I'm using doesn't accept scientific notation formats.
Comment: @BrianO'Donnell, hello again! I think I figured it out. There was one longitudinal value with a missing decimal point (making the number really large), so R re-formatted the rest of the coordinates using scientific notation.
Answer: I figured it out! In case anybody else is having the same problem this is the code that I used:
>test #non-numeric matrix
    long        lat
[1,] "-112.16442" "39.5934"
[2,] "-110.61798" "35.76698"
[3,] "-110.20331" "39.87408"

>apply(test, 2,as.numeric) #Numeric-matrix

         longs     lats
[1,] -122.1644 37.29340
[2,] -120.6180 37.76898
[3,] -121.2033 34.86808

And it didn't ruin the format. Yey.
Comment: I'm glad you solved your problem, but this question & answer won't likely help anyone unless you edit your question to provide more details about what specifically you tried with `as.numeric`, what the exact output was, and why it wasn't correct. I suspect the problem was simply that `as.numeric` dropped the dimensions and returned a vector rather than a matrix.


If condition with date interval and dynamic year

Question: I need a little help about a "if" condition in a specific period od the year. Cause I want to this once time forever the year myst be dynamic.
It will be like:
if (1 December of current year < $today > 8 january of next year)

I don't know how to do date's math for having the year that dynamically changes!
Answer: if (strtotime("1 December") < time() > strtotime("8 January next year"))

Comment: It's not correct! Why you vote this answer without knowing if it's working?? There is a syntax error, you can't comparion with 2 logical operator in php...needs some braket. The other error is the same sa mine. If you put "next year" and for example we are on 4 january 2011, when you make the comparsion it make with 8 january 2012....so it doesn't work!!
Comment: @Kreker, you are really something else! Somebody is trying to help and you shout at them like this?
Comment: @kreker about other error, you asc about 1 Dec and 8 jan next year. strtotime functions are work correctly for this dates.
Answer: @Kreker, my good man, use Or instead of And:
if ((strtotime("1 December") < time()) || (time() < (strtotime("8 January"))))
{
    echo "Yip!";
}


Herança multi-tabela no Laravel

Question: Tenho uma entidade Resource, que por sua vez tem várias implementações, por exemplo, VideoResource e MarkdownResource. Resource tem várias propriedades compartilhadas, os outros dois exemplos por sua vez, tem propriedades específicas para eles.
Eu já vi sobre herança usando single-table, mas acredito que não pode ser o meu caso, já que posso ter várias implementações de Resource e cada implementação pode ter de 2 a 5 propriedades específicas.
Como fazer esse tipo de relação com Eloquent?
Answer: A forma que foi criado para trabalhar com esse tipo de relacionamento é Polymorphic Relations, na pergunta só foi informado os nome das tabelas que é o suficiente para criar um exemplo minimo:
Migration:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class TableVideoResources extends Migration
{
    public function up()
    {
        Schema::create('videoresources', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title', 50);
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('videoresources');
    }
}

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class TableResources extends Migration
{
    public function up()
    {
        Schema::create('resources', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 50);
            $table->timestamps();
            $table->integer('resourceable_id')->unsigned();
            $table->string('resourceable_type', 100);
        });
    }
    public function down()
    {
        Schema::dropIfExists('resources');
    }
}

Class Model:
<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Resource extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'resources';
    protected $fillable = ['name'];
    public $timestamps = true;

    public function resourceable()
    {
        return $this->morphTo();
    }
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class VideoResource extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'videoresources';
    protected $fillable = ['title'];
    public $timestamps = true;

    public function resource()
    {
        return $this->morphOne(Resource::class, 'resourceable');
    }
}

ou seja, a classe VideoResource foi configurada para ter uma relação com Resource, dividindo ai os dados que são diferentes para VideoResource e as outras classes que herdam o que é igual devem ser configuradas igual VideoResource (na sua pergunta além de VideoResource tem MarkdownResource). Mas não existe muita mágica nisso tudo, por exemplo para salvar as relação deve criar primeiro VideoResource e acessar a relação e criar a Resource, exemplo:
Gravando VideoResource:
$videoResource = App\Models\VideoResource::create(['title' => 'Stackoverflow']);

Gravando Resource pela relação:
$videoResource->resource()->create(['name' => 'Portugues Brasil']);

para recuperar as informações:
App\Models\VideoResource::with('resource')->find(3);

Saída:
=> App\Models\VideoResource {#787
     id: 3,
     title: "Stackoverflow",
     created_at: "2018-02-22 14:27:39",
     updated_at: "2018-02-22 14:27:39",
     resource: App\Models\Resource {#793
       id: 3,
       name: "Portugues Brasil",
       created_at: "2018-02-22 14:29:57",
       updated_at: "2018-02-22 14:29:57",
       resourceable_id: 3,
       resourceable_type: "App\Models\VideoResource",
     },
   }

se pode verificar tudo isso na documentação e nesse exemplo minimo.
Referencias:

Polymorphic Relations
What Are Polymorphic Relations and How Do We Use Them with Eloquent?
Comment: Eu até já tinha esquecido da pergunta, tentei resolver e consegui, exatamente da forma explicada. Aqui segue o repositório que implementa o problema já resolvido: https://github.com/lykeios-io/lykeios

Herança multi-tabela no Laravel


How to evaluate $\frac{d}{dt} \left\{\frac{\partial F}{\partial x_1}(tx)\right\}$?

Question: Let $F:\mathbb{R}^3\to\mathbb{R}$ be of class $C^\infty$. Consider
$$t\in\mathbb{R}^* \mapsto \frac{\partial F}{\partial x_1}(tx),$$
with $x\in\mathbb{R}^3$.
I am in trouble understanding what is
$$\frac{d}{dt} \left\{\frac{\partial F}{\partial x_1}(tx)\right\}.$$
I would say that it is something like
$$\frac{\partial^2 F}{\partial x_i \partial x_1}(tx)\cdot x,$$
but I am not confident at all.
Could someone please help me with that?
Thank you.
Comment: Yes. (filling in character requirements)
Comment: Should be $x_i$, and a sum over $i$. Anyway, this is the kind of thing the chain rule is for
Comment: @peek-a-boo do you mean that it should be $\sum_{i=1}^3 \frac{\partial^2 F}{\partial x_i \partial x_1} (tx) x_i$?
Answer: The Leibniz notation could be sometimes very confusing, as it is in this case. If we write something like $\frac{d}{d s}H$ for some function $H$, then it means that the domain of $H$ is one-dimensional, say $\mathbb{R}$. However if we write $\frac{\partial}{\partial s}H$ it means that the domain of $H$ is multidimensional, say $\mathbb{R}^n$ for some $n>1$.
However sometimes we can write $\frac{d}{d \mathbf{x}}H$ to denote the Fréchet derivative of a function $H$ who domain is a vector space, but this notation is not used very much and in the context it is understood when $\mathbf{x}$ refers to a vector or an scalar.
Thus if you write $\frac{d}{d t}\left[\frac{\partial}{\partial x_1}F(t\mathbf{x})\right]$ then the function on the brackets just depends on $t$, this means that $t\mathbf{x}$ must depends only on $t$, that is, that $\mathbf{x}$ depends on $t$ also. Using the notation $\frac{\partial}{\partial x_k}$ together with $\mathbf{x}=(x_1,\ldots ,x_n)$ means that $\mathbf{x}$ is a function of $t$, otherwise the notation is misleading, so we can write
$$
\frac{\partial}{\partial x_1}F(t\mathbf{x})=\left(\frac{\partial}{\partial x_1}F\circ g\right)(t),\quad  g(t):=t\mathbf{x}(t)=(tx_1(t),\ldots,tx_n(t))=(g_1(t),\ldots,g_n(t))
$$
Therefore by the chain rule
$$
\begin{align*}
\frac{d}{d t}\left[\left(\frac{\partial}{\partial x_1}F\circ g\right)(t)\right]&=\left(\frac{d}{d \mathbf{x}}\frac{\partial}{\partial x_1}F\circ g\right)(t)\frac{d}{d t}g(t)\\
&=\sum_{k=1}^n\left(\frac{\partial^2}{\partial x_k\partial x_1}F\circ g\right)(t)g_k'(t)\\
&=\nabla \left(\frac{\partial}{\partial x_1}F\right)(t\mathbf{x}(t))\cdot (\mathbf{x}(t)+t\mathbf{x}'(t))\tag{*}
\end{align*}
$$
where $\frac{d}{d \mathbf{x}}$, as discussed before, represents the Fréchet (total) derivative. When $\mathbf{x}$ is constant, say $\mathbf{x}(t):=\mathbf{v}$ for some fixed vector $\mathbf{v}$ for every $t$, then the notation and the context must explicitly show it.
However if we would write $\frac{\partial}{\partial t}\left[\frac{\partial}{\partial x_1}F(t\mathbf{x})\right]$ then the notation means that $t$ is a coordinate of $\frac{\partial}{\partial x_1}F(t\mathbf{x})$ so it can be understood something like
$$
\frac{\partial}{\partial x_1}F(t\mathbf{x})=\left(\frac{\partial}{\partial x_1}F\circ h\right)(\mathbf{x},t),\; \text{ for }(\mathbf{x},t)=(x_1,\ldots,x_n ,t)\;\text{ and }\, h(\mathbf{x},t):=t\mathbf{x}
$$
Therefore, again using the chain rule, we have that
$$
\begin{align*}
\frac{\partial}{\partial t}\left[\left(\frac{\partial}{\partial x_1}F\circ h\right)(\mathbf{x},t)\right]&=\frac{d}{d(\mathbf{x},t) }\left[\left(\frac{\partial}{\partial x_1}F\circ h\right)(\mathbf{x},t)\right]\mathbf{e}_{n+1}\\
&=\left(\frac{d}{d \mathbf{x}}\frac{\partial}{\partial x_1}F\circ h\right)(\mathbf{x},t)\frac{d}{d (\mathbf{x},t)}h(\mathbf{x},t)\mathbf{e}_{n+1}\\
&=\left(\frac{d}{d \mathbf{x}}\frac{\partial}{\partial x_1}F\circ h\right)(\mathbf{x},t)\frac{\partial }{\partial  t}h(\mathbf{x},t)\\
&=\sum_{k=1}^n \left(\frac{\partial^2}{\partial x_k\partial x_1}F\circ h\right)(t)\frac{\partial}{\partial t}h_k(t)\\
&=\nabla \left(\frac{\partial}{\partial x_1}F\right)(t\mathbf{x})\cdot \mathbf{x}\tag{**}
\end{align*}
$$
where $\frac{d}{d (\mathbf{x},t)}$ means the Fréchet (total) derivative of the function, and $\mathbf{e}_{n+1}:=(0,0,\ldots,0 ,1)\in \mathbb{R}^{n+1}$, that is, is the unit-length vector in the direction of the last coordinate of $(\mathbf{x},t)$. Note the difference between (*) and (**).
Answer: Generally for a function $G:\mathbb{R}^n\longrightarrow \mathbb{R}$ we have
\begin{align*}\frac{dG}{dt} = \sum_{i=1}^n\frac{\partial G}{\partial x_i}\frac{dx_i}{dt}\end{align*}
so in your case we have
\begin{align*}
\frac{d}{dt}\frac{\partial F}{\partial x_1}(tx) = \sum_{i=1}^n\frac{\partial^2 F}{\partial x_i\partial x_1}\frac{d(tx_i)}{dt} = \sum_{i=1}^n\frac{\partial^2 F}{\partial x_i\partial x_1}x_i = \nabla(\frac{\partial F}{\partial x_1})(tx)\cdot x
\end{align*}
Comment: Yes, that's exactly what it is. Don't forget though, that it is evaluated at $tx$, not just $x$
Comment: It is the dot product between the first column of the Hessian matrix of $F$ and $x$, isn't it?
Comment: this is not right, or at least is misleading. See my answer.
Comment: @Masacroso I get your point, but I'm pretty sure that $x$ is supposed to be constant w.r.t. $t$ which would make the two answers coincide as far as I can see


View output add a class to first and last rows

Question: I'm trying to output views and i'm using 960gs as well.
It possible to enable views processing so views knows if it this is the last one of the row and that way i can add a class "alpha" to the first view out put and "omega" to the 4th item and last item?
Update: Looking for primarly a php solution; not a jquery one; as it's not best practice to utilize javascript to manipulate layouts (IMHO).
Answer: The contributed Semantic Views module has the option of adding first and/or last class attributes. Pretty snazzy solution since you can also use it to specify better html elements at the same time!
Answer: if you does not recieve answers that help from backend perspective, I am sure that you can solve this from jquery perspective:
Jquery select first and last divs from a list of items: https://stackoverflow.com/questions/3328076/jquery-select-first-and-last-divs-from-a-list-of-items
For instance this set of divs (also is possible with li, a, etc..):

qwe

asd

zxc

ghj

bnm

with Jquery you can select first and last item, in this case, to add a class to first/last target elements (put this in the end of your view results template):

of course you must have respective class to this different elements, for instance:

and here is the result:

this is another example: Addressing first/last item in an ul, li: https://stackoverflow.com/questions/5680032/addressing-first-last-item-in-an-ul-li
I hope information be useful.
Comment: Good point there @moon.watcher . Trying to avoid requiring javascript to manipulate layout. I'll give you a +1 anyways; but looking for merely a php solution.
Comment: yes, I agree about avoid manipulation of layout using javascript. Altough I think that Jquery has an good crossbrowser compatibility in lots of cases (its my humble opinion) and you can try/research/build alternatives to achive low consuption of resources of your scripts. Of course I can be wrong
Answer: Discovered that this is answer is still being worked on by the community. It's been a long-standing problem with views.
There's a issue queue node here: http://drupal.org/node/1188216
Hopefully, there will be a patch for this eventually.
As for now; I've found refuge in display suite for certain contexts and semantic views plugin


Show Modal From dynamically inserted button

Question: I have a table element :

and I am inserting rows dynamically in the table:
postConTable = "
<input id=\""+value.processId+"-details\" type=\"button\" class=\"btn btn-primary view-details\" value=\"View Details\" />
";
$("#postcon-table-success").append(postConTable);

here button has id as dynamic variable (processID) followed by "-value"
eg.230002-details, where 230002 is processID.
Now I am clicking the button
$('#postcon-table-running').on('click',".view-details", function() {
   console.log(this.id);
   $('#myModal').modal('show');
});

which is calling the jquery function and the log is getting printed :
230002-details
But its not showing the modal which is in the body tag.

Please wait

We are fetching data

Please help.
To ADD- when I create my modal in the parent tag of '#postcon-table-running', it is working.
But I cant do it that way because I want to implement same functionaliy from various buttons in various other divs.
Comment: do you see the modal html using firebug or page source? do you get errors in your error console?
Comment: Table rows are appended to `#postcon-table-success` but click handling is delegated to `#postcon-table-running`. Are you sure that's right?
Answer: It could be that the modal is not visible to the on click function.  Put your modal at the very end of the page.


Approximating Binomial with Normal

Question: Consider approximating a binomial distribution with normal. Originally, my binomial distribution is discrete, where the heights of the bars represent the probability. However, after approximating this distribution with a normal one, we find the probabilities using the area beneath the normal curve. How have the probabilities just changed from being heights to area? It seems unintuitive how these probabilities are more or less the same.
Comment: Rectangles have area too
Answer: It is an approximation, and only works reasonably well in some cases.
Let's take an example where it works well if you approach it sensibly, where $X$ is a binomial random variable with $n=48$ and $p=\frac14$,
so with mean $12$ and standard deviation $3$, and $Y$ is a normal distribution with the same mean and standard deviation.
Suppose we want to approximate $P(X \le 10)$. This is also $P(X \lt 11)$ because of $X$ only taking integer values so it is not obvious where to look on the distribution of $Y$, but it might be sensible to consider $P(Y \le 10.5)=P(Y \lt 10.5)$ and this is about $0.309$.  In fact $P(X \le 10) \approx 0.316$, so a reasonably close approximation if not exact.
We can extend this to looking at $P(X=10)$ and a reasonable approximation might be about $P(Y \le 10.5)-P(Y \le 9.5) \approx 0.106$ when the exact figure is $P(X=10)={48 \choose 10}\frac{3^{38}}{4^{48}} \approx 0.112$, again reasonably close though not exact.
You can say $P(X=10) = P(X \le 10.5)-P(X \le 9.5)$ and so $P(Y \le 10.5)-P(Y \le 9.5)$ looks more reasonable as an approximation in this context.
$P(Y \le 10.5)-P(Y \le 9.5)$ is the probability represented by the area over an interval, while $P(X \le 10.5)-P(X \le 9.5)$ is the probability of the point $10$ in the middle of the interval, but in terms of cumulative distribution functions there is not much practical distinction from this point of view.
(Another possible approximation to $P(X=10)$ is the density of $Y$ at $10$ and this is also about $0.106$, but this can be seen as an approximation of the average density across the interval of width $1$ and so to the area, and is not really relevant to your question.)

Approximating Binomial with Normal


correios frete gem

Question: Olá, estou usando esse cálculo no controller porém quando coloco <%= @pac %> ou <%= @sedex %> na view não está mostrando o valor, alguém está tendo o mesmo problema?
grato
def calculate_ship
frete = Correios::Frete::Calculador.new :cep_origem => "23970-000",
:cep_destino => params[:post_code]
servicos = frete.calcular :sedex, :pac
@pac = servicos[:pac].valor
@sedex = servicos[:sedex].valor
redirect_to checkout_order_path
end

Answer: O problema é que você está fazendo um redirect_to ao final. Isso faz com que seja feito uma nova requisição ao servidor e os valores são perdidos.
Você precisa substituir por algo como render 'checkout'.
Comment: é isso mesmo, obrigado pela dica Gui.

correios frete gem


What is the best way to load many youtube videos?

Question: I made a site displaying many youbute videos. If I load all of them at the same time then the site is too slow.
So I load them by inserting rows into a table with Math.min(1ms * 5^row_number, 500ms) delay between each row. Here is what my table looks like. The videos are embedded via iframes.
<code>video_11 video_12 (loads at 1ms)
video_21 video_22 (loads at 5ms)
video_31 video_32 (25 ms)
video_41 video_42 (125 ms)
video_51 video_52 (500 ms)
video_61 video_62 (500 ms)
</code>
It looks kind of choppy, is there a better way?
Answer: I wouldn't load the videos themselves.  That is a waste of bandwidth.
Why not grab a sceenshot instead?
Load a few videos if you want, and only load the rest on demand.
Also, be careful, the more videos you have being loaded, the more buffering you are likely to be doing...
Comment: Thanks, I think this will work. How do we load the video after a thumbnail is clicked? nvm, i see it in the jsfiddle. I don't understand how it works but I can figure it out.
Comment: Possibly the same way that you are loading your own videos right now.  Create a javascript / JQuery / AJAX function that when you click a particular image, will _replace_ the content of the cell with the video you want.


Como verificar se existe um determinado numero numa variável php?

Question: Então eu estava dando uma pesquisada, procurando alguma função do php que verifica se um determinado numero existe dentro de uma variável. E eu encontrei a preg_match(). Só que tem um porem, o php da um erro e pelo que eu intendi ela não  funciona com números só com outros caracteres alguem pode me ajudar?
código:
$numeros = "1 2 3 4 5 6 7 8 9";
preg_match(1,$numeros);

Erro:

Warning: preg_match(): Delimiter must not be alphanumeric or backslash
Comment: As funções a abaixo funcionaram. muitos obrigado.
Comment: você precisa usar os delimitadores...
Answer: Utilize os delimitadores dentro da string que você esta procurando:
$numeros = "1 2 3 4 5 6 7 8 9";
preg_match('/1/',$numeros); // Você pode usar / ou #

Answer: Pode-se usar o strpos(). Mas tem que ser encarada como string.
$numeros = "1 2 3 4 5 6 7 8 9";
$temNumero = strpos($numeros, '1');

if($temNumero >= 0) // ou ($temNumero > -1)
   echo 'Achou';
else
   echo 'Não achou';

Ou usando preg_match_all(), numa expressão regular.
$re = '/[1]/';
$str = '123456';

preg_match_all($re, $str, $matches);

if(count($matches) > 0)
   echo 'Achou';
else
   echo 'Não achou';

Comment: A primeira solução tem muitas limitações, principalmente porque a função `strpos` retornará 0 para o número 1 e quando testado no `if`, o teste falhará.
Comment: Corrigido, Anderson. Thanks.
Answer: Utilize strrpos ou strripos se não retornar falso foi encontrado:
int strrpos ( string $haystack , string $needle [, int $offset ] )

Exemplo no seu código:
<?php

    $numeros = "1 2 3 4 5 6 7 8 9";

    $result = strrpos ($numeros, "8");

    if (is_int($result))
    {
        echo 'encontrado';
    }
    else
    {
        echo 'não encontrou';
    }


Does one have to be disabled to participate in wheelchair fencing?

Question: What qualifies you to fence in a wheelchair competition? I am wondering because of this video from the Paralympic games 2012, where the two opponents walk around quite a bit and only use their wheelchair while fencing.
Answer: Yes, participants in wheelchair fencing in the Paralympic Games need to be disabled.
The Paralympic Movement provides sport for people with disabilities.  They list ten eligible impairment types, and in order for an athlete to compete, he or she must have a primary impairment that belongs to one of these impairment types.
Each sport in the Paralympics has specific classifications with medical eligibility rules.  For wheelchair fencing, which is administered by the International Wheelchair and Amputee Sports Federation(IWAS), these rules are found in the IWF Rules for Competition: Book 4: Classification Rules.  The book spells out tests that certified Classifiers use to determine whether or not an athlete is eligible.
Classifiers administer functional and bench tests to place athletes in one of five sport classes: 1A, 1B, 2, 3, and 4.  On one end of the spectrum, class 1A participants are "athletes with no sitting balance who have a handicapped playing arm.  No efficient elbow extension against gravity and no residual function of the hand which makes it necessary to fix the weapon with a bandage."  At the other end, class 4 participants are "athletes with good sitting balance with the support of lower limbs and normal fencing arm."
At the Paralympics, fencers compete in two categories: Category A is for fencers in class 3 or 4, and Category B is for fencers in class 2.  There is a Category C for fencers in classes 1A and 1B; this category does compete in some international competitions, but is not normally in the Paralympic Games. (Source)
The IWAS has a formal protest process. If someone feels that another athlete has not been classified correctly, they can issue a protest, and a jury of Classifiers will investigate and rule.
The video that you referenced is of the gold medal bout at the London 2012 Paralympic Games in the Men's Individual Sabre Category A, the category for athletes with the least impairment.
Comment: Thank you, very interesting! Is there a way to find out what disabilities those two fencers have? Or is this confidential as it's quite private?
Comment: @user4769 The athletes in the video are Yijun Chen and Tian Jianquan, both of China, but I haven't been able to find any more information on them yet.


What happens to the messages being processed on functions running when we disable the function?

Question: We are working with Azure functions, which are triggered on every message in the service bus queue. We are trying to solve a problem whereby we need to disable a function on the function app processing messages, dynamically, so that it does not process messages any further and we do not lose any message in the process as well.
We can disable the functions via multiple ways, referring to link but the problem remains the same. Unable to figure out what happens to the functions already spawned when trying to disable the same.
Since the function is service bus triggered there is always a possibility that the function is processing a message and we disable the same, does it get processed, any sorts of cancellation is raised, it just dies out with an exception?
It would be great someone could direct me to some documentation or something. Thanks.
Answer: Azure Service Bus triggered function will already have a lock on the message that's being processed. If Function is terminated and the message was not completed or disposition, the lock will expire and the message will reappear on the queue. That's because of the Functions runtime receives a message in PeekLock mode.
One factor to consider is the queue's MaxDeliveryCount. If a function is terminated upon the last processing attempt, the message will be dead-lettered as all processing attempts have been exhausted. That's a standard Azure Service Bus behaviour.


Do I need to find odd ratio for the result of binomial GLMM?

Question: I have run a binomial generalised linear mixed model (GLMM) via the lme4 package in R. Then I have got the result for it. In the paper, I wrote this for the result: b = 2.23, SE = 0.59, p < 0.01.
However, I'm not sure if I need to find odd ratio for this? If yes, can you please tell me how to do it in R. And how I should add the odd ratio result in the finding?
Answer: You definitely should report the odds ratio, logits are often difficult to interpret. It's been awhile since I've done one but try (with glmer loaded) either A or B.
A.)
fixed <- fixef(ModelName)
confintfixed <- confint(ModelName, parm = "beta_", method = "Wald")
OR <- exp(cbind(fixed, confintfixed))
OR
B.)
parameters::parameters(ModelName, exponentiate = TRUE, details = TRUE)
Other info below
https://www.rdocumentation.org/packages/lme4/versions/1.1-31/topics/glmer
^glmer package link
https://cran.r-project.org/web/packages/sjPlot/vignettes/plot_model_estimates.html
^ cool way to visualize odds
Comment: Hi Nick, the optimal model of mine is the one with three-way interaction. I've run emmeans function. Then it gives me the p-value of each pair of contrasts: for example, ao clear dm - av con no    -3.2262 0.595 Inf  -5.425  <.0001 / However, when I run the formula you've given me, the odd ratios are not for each pair of contrasts. So I can't add the odd ratio to the p-value. What should I do then? Is there the way to find odd ratio for each contrast for the three-way interaction model?
Comment: I'm not entirely sure, I'd need a bit more information. Do you have the output from the syntax above? Can you screen shot it so I can see what your saying?
Comment: Sure. Please see above.
Answer: The optimal model of mine is from this syntax:
fm1 <- glmer (answer~ (1|subj) + (1|item) + seeconversationmask, data=analysis1, family=binomial, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
So I have three variables. They're all categorical. The first variable has two categories; the second one has two categories and the last one has three caetegories. The optimal model is the model with three-way interaction which means all variables are needed to explain the finding.
And this is the output I've got from emmeans package to see if there are significant differences in each contrast:

The example of my interpretations is 'The participants received significantly lower score in ao, clear, dm context than ao, con, dm context (b = -4.74, SE = 0.60, p < 0.01).'
However, after running your syntax, it gives me this:

So now I wondered how the output from OR syntax fits with the comparisons of each pair contrast. Could you please suggest me about this?


Tangent bundle of P^n and Euler exact sequence

Question: I'm thinking about the Euler exact sequence for complex projective space, and I'm a bit confused. In the topological category, one has
$$ T\mathbb{P}^n \oplus \mathbb{C} \cong L^{n+1} $$
where $L$ is the tautological line bundle and $\mathbb{C}$ is the trivial line bundle. This comes from a splitting of the vector bundle homomorphism $\mathbb{C}^n \rightarrow \mathbb{C}^n/L$ which you can get by picking a Hermitian metric.
In algebraic geometry, you get a (non-split) exact sequence, which is the dual of the Euler sequence (http://en.wikipedia.org/wiki/Euler_sequence).
Is the Euler sequence for the holomorphic tangent bundle of $\mathbb{P}^n$ split as above? It would seem so, since even though we are in the holomorphic setting we can run the first argument with the Fubini-Study metric, but I've read some things that seem to suggest otherwise.
Answer: No, any construction using the Hermitian metric is going to take you outside the holomorphic category! By the way, you can understand the Euler sequence very elegantly by mapping $\Bbb P^n\times \Bbb C^{n+1}\to T\Bbb P^n\otimes\mathscr L$ as follows: If $\pi\colon\Bbb C^{n+1}-\{0\}\to\Bbb P^n$ and $\pi(\tilde p) = p$, for $\xi\in T_{\tilde p}\Bbb C^{n+1}$, map $\xi$ to $\pi_{*\tilde p}\xi\otimes\tilde p$, and check this is well-defined.
You might also try to generalize the Euler sequence to a complex submanifold $M\subset\Bbb P^n$, letting $\tilde M = \pi^{-1}M$. Then you get the exact sequence
$$0\to \mathscr L \to E \to TM\otimes\mathscr L\to 0\,,$$
where $E_p = T_{\tilde p}\tilde M$ for any $\tilde p\in \pi^{-1}(p)$. ($\tilde M$ is the affine cone corresponding to $M\subset\Bbb P^n$.)
Answer: No. If you consider the Euler exact sequence for $\mathbb{CP}^1$, we have the sheaf of 1-form is the canonical sheaf for $\mathbb{CP}^1$ which is $O(-2)$. By Euler exact sequence ,
$$0 \rightarrow O(-2) \rightarrow O(-1)^2\rightarrow O\rightarrow 0$$.
However, $O(-2)\oplus O$ is not isomorphic to $O(-1)^2$ as algebraic vector bundle (or locally free sheaf if you like) since the former has global holomorphic section but the latter doesn't.


Acrescentar itens vazios no final de array

Question: Olá pessoal preciso fazer o seguinte e não estou dando conta.
Tenho que criar uma array para gerar uma saida json com 50 itens por exemplo, mas se quando buscar no banco tiver somente 30 ele completar os 50 itens com valores vazios. Com os mesmo keys, mas sem valores.
while ($rowx = $stmtx->fetch(PDO::FETCH_ASSOC)){

                    extract($rowx);

                    $emp_itemx=array(
                        "idhis" => $idhis,
                        "id_user_cartao" => $id_user_cartao,
                        "ponto" => $ponto,
                        "id_user" => $id_user,
                        "qtde_pontos" => $qtde_pontos,
                        "iduserpromo" => $iduserpromo
                    );

                }

                echo json_encode($emp_itemx);

Comment: por que essa linha  do PDO não tá assim: $rowx = $stmtx->fetchAll(); já que virão varios resgistros do bd o fetchAll é mais indicado
Comment: dessa forma não seria também necessário chamar a função extract já que o resultado já viria assim $emp_itemx= array([0] =>array(
                    "idhis" => "xxxx",
                    "id_user_cartao" => "xxxx",
                    "ponto" => "xxxx",
                    "id_user" => "xxxx",
                    "qtde_pontos" => "xxxx",
                    "iduserpromo" => "xxxx")
                );
Comment: Marcos, valeu a dica, mas o meu problema é como descrevi acima, a questão dos dados do banco não estou tendo problemas. Preciso mesmo é completar os dados em branco no array!!
Comment: o array que você representou está errado, é mais fácil iterar sobre o retorno usando um foreach ao final ao invés do while
Comment: retorno  Array
(
    [0] => Array
        (
            [idhis] => 'xxx',
            [id_user_cartao] => 'xxx',
            [ponto] => 'xxx',
            [id_user] => 'xxx',
            [qtde_pontos] => 'xxx',
            [iduserpromo] => 'xxx'
        )
Comment: Tudo bem, mas como eu poderia completar o resultado que preciso?
Answer: Preencha um array com um valor determinado através da função array_fill() e combine dois ou mais arrays pela função array_merge()
<?php
$array1 = [];

//Define um elemento vazio para posterior preenchimento
$vazio = [
  "idhis" => null,
  "id_user_cartao" => null,
  "ponto" => null,
  "id_user" => null,
  "qtde_pontos" => null,
  "iduserpromo" => null
];

//Simula um preenchimento de 30 itens de $array1
foreach(range(1,30) as $n){
   $array1[] = [
    "idhis" => -$n,
    "id_user_cartao" => $n,
    "ponto" => $n * 10,
    "id_user" => $n * 100,
    "qtde_pontos" => $n * 1000,
    "iduserpromo" => $n * 10000
  ];
}

//Cria um array 20 elementos definidos como sendo vazios
$array2 = array_fill(0, 20, $vazio);

//Junta $array1 e $array2
$resultado = array_merge($array1 , $array2);

print_r($resultado);

Teste o código funcionando em https://repl.it/repls/RemarkableWatchfulDemand
Array
(
    [0] => Array
        (
            [idhis] => -1
            [id_user_cartao] => 1
            [ponto] => 10
            [id_user] => 100
            [qtde_pontos] => 1000
            [iduserpromo] => 10000
        )

    [1] => Array
        (
            [idhis] => -2
            [id_user_cartao] => 2
            [ponto] => 20
            [id_user] => 200
            [qtde_pontos] => 2000
            [iduserpromo] => 20000
        )

    [2] => Array
        (
            [idhis] => -3
            [id_user_cartao] => 3
            [ponto] => 30
            [id_user] => 300
            [qtde_pontos] => 3000
            [iduserpromo] => 30000
        )

    [3] => Array
        (
            [idhis] => -4
            [id_user_cartao] => 4
            [ponto] => 40
            [id_user] => 400
            [qtde_pontos] => 4000
            [iduserpromo] => 40000
        )

    [4] => Array
        (
            [idhis] => -5
            [id_user_cartao] => 5
            [ponto] => 50
            [id_user] => 500
            [qtde_pontos] => 5000
            [iduserpromo] => 50000
        )

    [5] => Array
        (
            [idhis] => -6
            [id_user_cartao] => 6
            [ponto] => 60
            [id_user] => 600
            [qtde_pontos] => 6000
            [iduserpromo] => 60000
        )

    [6] => Array
        (
            [idhis] => -7
            [id_user_cartao] => 7
            [ponto] => 70
            [id_user] => 700
            [qtde_pontos] => 7000
            [iduserpromo] => 70000
        )

    [7] => Array
        (
            [idhis] => -8
            [id_user_cartao] => 8
            [ponto] => 80
            [id_user] => 800
            [qtde_pontos] => 8000
            [iduserpromo] => 80000
        )

    [8] => Array
        (
            [idhis] => -9
            [id_user_cartao] => 9
            [ponto] => 90
            [id_user] => 900
            [qtde_pontos] => 9000
            [iduserpromo] => 90000
        )

    [9] => Array
        (
            [idhis] => -10
            [id_user_cartao] => 10
            [ponto] => 100
            [id_user] => 1000
            [qtde_pontos] => 10000
            [iduserpromo] => 100000
        )

    [10] => Array
        (
            [idhis] => -11
            [id_user_cartao] => 11
            [ponto] => 110
            [id_user] => 1100
            [qtde_pontos] => 11000
            [iduserpromo] => 110000
        )

    [11] => Array
        (
            [idhis] => -12
            [id_user_cartao] => 12
            [ponto] => 120
            [id_user] => 1200
            [qtde_pontos] => 12000
            [iduserpromo] => 120000
        )

    [12] => Array
        (
            [idhis] => -13
            [id_user_cartao] => 13
            [ponto] => 130
            [id_user] => 1300
            [qtde_pontos] => 13000
            [iduserpromo] => 130000
        )

    [13] => Array
        (
            [idhis] => -14
            [id_user_cartao] => 14
            [ponto] => 140
            [id_user] => 1400
            [qtde_pontos] => 14000
            [iduserpromo] => 140000
        )

    [14] => Array
        (
            [idhis] => -15
            [id_user_cartao] => 15
            [ponto] => 150
            [id_user] => 1500
            [qtde_pontos] => 15000
            [iduserpromo] => 150000
        )

    [15] => Array
        (
            [idhis] => -16
            [id_user_cartao] => 16
            [ponto] => 160
            [id_user] => 1600
            [qtde_pontos] => 16000
            [iduserpromo] => 160000
        )

    [16] => Array
        (
            [idhis] => -17
            [id_user_cartao] => 17
            [ponto] => 170
            [id_user] => 1700
            [qtde_pontos] => 17000
            [iduserpromo] => 170000
        )

    [17] => Array
        (
            [idhis] => -18
            [id_user_cartao] => 18
            [ponto] => 180
            [id_user] => 1800
            [qtde_pontos] => 18000
            [iduserpromo] => 180000
        )

    [18] => Array
        (
            [idhis] => -19
            [id_user_cartao] => 19
            [ponto] => 190
            [id_user] => 1900
            [qtde_pontos] => 19000
            [iduserpromo] => 190000
        )

    [19] => Array
        (
            [idhis] => -20
            [id_user_cartao] => 20
            [ponto] => 200
            [id_user] => 2000
            [qtde_pontos] => 20000
            [iduserpromo] => 200000
        )

    [20] => Array
        (
            [idhis] => -21
            [id_user_cartao] => 21
            [ponto] => 210
            [id_user] => 2100
            [qtde_pontos] => 21000
            [iduserpromo] => 210000
        )

    [21] => Array
        (
            [idhis] => -22
            [id_user_cartao] => 22
            [ponto] => 220
            [id_user] => 2200
            [qtde_pontos] => 22000
            [iduserpromo] => 220000
        )

    [22] => Array
        (
            [idhis] => -23
            [id_user_cartao] => 23
            [ponto] => 230
            [id_user] => 2300
            [qtde_pontos] => 23000
            [iduserpromo] => 230000
        )

    [23] => Array
        (
            [idhis] => -24
            [id_user_cartao] => 24
            [ponto] => 240
            [id_user] => 2400
            [qtde_pontos] => 24000
            [iduserpromo] => 240000
        )

    [24] => Array
        (
            [idhis] => -25
            [id_user_cartao] => 25
            [ponto] => 250
            [id_user] => 2500
            [qtde_pontos] => 25000
            [iduserpromo] => 250000
        )

    [25] => Array
        (
            [idhis] => -26
            [id_user_cartao] => 26
            [ponto] => 260
            [id_user] => 2600
            [qtde_pontos] => 26000
            [iduserpromo] => 260000
        )

    [26] => Array
        (
            [idhis] => -27
            [id_user_cartao] => 27
            [ponto] => 270
            [id_user] => 2700
            [qtde_pontos] => 27000
            [iduserpromo] => 270000
        )

    [27] => Array
        (
            [idhis] => -28
            [id_user_cartao] => 28
            [ponto] => 280
            [id_user] => 2800
            [qtde_pontos] => 28000
            [iduserpromo] => 280000
        )

    [28] => Array
        (
            [idhis] => -29
            [id_user_cartao] => 29
            [ponto] => 290
            [id_user] => 2900
            [qtde_pontos] => 29000
            [iduserpromo] => 290000
        )

    [29] => Array
        (
            [idhis] => -30
            [id_user_cartao] => 30
            [ponto] => 300
            [id_user] => 3000
            [qtde_pontos] => 30000
            [iduserpromo] => 300000
        )

    [30] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [31] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [32] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [33] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [34] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [35] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [36] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [37] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [38] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [39] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [40] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [41] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [42] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [43] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [44] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [45] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [46] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [47] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [48] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

    [49] => Array
        (
            [idhis] =>
            [id_user_cartao] =>
            [ponto] =>
            [id_user] =>
            [qtde_pontos] =>
            [iduserpromo] =>
        )

)

Answer: nesse caso estou supondo que só existe um registro retornado do BD:
$emp_itemx=array(array(
                "idhis" => 'xxx',
                "id_user_cartao" => 'xxxx',
                "ponto" => 'xxx',
                "id_user" => 'xxx',
                "qtde_pontos" => 'xxx',
                "iduserpromo" => 'xxxx'
            ));

for($i = count($emp_itemx);$i < 50;$i++){
$emp_itemx[$i] = array(
"idhis" => '',
"id_user_cartao" => '',
"ponto" => '',
"id_user" => '',
"qtde_pontos" => '',
    "iduserpromo" => '');

}
desssa forma ele acrescentará tantos quantos forem necessário até atingir os 50 registros
Comment: Vou testar e já aviso!!  Valeu
Comment: Marcos, ela está repetindo a quantidade que falta pra inteirar 50 depois de cada item que vem do banco e não só final de todos!! se tenho 20 linhas no banco ele coloca mais 30 depois de cada um, ficando com 600 linhas no array.
Comment: é essa a questão, você deve ter inserido o for dentro do while
Comment: Realmente, vacilo. Está completando o restando certo fora do while, mas está retornando somente 1 item que vem do banco!!
Comment: por isso te falei sobre substituir o fetch() pelo fetchAll();
Comment: assim: $emp_itemx = $stmtx->fetchAll(); você economiza um while() e um extract(); e não vai precisar nem mesmo iterar esse array. o json_encode já entende
Comment: Quem sabe sabe. Valeu Marcão. Tava sofrendo aqui, agora que peguei seu raciocínio, não precisava de nada daquilo mesmo, é não estou acostumado com PDO, eu sempre uso msqli.
Comment: Veja como fiz:
`
$card_arrx=array();
    $emp_itemx = $stmtx->fetchAll();

    for($i = count($emp_itemx);$i < 15;$i++){
    //echo "cont: ".$i;
    $emp_itemx[$i] = array(
    "idhis" => '',
    "id_user_cartao" => '',
    "ponto" => '',
    "id_user" => '',
    "qtde_pontos" => '',
     "iduserpromo" => '');
    }`
Comment: insere na pergunta as linhas de código que vem antes, não to entendendo essa linha $card_arrx=array();
Comment: Marcos, somente iniciei a variável do tipo array.
Comment: então funcionou?
Comment: Funcionou sim Marcos, graças às duas dicas. Obrigado!!


How can I merge these functions?

Question: Given Data:
There are three functions

f(x)=sin(πx/2)
g(x)=sin(πx/3)
h(x)=sin(πx/4)

and a point A(6,0).
To find:
Which of the given functions pass via point A.
My Approach:
As the  y coordinate of pt.A is 0, we know that any function which passes through pt.A will definitely pass via x axis at that point. Also, if a function passes through  A(6,0), this implies that for that function, at x=6 , the  y value, or f(6)  should equal 0.Plugging in x =6, we get:

f(6)=g(6)= 0 ;h(6)≠0

⇒ The functions f(x)  & g(x)  pass via point A(6,0).
My question:
Is there any method by which I can merge/combine the equations of the given functions so that I get a single equation which serves the whole purpose (instead of plugging values in individual equations, can I merge all equations to get a single equation which works for all)? Is it possible?
Comment: You can make it a single multi-variable function $f(x,y)=\sin({\pi x\over y})$ but you still need to test three points $(6,2,0)$, $(6,3,0)$, $(6,4,0)$. If your question means "computationally perform a single test" then I think there is no such method.
Comment: okk...thank you
Answer: It depends on what you mean.  If you're looking for a way to have three yes/no answers from the same process, that would be multivalued, and typically we define functions to only output a single value.
If you're fine with losing information in the process, there are some simple options that might give you a useful single value, depending on your application.  For example, if you are trying to test for at least one of these functions passing through (6,0), then you could use:
$$
q(x) = f(x) \cdot g(x) \cdot h(x) \\
$$
which would return 0 if and only if at least one of them were 0.
Or if you were only interested in the case where all the functions are 0, you could use:
$$
q(x) = (f(x))^2 + (g(x))^2 + (h(x))^2
$$
which (assuming your functions output real numbers and not imaginary numbers) will output zero if and only if all the functions are 0.
Comment: Well, think about it.  If f(6) is anything but zero, it'll become a positive number when squared, no matter how small.  Same for g(6) and h(6).  If you add positive numbers together, they only get farther from zero.  The only way for it to stay at zero is for all of them not to increase the total sum.
Comment: alright, got it...thanks
Comment: I should have qualified the above with: these are simple solutions.  It should be possible to craft a function that whose return value has a factor of +2 if f(x) is zero, a factor of +3 if g(x) is zero, and a factor of +5 if h(x) is zero, and zero otherwise.  That way, you could test for if any of them were zero, and be able to figure out which ones, based on factoring the answer.  Something like that.  But that seems more difficult.

How can I merge these functions?


pegar nome do campo na query e popular outro!

Question: estou fazendo uma pesquisa no banco.
Na tabela, tenho 6 datas: data1, data2, data3, data4, data5 e data6.
Estou varrendo essas datas para saber qual delas combina com o mês atual.
Isso já está sendo feito:
...
WHERE
 YEAR(data1) = YEAR(CURRENT_DATE) AND MONTH(data1) = MONTH(CURRENT_DATE) OR
 YEAR(data2) = YEAR(CURRENT_DATE) AND MONTH(data2) = MONTH(CURRENT_DATE) OR
 YEAR(data3) = YEAR(CURRENT_DATE) AND MONTH(data3) = MONTH(CURRENT_DATE) OR
 YEAR(data4) = YEAR(CURRENT_DATE) AND MONTH(data4) = MONTH(CURRENT_DATE) OR
 YEAR(data5) = YEAR(CURRENT_DATE) AND MONTH(data5) = MONTH(CURRENT_DATE) OR
 YEAR(data6) = YEAR(CURRENT_DATE) AND MONTH(data6) = MONTH(CURRENT_DATE)
ORDER BY cliente, tipo, id

Agora preciso descobrir em qual data (1,2,3,4,5 ou 6) que caiu para pegar esse número procurar em outro campo chamado valorX, onde x é o valor do campo data (1,2,3,4,5 ou 6) e concatenar e retornar quantos reais estão nesse campo.
Alguém me ajuda nessa lógica?
Comment: Já avaliou a utilização do CASE / WHEN?
Comment: Ainda não. Na verdade não sei como fazer!
Minha dificuldade aqui está lógica. Eu acho!
Answer: Não entendi sua construção para o valor do ano e mês a serem pesquisados mas experimente colocar na lista de campos de seu SELECT:
SUM (CASE WHEN (year(data1) = ano AND month(data1) = dia) THEN valor1
     CASE WHEN (year(data2) = ano AND month(data2) = dia) THEN valor2
     CASE WHEN (year(data3) = ano AND month(data3) = dia) THEN valor3
     CASE WHEN (year(data4) = ano AND month(data4) = dia) THEN valor4
     CASE WHEN (year(data5) = ano AND month(data5) = dia) THEN valor5
     CASE WHEN (year(data6) = ano AND month(data6) = dia) THEN valor6) AS valor_total

Por "concatenar" entendi que você deseja somar os valores.
Comment: Acho que da forma que eu estou querendo fazer não vai possível com uma só SQL. Mas é o seguinte: Após a sql decidir em qual campo data (data1, dat2...data6) caiu o ano e o mes passados, então ele vai pegar esse valor (1,2,...6) e vai concatenar com a palavra valor ficando valor1, o valor2, etc... e depois disto buscar qual o conteúdo do mesmo retorno que há no campo valor+numero. Acho que terei que mudar a abordagem pois está ficando muito bagunçado! e pode acabar saindo do foco do fórum.