Find $x$ if $\frac {1} {x} + \frac {1} {y+z} = \frac {1} {2}$

Question: I found this question from past year's maths competition in my country. I've tried any possible way to find it, but it is just way too hard.

Find $x$ if \begin{align}\frac {1} {x} + \frac {1} {y+z} &= \frac {1} {2}\\ \frac {1} {y} + \frac {1} {x+z} &= \frac{1}{3}\\ \frac {1} {z} + \frac {1} {x+y} &= \frac {1} {4}\end{align}
$(A)\;\frac 32$
$(B)\;\frac {17}{10}$
$(C)\;\frac {19}{10}$
$(D)\;\frac {21}{10}$
$(E)\;\frac {23}{10}$

EDIT: I'm very sorry guys, it should be $\frac {1} {x+y}$ not $xy$, I'm sorry for the typos (idk what is wrong with me)
Comment: Hint: start with the last formula $$\frac {1} {x} +\frac {1} {y} + \frac {1} {z} + \frac {1} {xy}  + \frac {1} {yz} + \frac {1} {xz}= \frac {13}{12}$$ and multiply both sides by $xyz.$
Comment: are you sure that you have made no typo?
Comment: are $x,y,z$ real numbers?
Comment: do you want to find special method to find x?or just find x? it is easy to find one value from first equation put another by this way find others
Comment: you mean eliminate the variable $x$?
Comment: @Dr.SonnhardGraubner,yes
Comment: I tried using the standard methods below and didn't get the answer, but left it there to show the techniques and hopefully someone can spot the error
Comment: "solving your question" does not require "solving the system of equations" you have just to study the $5$ cases one by one (maybe not elegant but this is the shortest way) take $x=\frac{3}{2}$ and replace in the equations if you can find $y$ and $z$ then it's the good answer if there is a contradiction then go to the second option $\cdots$
Comment: apparently this was all an exercise in futility, as the question was typed in wrong.
Comment: @Elaqqad I disagree.  Answering the question on the test can be done by going through the cases.  However, the cases are an artifact of the way the test is designed, and no adequate solution worthy of being posted on math.SE will rely on case analysis unless there is a rationale for the cases beyond "the test had these as the possible answers." This is about problem solving, not test taking strategies.
Comment: @wuiyang And your thoughts on this are?
Answer: \begin{align}
\frac {1} {x} + \frac {1} {y+z} &= \frac {1} {2}\\ \frac {1} {y} + \frac {1} {x+z} &= \frac{1}{3}\\ \frac {1} {z} + \frac {1} {x+y} &= \frac {1} {4}
\end{align}
Is equivalent to the system
\begin{align}
xy+xz&=2(x+y+z)
\\
xy+yz&=3(x+y+z)
\\
xz+yz&=4(x+y+z),
\end{align}
Solving this system as a linear system of
equations in terms of $xy,xz$ and $yz$ and $x+y+z$,
we arrive at
\begin{align}
xy&=\tfrac12 (x+y+z), \quad(1)
\\
yz&=\tfrac52 (x+y+z),
\\
xz&=\tfrac32 (x+y+z).
\end{align}
Dividing these equations pairwise, we get
\begin{align}
z&=5x
\\
y&=\tfrac53 x,
\end{align}
combining with (1) we have
\begin{align}
\tfrac{5}{3}x^2-\tfrac{23}{6}x&=0
\end{align}
and since $x\ne0$, the answer is $x=\tfrac{23}{10}$.
Answer: NOte: edit #1, equations changed when typo was noticed
NOTE!!!  This is not a complete solution, and there is likely something wrong with it.  I'm posting it for 2 reasons:  1: To show the type of logic one would use, and 2: To see if anyone can spot the mistake so it can be fixed.  (and 3, I spent so much time on it I don't want to delete it!)
Now:
Multiply through each equation by $xyz$ to get rid of the factions, and turn it into 3 equations in 3 unknowns:
$$yz+x=\frac 1 2 xyz $$
$$xz +y=\frac 1 3 xyz $$
$$xy+z=\frac 1 4 xyz $$
Let's go backwards and use the third equation to solve for z:  Subtract z from both sides and factor out the z, and you get $$xy=z(\frac 1 4 xy -1)$$, to clear the fractions I'm going to multiply through by 4 for convenious,  giving $$4xy=z(xy-4)$$,  thus $$z=\frac {4xy} {xy-4}$$  Now we plug that into our first two equations for $z$, giving us
$$y(\frac {4xy} {xy-4})+x=\frac 1 2 xy(\frac {4xy} {xy-4}) $$ and
$$x(\frac {4xy} {xy-4})+y=\frac 1 3 xy(\frac {4xy} {xy-4}) $$
Now, we're going to solve the second equation for $y$.  Again, it's much easier to get rid of the fractions first, so I'm going to multiply the whole equation by $3(xy-4)$ to get $$12x^2y+3xy^2-12y^2=4x^2y^2$$ Every term has a $y$ and $y\ne 0$, so cancelling, we get $$12x^2+3xy-12y=4x^2y$$
Move the two terms with $y$ to the right hand side and factor out the $y$, and we get $$12x^2=y(4x^2+12-3x)$$, hence
$$y=\frac {12x^2} {4x^2 +12 -3x}$$
Now I need to plug that into our first equation, but before I do that, I'm going to clear out the denominators in the first equations, so I multiply through by $2(xy-4)$ to give us $$8x^2y^2+2x(xy-4)=xy$$
Again at this step I can divide through by an $x$, giving us
$$8xy^2+2xy-8=y$$
Now, we plug in what we have $y$ for in terms of x, giving us $$8x(\frac {12x^2} {4x^2 +12 -3x})^2+2x(\frac {12x^2} {4x^2 +12 -3x})-8=\frac {12x^2} {4x^2 +12 -3x}$$
Continuing our theme of not dealing with fractions, we're going to multipy through by $(4x^2-12x-3)^2$ to get
$$8x(12x^2)^2+24x^3(4x^2-12x-3)-8(4x^2-12x-3)^2=12x^2(4x^2-12x-3) $$
Multiply this out and we have $$1152x^5+96x^5-288x^4-72x^3-128x^4+768x^3-960x^2-576x-72=48x^4-144x^3-36x^2$$  Moving everything to the left hand side and combining powers of $x$, we have $$1248x^5-464x^4+840x^3-924x^2-582x-72=0$$
The only simplification that can be done here is dividing by 2, which still gives us a quintic,  which has no easy way to solve.  Wolframalpha shows is now showing 3 real solutions, none of which match
Comment: I'm sure there is a mistake somewhere in your calculation.  There are five possible real solutions to this system of equations (I have checked with Mathematica).  However, none of the real solutions are nice.  If $a:=\frac{1}{x}$, then $114a^5-72a^4-288a^3+156a^2+119a-60=0$.
Comment: my question had typo, should be $\frac {1} {x+y}$ etc, not $xy$..
Comment: II changed the equation.
Answer: Let $x=1/p$, $y=1/q$, and $z=1/r$.  The three equations become
$$\begin{align}
{1\over2}&=p+{qr\over q+r}={s\over q+r}\\
{1\over3}&=q+{rp\over r+p}={s\over r+p}\\
{1\over4}&=r+{pq\over p+q}={s\over p+q}\\
\end{align}$$
where
$$s=pq+qr+rp$$
Thus
$$\begin{align}
2s&=q+r\\
3s&=r+p\\
4s&=p+q\\
\end{align}$$
From this it follows that
$$(q+r)+(p+q)=2(r+p)\implies2q=r+p=3s\implies q={3\over2}s$$
and the others follow:
$$r=2s-q={1\over2}s\quad\text{and}\quad p=4s-q={5\over2}s$$
But now we have
$$s=pq+qr+rp={15\over4}s^2+{3\over4}s^2+{5\over4}s^2={23\over4}s^2$$
hence $s=4/23$, so $p=10/23$, and thus $x=23/10$.
Answer: multiplying (2) by $x$ $(x \ne 0)$ we obtain
$$\frac{1}{z}=\frac{1}{4}-\frac{1}{xy}$$
with (3) we obtain $$y=\frac{12(x^2-1)}{4x^2-3x}$$ (I)
from (1) and (3) we get
$$\frac{x^2y}{3}-x^2+1=\frac{xy}{4}$$
plugging (I) in this equation  and simplifying we get
$$-60 x^5+119 x^4+156 x^3-288 x^2-72 x+144=0$$
with five real solutions, no of them from (A) to (E)
the system after the correction has the solution $$x=\frac{23}{10}$$
Comment: my question had typo, should be $\frac {1} {x+y}$ etc, not $xy$.. sorry
Comment: hm it was also my time when I have solved your problem with the typo
Comment: and now i'm waiting for the downvoters of me
Answer: Choosing
$p = \frac{1}{x} $
$q = \frac{1}{y}  $
$r = \frac{1}{z} $
will certainly help writing the equations more neatly, I guess.
Then your equations can be written as:
$$2p + 2qr = 1 \\ 3q + 3pr = 1 \\ 4r + 4pq = 1$$
using first two equations you get:
$$ 2p + 2qr = 3q + 3pr \\ \implies r = \frac{3q - 2p}{3p - 2q}$$
Substitute in equations and solve as solved by Alan above.


JQuery script twice running in twig

Question: I use twig for my templates. when I load jquery script in {% js_block %} it will be loading twice and i don't know why? But when i move my script out of {% js_block %} it's work right.  what is the problem?
{% extends 'layout/base.html.twig' %}
{% block js_block %}

{% endblock %}

Solution: I find the problem.  I was loaded {% js_block %} into {% body_block %}:
{% extends 'layout/base.html.twig' %}
{% block body_block %}
//HTML CODES
{% block js_block %}

{% endblock %}
{% endblock %}

The solution is:
{% extends 'layout/base.html.twig' %}
{% block body_block %}
//HTML CODES
{% endblock %}
{% block js_block %}

{% endblock %}

Comment: It's most likely that your script is being run twice. Add some logging so you can see what it's doing.
Comment: So what is the issue with this? Is it not sending your mail? You aren't checking your `$mail->send()` which could've thrown an error - `if(!$mail->send()){  echo $mail->ErrorInfo; }`
Comment: @Darren I've looked at the results, but still email will be sent twice.
Comment: @ahmed @jilykate @Darren By using `$(".person-reset-pass").unbind('click');` solved my problem. But don't trigger click event somewhere. I just use bootstrap.
Answer: It seems like you call the script by ajax or inside a callback function.
Run the script so the 'click' function run once, not more.
Each time you use the click function on the same element, it repeats the event listener.
I advice you to select using "ID" instead of "class".
Comment: By using $(".person-reset-pass").unbind('click'); solved my problem. But don't trigger click event somewhere. I just use bootstrap.
Answer: I bet you trigger this 'click' event somewhere.
Comment: By using $(".person-reset-pass").unbind('click'); solved my problem. But don't trigger click event somewhere. I just use bootstrap.

JQuery script twice running in twig


SharePoint - standard version enough for simple forms?

Question: I'm trying to figure out winch version of SharePoint (and CAL) I need. I haven't even used SharePoint yet - so please bear with me here.
From what I've read - the price jumps substantially from Standard to Enterprise CALs, while the server license is nearly the same.
What I need to accomplish (or well, what the CEO wants me to accomplish) is:

Overtime form
Sick leave form
Any future form we might need

We're also going to host all employee-handbooks (rules, instructions, etc) on SharePoint, and need to force users to receive an email when the documents get updated
Do I get these features with SharePoint Standard? How do I get the forms designed? From what I've read I'll need an enterprise CAL and server to be able to upload forms from InfoPath to SharePoint. Can I buy externally designed forms from someone and use them on Standard edition?
Comment: Closing as OT - We now have a really great [Stack Exchange site dedicated to Sharepoint](http://sharepoint.stackexchange.com/) which didn't exist back when this question was born :)
Answer: InfoPath Forms hosting is an Enterprise feature so you'd need that edition if you're set in using InfoPath.
Depending on exactly what you want to do within these forms could it not be an option to just use simple Word based forms wrapped up with some kind of workflow to manage the process?
Alerts on document library changes are available in Standard edition (& maybe Foundation services) although I think you may need to do some PowerShell to subscribe people to it automatically if you don't want to leave them to do it manually.
Answer: The easiest implementation of complex forms is with InfoPath. To use InfoPath forms with SharePoint Server, you need InfoPath Forms Services. This service is only available in the Enterprise version.
Here's a feature comparison:
http://sharepoint.microsoft.com/en-us/buy/Pages/Editions-Comparison.aspx
I'm not familiar with using external forms. You can have a document library with any sort of file you want, but I don't think you'll get integration with external forms. SharePoint is mostly focused on integrating Microsoft Office products into a website.


Panels selection rule node author

Question: I was wondering, I have a panels using the "Node template", is there a way to have "node author" as a selection rule, now I only have "node type".
I'm using Drupal 7.9.
Answer: Under the "Contexts" tab for your page variant, add a relationship to Node:author.  This will expose the available fields from the author for your use.
However, What are you trying to do?  You might be better off to define what you want in Views and then set up a node page variant to display the view for you.
Answer: Just an fyi, in case you are attempting to override the node edit form using panels, and selection rules, you may have to use the dev version of ctools. I was banging my head against the wall for a while trying to figure out why certain selection rules where not displaying. Once i replaced ctools with the dev version, everything worked fine

Panels selection rule node author


Substitution variable in Essbase script

Question: I´m trying use a substitution variable for parametrize my private Key. I have created the substituion variable with the name 'privateKey'.
RUNJAVA com.hyperion.calcmgr.common.cdf.MaxLScriptFunction
"-D"
"123456.1234567" /* Private key */
""
"login $key 944589711255867592121610891 $key 944589711255867592121610891 on 'localhost'"
"alter database 'MIS'.'Analytic'
clear data in region
'{
.....
} ' physical "
"logout"
"spool off"
"exit";

I have tried change in the script for $privateKey but doesn´t work.
RUNJAVA com.hyperion.calcmgr.common.cdf.MaxLScriptFunction
    "-D"
    "$privateKey" /* Private key */
    ""
    "login $key 944589711255867592121610891 $key 944589711255867592121610891 on 'localhost'"
    "alter database 'MIS'.'Analytic'
    clear data in region
    '{
    .....
    } ' physical "
    "logout"
    "spool off"
    "exit";

Can someone help me ?
Thanks in advance
Greetings
Answer: Hi Laggc – I don't recommend this approach, but if you want to refer to a substitution variable in a MaxL script, you need to use an ampersand. The dollar sign is used fro MaxL variables as well as the special $key "meta-variable". So you would need to use &privateKey% instead of $privateKey.

Substitution variable in Essbase script


Calculus 2 question

Question: Consider the function $y = x^2$
Estimate the distance along this curve from $x = 0$ to $x = 2$ using
straight line distances on the intervals $[0, 1]$ and $[1, 2]$.
Is this question asking me to calculate approximating area?
Comment: No, it's asking you to approximate distance, not area.  My guess is that this is a lead-in to arc length.
Comment: What work have you done so far?
Answer: Welcome to MSE. You're being asked to approximate arc length, not area. The length of those two segments will be an approximation for the actual arclength of $y = x^2$ from $x = 0$ to $x = 1$.
Visually, you're using the two black segments $AB$ and $BC$ as a stand-in for the green parabola between $A$ and $C$.

Calculus 2 question


Bulk update for unchecked "Generate automatic URL alias"

Question: I have a lot of programmatically generated nodes with the option "Generate automatic URL alias" unchecked, so i can't use the Bulk Update of the pathauto module.
How can i to bulk generate the pathauto alias for these nodes?
Edit: i use Drupal 7
Answer: VBO doesn't have an option to change the status of 'Generate automatic URL alias'
You could execute the following mysql query:
UPDATE `pathauto_state` SET `pathauto`=1 WHERE `entity_type` = 'node'

Or if you want to update just exact content type only:
UPDATE  `pathauto_state` p, `node` n SET `pathauto` = 1 WHERE
p.entity_id = n.nid and n.type = 'mycustontype'

where 'mycustomtype' is a machine name of the content type.
Or if you have drush installed:
drush sqlq "UPDATE pathauto_state SET pathauto=1 WHERE entity_type = 'node'"

After that you can bulk generate the new paths as you would normaly do on:
admin/config/search/path/update_bulk
Comment: Thank you! This is the correct answer. Using VBO doesn't work to update path alias unless path alias is already selected.
Answer: Have you tried using Views Bulk Operation. All you will need to do is create a view that will list all the nodes that will meet your criteria and then assign an action 'Generate Url alias' (I haven't tried it though.)
Comment: This method does not work if the 'generate url alias' option in not enabled on the existing node's node edit form.  Which seems to make VBO useless in the situation that you have a lot of existing nodes for which the 'generate url alias' option was not enabled.
Comment: This isn't the correct answer for the reasons Benjen explained. I'm having the same problem.
Comment: Agreed it won't work for entities with Generate URL Alias unchecked. To work around this, you'll need to manually update the table that tracks that checkbox's state with sql. In latest D7 `pathauto 7.x-1.3`, that's `pathauto_state`. Two examples are below: One is for updating existing records, the other is for inserting new records where they don't yet exist.
Answer: In addition to Rick B's answer, you will also need to create entries for the nodes that have never had that checked. That can be accomplished running this query:
INSERT INTO pathauto_state
SELECT 'node',n.nid ,1
FROM node n
WHERE n.type = 'api'
AND n.nid NOT IN (SELECT entity_id FROM pathauto_state)

which can be run either using drush on directly on the database as Rick described.
For taxonomy terms, determine your term's vocabulary id (3 in the example below) and do a similar insert:
INSERT INTO pathauto_state
SELECT 'taxonomy_term', t.tid, 1
FROM taxonomy_term_data t
WHERE t.vid = 3
AND t.tid NOT IN (SELECT entity_id FROM pathauto_state)

Answer: I can verify this works with Views Bulk Operations (VBO).
Just tried what Gokul N K mentioned because I ran into the same problem and I can verify it still works with actual module versions.
I had existing taxonomy terms with unchecked "Generate automatic URL alias" and I wanted to update them in bulk.
My setup below:
Drupal 7 (7.34) with Views (7.x-3.8), Pathauto (7.x-1.2) & VBO (7.x-3.2). I assume the modules present / installed configured.

deleted all taxonomy term aliases /admin/config/search/path/delete_bulk
created a new view under /admin/structure/views and selected (Show) Taxonomy terms (in my case I selected all for all vocabularies, you could choose a certain vocab only)
select "fields" under "Display format", make more adjustements if necessary, then "Continue & edit"
Under fields, hit "add" and search for "Bulk operations: Taxonomy term", check and apply
then check "Update taxonomy term alias" and apply
Save your view and head to the views location and bulk update all taxonomy term path aliases
Answer: For those of you that need this to be in php form for using in a module/theme/etc really quick:
<?php
$update_auto_aliases = db_update('pathauto_state')
  ->fields(array(
    'pathauto' => 1,
  ))
  ->condition('entity_type', 'node', '=')
  ->execute();
?>

Answer: In my case (for Drupal10 ) bulk update was not generating aliases due to the fact that all the nodes (when you edit a node) had unchecked the checkbox "generate automatic alias". I have found a quick workaround (which I recommend when you have less than a few hundreds nodes). Go to /admin/content  and from there select the nodes to be updated and make sure to select "Update Url alias" in the action dropdown (below the filters) and then click "Apply to selected items".
Answer: You need to delete the aliases for those previously created nodes before assigning them new aliases. This post explains how to do that.
Comment: I am using Drupal 7, not 5 or 6.
Anyway in Drupal 7 the content of the link can be done from admin panel selecting a proper configuration.
I am trying to bulk assign an alias to nodes that have the option "Generate automatic URL alias" unchecked
Answer: I think this can be done with Drupal 8 and VBO (at least it worked for me) - using the "Modify field values" action - because "Generate automatic URL alias" is just a field automatically provided for each item of content. The caveat is that you'll have to do it for each content type, but this can all be done on the same form as follows :-

Select the items in the VBO listing required (or Select all)
Choose the "Modify field values" action
Click "Apply to selected items" button
Expand each content type you want to apply this to and tick the "URL Alias" checkbox. The expanded form should then show a "Generate automatic URL alias" checkbox. This defaults to ticked so you don't have to do/change anything. Don't press the Submit button yet...
After doing step #4 for each content type press the submit button.

I didn't get a confirmation message afterwards (which is disconcerting - probably a bug in the excellent VBO module) but it did work for me (presumably in the background batch job).
Comment: The question was tagged for Drupal 7.
Also, it was 7 years ago and it was legit to use Drupal 7


Key/Value pairs separated in the markup. Is there any other way for better SEO?

Question: Theres a section in a site that I'm building that has some informations separated into two columns. The left column has the "keys" (don't know how else to call it, sorry) and the right column has the values, as seen below:

Floating the inner divs and aplying some other styles, I can achieve that exact result using something like this:

Size

etc...

10MB

etc...

But since each key is completely separated from its value, the markup doesn't seem to be search engine friendly at all. Is there any other way of doing that, maintaining the centered style and having the markup be more semantic?
Thanks for the help,
Daniel.
Comment: Any reason you aren't using a table for tabular data?
Comment: @mrtsherman: Since the motivation is SEO related, I'd assume that's why. Isn't there some SEO paranoia about tables because they require too much markup and not enough keywords?
Comment: @Madmartigan - I try not to listen to SEO paranoia too much. My marketing guys would have me spend as much time rejiggering my markup as developing a functional website because they read somewhere it helps SEO.
Comment: This definitely calls for a TABLE tag.
Answer: You can certainly use tables for this data, it would probably be appropriate. Another option you might use is a description list:

Size

2.63 MB

Views

34,412

Downloads

2,125

Likes

1.368

Category

Test

Add some CSS...
dt, dd {
    font-family:sans-serif;
}
dt {
   float:left;
   clear:left;
   text-align:right;
   width:50%;
   color:#bbb;
}
dd {
   float:left;
   margin-left:3em;
   color:#999
}

And there you have it. http://jsfiddle.net/FuaNk/
I can't comment on whether or not this helps SEO, but the values are adjacent to the keys, which seems to fit your requirements.
More info on
, formerly known as the "definition list":

http://html5doctor.com/the-dl-element/
http://dev.w3.org/html5/markup/dl.html
Comment: Thanks! It seems to make much more sense this way.


PySpark filter a list of element and then merge back

Question: My rdd contains pair of IDs and a list of items. for example, each item will be like (1, [a, b, c]). I need to apply a filter to this item. Let say I don't want an on the list.
My current approach is to use flatMapValues to break the items into key-value pairs. filter them and use groupByKey to merge them back into (1, [b, c]).
After I did some research and seems like groupByKey is terrible when data is huge. Also, seems like I'm breaking down the list, and them merging it back after the list might seems redundant. Is there a way to accomplish this without break the array down and merge it back?
Answer: You can use a list comprehension with mapValues:
rdd2 = rdd1.mapValues(lambda l: [i for i in l if i != 'a'])


How to make a jenkins call to retrieve the job details every 'X' minutes in meteor?

Question: What I'm up to is to get the jenkins job details and store it in mongo DB every "X" minutes. I have to make an HTTP.call(JenkinsURL) which I know how to do. My problem is calling it for specific intervals.
buildDetails=HTTP.call('GET',buildURL);

buildURL has the Jenkins job URL. I found this link which gives an overview of the code for my problem, but I don't know how and where i should place these code to get it working. I tried all possibility.
Is there any method in meteor which can make this possible to run a specific code to be run for every X min??
Comment: *I tried all possibilities* - Do explain. You can use ```Meteor.setInterval()``` to run something every X interval of time.
Comment: I mean that i have tried all the combination of the code in the link which i have specified. I tried the Meteor.setInterval(), it works as it defined, but when i refresh and navigate to other page it will stop executing the interval() code.
Comment: That would be because you're calling it from the client. Is there any specific reason to do it from the client? Normally, for your use case, it should be called from the server don't you think?
Comment: I'm not calling it from client, i want to run those set of commands from server and should be running on backgroud..
Answer: Is there any method in meteor which can make this possible to run a specific code to be run for every X min??
Yes, there is.
Meteor.setInterval that can be used to do something repetitively every X interval of time.
You can put your HTTP call within it on the server. Eg:
Meteor.startup({function(){

    var timerID = Meteor.setInterval(function(){
                     buildDetails=HTTP.call('GET',buildURL);
                     // and other things
                     }, 60000) //60000ms = 1 min
                 }
});

When you want to stop the timer function, simply call Meteor.clearInterval
Meteor.clearInterval(timerID);

Comment: getting error like= "unexpected , expected , "  at the  Meteor.setInterval(getAndStore(){
Comment: My bad. I had the wrong syntax for ```getAndStore()```. It should just be a ```function```. I've fixed it. Also, this is meant to work exactly like you want it to. I'm not sure why you a page refresh makes this to stop working. It should ideally continue to work until the application is shut down, or you explicitly call ```clearInterval```
Comment: Tq, it's working as i expected, but the problem is that when other server side code(helpers,events and other function) executes, getAndStore() will wait till other executes and if i have more number of HTTP.call() the interval will start from initial count. Is there any other way to make it run in background like thread? pls provide any reference if u know..
Comment: helpers and events are not server side code. You can try wrap the ```setInterval``` within```meteor.onStartup()```  and possible place it in ```/server/lib/``` so that it runs as soon as the app is running.
Comment: ohh..sry i know helpers and events on client side, i mean other meteor.methods() functions. And is there any way we can run this code in seperate thread like in other programming languages?


Panels on the front page get invalid $user variable

Question: I have a Drupal 7 wite where the front page is a Panel. In one of its tiles I have a custom PHP code that prints out the value of `$user->name'. Now the problem is that it usually prints out a different user's name.
Cacheing and memcache is now switched off. Do you have any idea what might cause this problem..?
Comment: Is there any caching on the panel or the panel pane set? Have you added the User as a context to the Panel? Do you use keyword substitution for "$user->name"?
Answer: Ok, got is. Panels have its own caching that was switched on.
Comment: You don't have to turn the caching off, as Pontus says, just change it to be by context and ensure the user is part of the context.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.


Resource interpreted as Script but transferred with MIME type text/html javascript

Question: I got a problem with including AngularJS/javascript into my html document. Every time i load my index.html i got this error:
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/assets/angular/1.2.9/angular-route.js". index.html:17
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/assets/angular/1.2.9/angular.js".

This are my script tags:

What i have tried so far:
Include <?php Header("Content-Type: application/x-javascript; charset=UTF-8"); ?>,
Defining that the script tag text/javascript is or application/javascript
I hope that you guys can help me with this problem.
Answer: Try putting type="text/javascript" in your script tags
Comment: The only other thing I can think of is checking that the script files actually contain the intended javascript and not other content. Try it against the Angualr cdn to rule out issues with the local files.


Why is this margin of error problem wrong?

Question:
$M.OE = (2.75)*(2.7)/\sqrt{n}\;$?
Comment: Where did you get $2.75$ from?
Comment: z = 2.575 (the area corresponding to 99% confidence interval assuming normal distribution )
Comment: So then it would be z=2.199? but that is also wrong.
Comment: You should be using a t-distribution when the sample size is small and the population standard deviation is not known.
Comment: And you should be dividing by $\sqrt n$ as you sample size gets larger your margin of error gets smaller.
Comment: @DougM could you please show how to get the t-distribution? Would the rest be the same and multiplied by the t-distribution
Comment: I meant to put a division sign in there
Comment: Is the answer 2.775?
Comment: @MathewMahindaratne yes
Answer: $t = \frac {\mu - \bar x}{s/\sqrt n}$
$\mu - \bar x$ is the margin of error. (true mean - sample mean)
$s$ is the sample standard deviation.
Then you look up on a table or use a statistical calculator to find the range of t for your confidence interval, and the "degrees of freedom" $(n-1)$ and as either a $1$ tail or $2$ tailed test.
$99$% and $9$ degrees of freedom and $2$-tailed test give
$|t|<3.25$
$|\mu - \bar x| < \frac {3.25 \cdot 2.7}{\sqrt {10}} = 2.77$
Comment: The answer needs to be rounded to $3$ decimal points, so it should be $2.775$ instead. :-)
Comment: 3 decimal points of accuracy on the margin of error that is 3 points wide? (and an initial estimate with 1 decimal pt of accuracy)  That false precision!  But yes, 2.775 would be the correct expansion.
Comment: Doug M: True, but question is asked to give the answer with $3$ decimals (please read the last sentence of the question).
Answer: As a rule of thumb, when $n\leq30$ we should use a $t$-distribution rather than a normal distribution.
With a $t$ distribution our confidence interval is given by
$$\bar{X}\pm t \frac{s}{\sqrt{n}}$$
with degrees of freedom $$df=n-1$$
I leave it to you to find the necessary $t$ value using a $t$-table.


pygame image background does not match main background

Question: I have an image with a transparent background. When I blit the image on to the background of my game the transparent background appears on the screen (see image below)

here is my code:
import sys
import pygame

def runGame():
    """ Function for running pygame """

    pygame.init()
    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Car Simulator")
    image = pygame.image.load('./car1.bmp').convert()

    bg_color = (230,230,230)

    # Start main loop for the game
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.blit(image, (50,100))

        pygame.display.flip()

runGame()

At first I thought it was because I was not using the convert() method. However I'm still having the same issue. Any ideas on how I can get the background of the image to match the background of the screen. Any help would be appreciated. Thank you.
Answer: If the background has a uniform color, then you can set the transparent colorkey by pygame.Surface.set_colorkey. For instance if the background is the white (255, 255, 255):
image = pygame.image.load('./car1.bmp').convert()
image.set_colorkey((255, 255, 255))

Anyway that won't solve the issue if the background has multiple colors.
I recommend to use an image format which supports per pixel alpha. For instance PNG (Portable Network Graphics):
image = pygame.image.load('./car1.png').convert_alpha()

See also How can I make an Image with a transparent Backround in Pygame?


Closed form of Euler-type sum over zeta functions $\sum _{k=2}^{\infty } \frac{\zeta (k)}{k^2}$?

Question: Revisiting the question on the integral over the harmonic number I stumbled over the nice formula
$$\sum_{k\ge2} (-1)^{k+1}\frac{\zeta(k)}{k} = \gamma\tag{1}$$
where $\zeta(z)$ is the Riemann zeta function and $\gamma$ is Euler's gamma.
Searching SE I found solutions to related but even more complicated problems (see below) so I dropped $(1)$ and propose here instead the problem asked in the heading, viz. to find a closed expression for
$$s=\sum_{k\ge2} \frac{\zeta(k)}{k^2} \simeq  0.835998  \tag{2}$$
I tried several approaches but still couldn't find a closed expression. So I would consider this a tough sum.
More generally we can ask for sums of the form
$$s_q=\sum_{k\ge2} \frac{\zeta(k)}{k^q}   \tag{3}$$
A similar tough sums is
$$s_{-1}=\sum_{k\ge2} \frac{\zeta(k)}{k(k-1)} = ?  \tag{4}$$
Whereas for sums of the type $\sum_{k\ge2} \frac{\zeta(k)}{k(k+1)}$, $\sum_{k\ge2} \frac{\zeta(k)}{k(k+1)(k+2)}$, or generally
$$s_{p(m)}=\sum_{k\ge2} \frac{\zeta(k)}{(k)_m}=\text{closed expression}  \tag{5}$$
where $(k)_m=k(k+1)(k+2)\ldots (k+m-1)$ is the Pochhammer symbol, closed expressions for any integer $m\ge2$ can be found using CAS (e.g. Mathematica).
My effort so far
Because of the length of these developments I have put them into a (preliminary) self answer.
Related problems
[1] A Tough Series $\sum_{k=1}^\infty \frac{\zeta(2k+1)-1}{k+1}=-\gamma+\log(2)$
[2] Closed form for a zeta series :$\sum^\infty_{k=2}\frac{(-1)^{k-1}\zeta(k)}{(k+2)2^{k+2}}$
Comment: Since

$$\sum_{k\geq 2}\zeta(k)\frac{x^k}{k} = -\gamma x+\log\Gamma(1-x) $$
we have
$$\sum_{k\geq 2}\frac{\zeta(k)}{k^2}=-\gamma+\int_{0}^{1}\frac{\log\Gamma(1-x)}{x}\,dx\stackrel{\text{IBP}}{=}-\gamma+\int_{0}^{1}\psi(x)\log(1-x)\,dx $$ so it might be useful to have closed forms for $$\int_{0}^{1}x^m \psi(x)\,dx.$$
Comment: @Jack D'Aurizio I've thought about that, but the integral is even more complicated (see my answer (A.3)).
Answer: This is a preliminary incomplete answer showing my effort to solve the problem.
What I did so far to find a closed expression to $(2)$ is mainly a reformulation. Maybe someone recognises one of these expressions.
It turned out that different approaches sometimes lead to the same result. I have therefore indicated "really" different formulas by putting them in a box.
0) Just be reassured not to miss trivial things I consulted the online-encyclopedia of integer sequences with the first few digits of $N(s)$.
Nothing relevant was found but the first 5 digits appear somewhere in several funny numbers, like https://oeis.org/A019694, Decimal expansion of 2*Pi/5.
1) Expanding zeta in a series and changing the order of summation, leaves another sum
$$s=\sum _{k=2}^{\infty } \frac{\zeta (k)}{k^2}=\sum _{k=1}^{\infty } \frac{1}{k^2}\sum _{m=1}^{\infty } \frac{1}{m^k}
\\
=\sum _{m=1}^{\infty } \left(\sum _{k=2}^{\infty } \frac{1}{k^2 m^k}\right)
\\
\boxed{s=\sum _{m=1}^{\infty } \left(\operatorname{Li}_2\left(\frac{1}{m}\right)-\frac{1}{m}\right)}\tag{A.1}$$
2) Replacing inverse power $\frac{1}{k^2}$ by an integral and doing the sum, leaves a nice compact integral
In fact,
$$\int_0^1 x^{k-1} \log \left(\frac{1}{x}\right) \, dx=\frac{1}{k^2}\tag{A.2.1}$$
and using the Taylor expansion of the harmonic number
$$\sum _{k=2}^{\infty } x^{k-1} \zeta (k)=-H_{-x}\tag{A.2.2}$$
we have
$$s=\sum _{k=2}^{\infty } \zeta (k) \int_0^1 x^{k-1} \log \left(\frac{1}{x}\right) \, dx
\\
=\int_0^1 \log \left(\frac{1}{x}\right) \sum _{k=2}^{\infty } x^{k-1} \zeta (k) \, dx=\int_0^1 \left(-H_{-x}\right) \log \left(\frac{1}{x}\right) \, dx
\\
\boxed{s=\int_0^1 H_{-x} \log (x) \, dx}\tag{A.2.3}$$
3) Exploring the integral $\int_0^1 H_{-x} \log (x) \, dx$
EDIT 06.03.20 begin
Using the basic relation $H_n=H_{n-1}+\frac{1}{n}$ and letting $n=1-x$ we can replace $H_{-x} \to H_{1-x} -\frac{1}{1-x}$ which, observing $\int_0^1\frac{\log(x)}{1-x}\,dx = -\zeta(2)$, leads to the possibly more pleasant form
$$s = \zeta(2) + \int_0^1 \log(1-x) H_{x}\,dx\tag{A.3.0}$$
EDIT end
Integrating by parts, $\int H_{-x} \, dx=\gamma  x-\text{log$\Gamma $}(1-x)$, gives
$$s=\int_0^1 H_{-x} \log (x) \, dx=\int_0^1 \frac{(\operatorname{\log\Gamma}(1-x)-x\gamma) }{x} \, dx\tag{A.3}$$
Here it might appear helpful to have the generating integral
$$s(\xi)=\int_0^1 x^\xi H_{-x} \, dx\tag{A.3.1}$$
so that we can generate the $\log$ by the derivative with respect to $\xi$.
But that integral is divergent at $x=1$.
3a) Inserting the definition of $H$ as an integral leaves another integral
$$s=\int_0^1 \left(\int_0^1 \frac{\left(1-z^{-x}\right) \log (x)}{1-z} \, dz\right) \, dx
\\
=\int_0^1 \left(\int_0^1 \frac{\left(1-z^{-x}\right) \log (x)}{1-z} \, dx\right) \, dz
\\
=\int_0^1 \frac{-\log (z)+\log (\log (z))+\Gamma (0,\log (z))+\gamma }{\log (z)-z \log (z)} \, dz
\\
\boxed{s=\int_0^{\infty } \frac{t+\log (-t)+\Gamma (0,-t)+\gamma }{t \left(1-e^{t}\right)} \, dt}\tag{A.3.2}$$
3b) Inserting the definition of $H$ as an infinite sum, leaves another infinite sum
$$s=\int_0^1 \log (x) \sum _{m=1}^{\infty } \left(\frac{1}{m}-\frac{1}{m-x}\right) \, dx
\\
=\sum _{m=1}^{\infty } \int_0^1 \left(\frac{1}{m}-\frac{1}{m-x}\right) \log (x) \, dx=\sum _{m=1}^{\infty } c(m)\tag{A.3.3}$$
with
$$c(1)=\frac{1}{6} \left(\pi ^2-6\right)\tag{A.3.4}$$
and
$$c(m\gt1)=\int_0^1 \left(\frac{1}{m}-\frac{1}{m-x}\right) \log (x) \, dx
\\
=-\operatorname{Li}_2\left(\frac{m-1}{m}\right)-\frac{1}{m}-\log ^2(m)+\log (m-1) \log (m)+\frac{\pi ^2}{6}\tag{A.3.5}$$
This can be simplified appreciable using the transformation formula
$$\text{Li}_2\left(\frac{m-1}{m}\right)=-\text{Li}_2\left(\frac{1}{m}\right)-\log \left(\frac{1}{m}\right) \log \left(\frac{m-1}{m}\right)+\frac{\pi ^2}{6}$$
to give
$$c(m) = \text{Li}_2\left(\frac{1}{m}\right)-\frac{1}{m}$$
so that we have found a complicated way to regain exactly $(A.1)$.
4) Replace zeta by an integral, leaves another integral
We have
$$\zeta (k)=\frac{1}{\Gamma (k)}\int_0^{\infty } \frac{t^{k-1}}{e^t-1} \, dt\tag{A.4.1},$$
so that our sum becomes
$$s=\sum_{k\ge2} \frac{1}{k^2}\frac{1}{\Gamma (k)}\int_0^{\infty } \frac{t^{k-1}}{e^t-1} \, dt=\int_0^{\infty } \frac{1}{e^t-1}\left( \sum_{k\ge2}\frac{1}{k^2}\frac{t^{k-1}}{\Gamma (k)}\right)\, dt
\\
=\int_0^{\infty } \frac{-\log (-t)-\Gamma (0,-t)-e^t \Gamma (2,t)-\gamma +1}{t \left(e^t-1\right)} \, dt\tag{A.4.2}$$
We can simplify the integrand.
The incomplete gamma function is defined as
$$\Gamma (r,y)=\int_y^{\infty }x^{r-1} \exp (-x)\, dx\tag{A.4.3}$$
This gives
$$\Gamma (2,t) =e^{-t} (t+1)\tag{A.4.3a} $$
and we can see (e.g. by plotting) that the combination
$$-\log (-t)-\Gamma (0,-t)\tag{A.4.3b}$$
is real for all real $t$. I don't know a name for this expression.
This gives finally
$$s = \int_0^{\infty } \frac{1}{t(1-e^t)} \left(t+\log (-t)+\Gamma (0,-t)+\gamma \right)\, dt\tag{A.4.4}$$
which coincides with the last formula of $(A.3.2)$.
5) Generating functions
Defining the generating functions analogous to $(3)$
$$g(q,z) =\sum_{k\ge2} \frac{z^k}{k^q}\zeta(k)\tag{A.5.1}$$
we have
$$g(0,z) = -z (\psi ^{(0)}(1-z)+\gamma ) = - z H_{-z}\tag{A.5.2}$$
and the sequence
$$g(q,z)=\int_{0}^z \frac{g(q-1,y)}{y}\,dy, q=1,2,\ldots \tag{A.5.3}$$
Giving
$$g(1,z)=\int_0^z H_{-y} \, dy=\gamma  z-\operatorname{\log\Gamma}(1-z)\tag{A.5.4}$$
and the g.f. we are looking for
$$g(2,z)=\gamma  z-\int_0^z \frac{1}{y}\operatorname{\log\Gamma}(1-y) \, dy=\text{?}\tag{A.5.5}$$
This one we have encountered already in $(A.3)$.
Notice that interestingly $\lim_{z\to -1} \, g(0,z)=1$ in spite of the fact, that the series diverges. In fact, there is no limit but two partial sums with even and odd parity tend to $\frac{1}{2}$ and $\frac{3}{2}$, respectively, i.e. the sequence has two accumulation points, and their arithmetic mean is $=1$.
6) Complex contour integral
I am not sure if this approach could lead to a closed expression but it might be interesting.
Representing the infinite series as a complex contour integral with the "kernel function" $H_{-z}$ and a path coming from $i+\infty$, going to $i+\frac{3}{2}$, to $-i+\frac{3}{2}$, and then back to $-i+\infty$, then bending the path around we arrive at the following representation of our sum $s$:
$$s=2-\gamma -\frac{1}{2 \pi }\int_{\frac{1}{2}-i\infty }^{\frac{1}{2}+i \infty } \frac{H_{-z} \zeta \left(z\right)}{z^2} \, dz\tag{6.1}$$
where the terms before the integral are the residue of the integrand at $z=1$:
$$\text{Res}\left(\frac{H_{-z} \zeta (z)}{z^2}\right)|_{z=1} =-2 + \gamma\tag{6.2}$$
Notice that the integral is taken on the critical strip where the zeta function has its non-trivial zeroes (if Riemann was right).


How would i change the colour dynamically depending on the width

Question: OK so I have a bar that depending on the percentage set will fill to that set percentage.
However how could i change this the have a transition of the colour depending on the percentage.
For example
0% to 25% red the slowly turn green as approaches 100%
HTML

CSS
.progress {
    width:200px;
    height:50px;
    border:1px solid black;
    position:relative;
}
.progress:after {
    content:'\A';
    position:absolute;
    background:black;
    top:0; bottom:0;
    left:0;
    width:90%;
    -webkit-animation: filler 2s ease-in-out;
    -moz-animation: filler 2s ease-in-out;
    animation: filler 2s ease-in-out;
}

@-webkit-keyframes filler {
    0% {
        width:0;
    }
}
@-moz-keyframes filler {
    0% {
        width:0;
    }
}
@keyframes filler {
    0% {
        width:0;
    }
}

any help on this will be fantastic, thanks you.
Comment: Javascript....CSS can't do that. You'll need JS anyway to change the percentage.
Answer: You could use linear-gradient here and animate :after pseudo-element to translate on X axis and gradually reveal parent element beneath with gradient.
Also animation-fill-mode: forwards is to keep :after to the right side once animation has finished.

.progress {
  width: 200px;
  height: 50px;
  border: 1px solid black;
  background: linear-gradient(to right, red 25%, green 100%);
  position: relative;
  overflow: hidden;
}
.progress:after {
  content: '\A';
 position: absolute;
  top: 0;
  bottom: 0;
  background: white;
  left: 0;
  width: 100%;
  -webkit-animation: filler 2s ease-in-out;
  -moz-animation: filler 2s ease-in-out;
  animation: filler 2s ease-in-out;
  animation-fill-mode: forwards;
}
@-webkit-keyframes filler {
  100% {
    transform: translateX(100%);
  }
}
@-moz-keyframes filler {
  100% {
    transform: translateX(100%);
  }
}
@keyframes filler {
  100% {
    transform: translateX(100%);
  }
}

Answer: You can do it with HTML5 progress element:
<progress></progress>

And you can give style like this:
progress[value] {
  //your style
}

You can find an example usage in this link.
Comment: Please clarify how this would change color **dynamically**. The link you provided does not seem to cover that....and **that** seems to be the requirement here.
Comment: I wanted to explain; if you firstly set colors by percentage of progress bar -which i gave a basic example above-, when you trigger its percentage (by changing progress width) with JS, you don't have to set color with JS anymore. You have to only control percentage by JS and then it automatically set the color (or another style variables).


Como usar um nome com colchete (parênteses retos) num selector de jQuery?

Question: Qual é a melhor maneira de chamar um elemento que tem parênteses retos no nome, usando jQuery?.
HTML

jQuery
$('div[name=name[1]]'); //errado?
$('div[name="name[1]"]'); //correto?
$('div[name="name\\[1\\]"]'); //correto?
$('div[name=name\\[1\\]]'); //correto?

Comment: Está divertido aprender o português aqui :) Colchete é parente recto.
Comment: @Sergio "parêntesis" e "parêntese" são sinónimos. Eu uso a grafia "recto" porque não escrevo conforme o desacordo ortográfico. Já agora, é "há" (do verbo "haver" e não "à", que é uma contracção de uma preposição com um artigo definido).
Comment: Agora fiquei na dúvida, parente recto não está correto (ou correcto :) ) em Portugal?
Comment: @bigown, acho que depois do acordo ortográfico do ano passado recto passou a reto... mas como estou a viver na suécia à 5 anos ainda falo o português "antigo" :)
Comment: "parêntesis recto"
Comment: @AlexandreCartaxo então deve ser com "i" em parêntes**i**s? e deve ser "reto" ou "recto"?
Comment: @AlexandreCartaxo ok :) um edit é bem-vindo!
Comment: @Sergio Não necessariamente. Conforme o AO90 está correcto.
Answer: O primeiro exemplo $('div[name=name[1]]'); está incorrecto, e dá o erro
unrecognized expression: div[name=name[1]].
As outras opções estão correctas, se bem que por razões ligeiramente diferentes.

Explicação:

$('div[name="name[1]"]') é ok de usar porque o jQuery trataname[1] como uma string, uma vez que está dentro de aspas, e não como um selector CSS/jQuery, e assim não precisa de ser blindado com o escape \\.
$('div[name="name\\[1\\]"]'), funciona, mas não precisa de \\. O jQuery lê o o selector name\\[1\\] como uma string pois está dentro de aspas, e no javascript a barra invertida faz com que a segunda barra seja ignorada\ resultando em \[, que por sua vêz é o mesmo que [. Assim este exemplo tem barras invertidas sem necessidade.
$('div[name=name\\[1\\]]') é ok e os parentes rectos internos [] têm de ser blindados com barras invertidas desse modo para não serem confundidos com selectores CSS/jQuery.

Da documentação do jQuery:

Para se usar qualquer um dos seguintes meta-caracteres !"#$%&'()*+,./:;<=>?@[]^`{|}~ como parte de um nome, têm de ser blindado com duas barras invertidas, barras à esquerda: \\.

Exemplo aqui

Mais leitura (em Inglês):

MDN - Escaping characters
jQuery - Selectors
W3.org - Characters


Glissando that ends on a flat

Question: I have a piece that is in two flats and has a glissando that starts on G and ends on a B quarter note two octaves higher.  Am I supposed to glissando on the white keys through A and then hit and hold the B flat at the end?
Comment: Really good question.
Answer: The glissando symbol, by default, means a white-key gliss, regardless of key signature.
There is a common piano technique by which you play a gliss with one hand and then strike the final note with the other. This has the added benefit of the final note being accented, which will also allow it to sustain more. Without any other contextual information being given, I would assume that that is what is being indicated by the music you have.
As jdarnel27 mentioned, black-key glisses are possible (pentatonic) as are chromatic glisses (using one finger on the white keys and the other on the black ones), but I would expect both of these to be explicitly notated as such.
Answer:
Am I supposed to glissando on the white keys through A and then hit
  and hold the B flat at the end?

I'm not a piano theory expert, but I would say yes.
Performing the glissando across the white keys gives you a major scale (more or less); this is the "sound" I typically associate with a glissando in music.
If you move across just the black keys, you are playing a pentatonic scale.  Unless the music explicitly says so, I doubt that is the sound you're going for.
Comment: @leftaroundabout I was being keyboard-specific because the question is tagged [piano].
Comment: With _keyboard_ glissandi you'd associate the white-key sounds. On most other instruments, a glissando restricted to the C-major scale would be ridiculous.

Glissando that ends on a flat


Showing column twice in a query, second time showing data post update/set

Question: For testing purposes I'm wondering if the following two selects could ever be combined:
begin transaction

select  x
from    example_table

update  example_table
set     x = 'new value'

select  x
from    example_table

rollback transaction

Essentially, I'd like to see a result output like:

Column Name, Updated Column Name
Answer: If I understand you correctly you can do in using OUTPUT clause (SQL Server 2005 +)
use tempdb
go

create table #tbl (i int)

insert into #tbl values (10),(20),(30),(40)

update #tbl
set i=i+1
output deleted.i i_old,inserted.i  i_updated

drop table #tbl

From Books OnLine

OUTPUT Clause returns information from, or expressions based on, each
  row affected by an INSERT, UPDATE, DELETE, or MERGE statement.

...

DELETED is a column prefix that specifies the value deleted by the
  update or delete operation. Columns prefixed with DELETED reflect the
  value before the UPDATE, DELETE, or MERGE statement is completed.

...

INSERTED is a column prefix that specifies the value added by the
  insert or update operation. Columns prefixed with INSERTED reflect the
  value after the UPDATE, INSERT, or MERGE statement is completed but
  before triggers are executed.

EDITED
begin transaction

update  example_table
set     x = 'new value'
output deleted.x old_value, inserted.x new_value

rollback transaction

Comment: @Michael That's what my example demonstrates. I create, populate with data and drop table just to give an example. Actually you need just `UPDATE...`
Comment: I'm unsure if I'm explaining myself properly. I'm actually updating a pre-existing table and want to show an output of the original value as well as the new value that I've changed it to.
Comment: I apologize but I'm a bit confused by this - could you do this again using the example in the original post?


How do you find the inflection point of this graph?

Question: The graph is this:
$$
\frac{(x+1)^3 - 4(x+1)^2 + 4(x+1)}{(x+1)^2 - 2(x+1) + 1}
$$
I know you can find second derivative and then solve for values that make it undefined or 0, but I was told apparently there is another faster way to get the inflection point. What is that method?
Comment: To begin with maybe put $x+1=u$ and then work with the simpler function of $u$ (remembering to "shift back" for the true $x$ coordinates).
Comment: Maybe you can simplify that expression before you try to take the second derivative.
Comment: I don't think there is a faster way to get a point of inflection other than finding the second derivative and its solution and checking for a sign change in its neighbourhood.
Answer: simplifying the given term we get $$\frac{(x-1)^2(x+1)}{x^2}$$
i think yes since the second and the third derivative is simple
Comment: Does this make finding inflection points easier? (If so how?)
Comment: @coffeemath To elaborate a little on how the doctor got this, notice that you can factor $x+1$ out of the numerator getting $(x+1)( [x+1]^2-4[x+1]+4)$ and the right-hand factor you can recognize as quadratic in $x+1$ which can be factored as $[x+1]^2 -4[x+1] + 4 = ([x+1]-2)^2$.  If this isn't easy to see, follow the comment above and switch to $x+1=u$ and then try doing this, and at the end switch back to $x+1$.
Comment: @coffeemath Also, now that the expression is simplified, taking derivatives is easier.  So ultimately you still compute two derivatives and set equal to $0$, etc.
Comment: @Addem Yes. So it still seems to remain tthat two derivatives are needed to be sure of inflections.
Comment: On the aftermath of seeing the techniques/solutions offered here, those mainly being either simplify the expression before differentiation, or substitute (x+1)=u, simplifying, then solving, I think it is pretty safe to assume that you must get the second derivative to solve it, but the way in which you get the second derivative can be made easier, which is probably what my friend meant, when he said "there is a faster way." Thanks for the help! I also feel dumb for not having thought of simplifying it or subbing x+1 as another variable. Guess I didn't put enough thought into it. Thanks again!
Answer: Let $$y=\frac{(x+1)^3 - 4(x+1)^2 + 4(x+1)}{(x+1)^2 - 2(x+1) + 1}$$
Then using the substitution, $u=x+1$, we obtain
$$y=\frac{u^3 - 4u^2 + 4u}{u^2 - 2u + 1}$$
This simplifies to $$y=\frac{u(u-2)^2}{(u-1)^2}$$
Differentiating with respect to $u$, we obtain
$$\frac{\partial y}{\partial u}=\frac{u^3-3u^2+4u-4}{(u-1)^3}$$
Since $$\frac{\partial u}{\partial x}=1$$
We have $$\frac{\partial y}{\partial x}=\frac{\partial y}{\partial u}\cdot\frac{\partial u}{\partial x}=\frac{\partial y}{\partial u}$$
Substituting back in $u=x+1$, we are left with
$$\frac{\partial y}{\partial x}=\frac{(x+1)^3-3(x+1)^2+4(x+1)-4}{x^3}$$
This simplifies to
$$\frac{\partial y}{\partial x}=\frac{(x^3+3x^2+3x+1)-(3x^2+6x+3)+(4x+4)-4}{x^3}=\frac{x^3+x-2}{x^3}$$
Computing the second derivative
$$\frac{\partial^2 y}{\partial x^2}=\frac{\partial}{\partial x}(1+\frac{1}{x^2}-\frac{2}{x^3})=-\frac{2}{x^3}+\frac{6}{x^4}=\frac{6-2x}{x^4}$$
A point of inflection will occur when $\frac{\partial y}{\partial x}=0$, solving for this we get $6-2x=0$ gives $x=3$
The sufficient condition for points of inflection require that either side of the neighbourhood of $x=3$ have different signs.
Checking in the neighbourhood of $x=3$ we obtain a positive value for $\frac{\partial^2 y}{\partial x^2}$ when $x=2$ and a negative value for $\frac{\partial^2 y}{\partial x^2}$ when $x=4$.
Therefore $x=3$ is a point of inflection.


Including omitted variables in intervention analysis with ARIMA

Question: I am wondering about omitted variables in the context of intervention analysis. In my research, I have a time series of price differences between two regional commodity markets as the dependent variable. Those price differences were possibly influenced by a political intervention. Is it sufficient to include a dummy variable, that would be 1 after the intervention, and 0 before the intervention, in an ARIMA model?
Obviously, the transportation costs between the regional markets in my example could also influence the price differences. If I would have time series about the transportation costs, how could I include them in the intervention analysis? Since feedback between transportation costs and price differences is likely, I think that I would need a VAR approach?
Comment: @gung, as per your encouragement, I replaced [tag:econometrics] with [tag:finance], although in this case it is not entirely clear cut. But I will try to ask the question on Meta tomorrow, I am curious about others' opinions.
Comment: @gung, I am curious in which cases it is advisable to add the [tag:econometrics] tag. Regardless of what the tag Wiki says, I think of the distinction of econometrics from the rest of statistics more in terms of models and techniques (such as structural models based on economic theory and instrumental variables estimation) rather than just the applications. Because on one hand one can do a "purely statistical" modelling of an applied economics problem, but on the other hand one can do something "typically econometric" (distinct from a typical statistical application).
Comment: @RichardHardy, that's a reasonable point. I added the tag here b/c of the subject matter to which the model will be applied (as you surmise). It seems to me that knowing something about a topic is relevant to modeling generally, & that the issues that will need to be taken into consideration in this specific case are issues economists would readily notice & be used to considering. You could raise the issue on meta.CV for discussion, if you'd like.
Comment: @gung, OK. Because I treat the tags [tag:macroeconomics] and [tag:finance] are more like you treated [tag:econometrics] here.
Comment: @RichardHardy, you could swap it out for one of those, if you think one is more appropriate. I don't doubt you are more savvy with these terms than I am.
Answer: Intervention Variables can be pulses (one-time effects) or level shifts/time/trends/seasonal pulses reflecting multi-period effects. Often the actual point of intervention can be different from the "known point" as there may have been either anticipation and/or lagged effects. I would not model the differences but rather model one price being predicted/affected by the other.
Comment: If I model one price being affected by the other, I unterstand that I would have feedback between the variables. Then a VAR model with the two prices and the intervention variable could be a suitable approach?
Comment: if you wished to predict there two series simultaneously ... yes
Comment: Would I also need to include possible fundamental influences on the commodity prices in such a VAR approach, or could there be reasons to not include them? I expect that the political intervention only effected the price differences between the markets, not the absolute level of the prices. Therefore, I initially thought that only variables affecting the price differences (e.g. transportation costs) would be of relevance for me. However, I now think that I require a larger model that also accounts for possible fundamental influences on the absolute level of prices.
Comment: definitely include fundamental influences in the model


Publicando app na Apple Store

Question: Ao enviar o app para a Apple Store, recebi o e-mail:

Missing Info.plist key - This app attempts to access privacy-sensitive
  data without a usage description. The app's Info.plist must contain an
  NSPhotoLibraryUsageDescription key with a string value explaining to
  the user how the app uses this data.

O que exatamente eu preciso fazer?
Obs: O app foi feito com Ionic e usa plugins para camera, firebase e clipboard
Comment: Quando voce cliccou em UPLOAD TO APP STORE, conclui todas as etapas com sucesso? Apareceu um checbox verde e escrito Pronto(ou algo do tipo) em baixo?
Comment: Verifica o email associada a conta de desenvolvedor que subiu o app, as vezes da problema e enviam um email avisando.
Comment: @NeuberOliveira Na mosca! Os e-mails estavam na caixa de spam. Só não entendi muito bem o que eles querem que eu faça. Veja: Missing Info.plist key - This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.
Answer: Verifica o email associada a conta de desenvolvedor que subiu o app, as vezes da problema e enviam um email avisando.

This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.

É bem autoexplicativo, você precisa adicionar no seu plist essa entrada NSPhotoLibraryUsageDescription, Isso é um texto que é exibido no alert que aparece quando pede alguma permissão, no seu caso é permissão para acessar o galeria de fotos.
<key>NSPhotoLibraryUsageDescription</key>
<string>Explica aqui o por que você esta pedindo essa permissão, e o que vai fazer com as fotos</string>

Publicando app na Apple Store


How to solve for positive relatively prime numbers?

Question: When finding the relative prime for large numbers like 360 (that has a prime factorization with multiples of the same prime factor), how would it be solved?
ie. How many numbers between 1 and 360 are relatively prime to 360?
I would think either

N = 360 [prime factorization: 2, 2, 2, 5, 9]
$N(A_1) = \frac{360}{2}$
$N(A_2) = \frac{360}{5}$
$N(A_3) = \frac{360}{9}$
$N(A_1 \cup A_2) = ...$
$N(A_1 \cup A_3) = ...$
$N(A_2 \cup A_3) = ...$

...
or

N = 360 [prime factorization: 2, 2, 2, 5, 9]
$N(A_1) = \frac{360}{2}$
$N(A_2) = \frac{360}{2}$
$N(A_3) = \frac{360}{2}$
$N(A_4) = \frac{360}{5}$
$N(A_5) = \frac{360}{9}$
$N(A_1 \cup A_2) = ...$

...
Comment: How many natural number less than $n$ that  are relatively prime to $n$  = $\phi(n)$.  $\phi(n)$ is called Euler's totient function (https://en.wikipedia.org/wiki/Euler%27s_totient_function ). Read the section on https://en.wikipedia.org/wiki/Euler%27s_totient_function#Computing_Euler's_totient_function
Answer: What primes do you need to worry about? The primes that divide $360$ are $2,3,5$, so you  really want to find those numbers which are not divisible by $2, 3$, or $5$.
Now

$360/2 = 180$ numbers up to $360$ are divisible by $2$.
$360/3 = 120$ numbers up to $360$ are divisible by $3$.
$360/5 = 72$ numbers up to $360$ are divisible by $5$.

But some numbers are divisible by both $2$ and $3$, or by $3$ and $5$, or $2$ and $5$. So we've overcounted. (This is an inclusion-exclusion argument in progress).

There are $360/6 = 60$ divisible by $2$ and $3$.
There are $360/15 = 24$ divisible by $3$ and $5$.
There are $360/10 = 36$ divisible by $2$ and $5$.

But we've overcounted how much we've overcounted! There are also numbers divisible by $2$, $3$, and $5$.

There are $360/(2 \cdot 3 \cdot 5) =12$ numbers up to $360$ that are divisible by $2\cdot3\cdot5 = 30$.

Thus in total there will be
$$ 360 - (180 + 120 + 72 - (60 + 24 + 36 - (12))) = 96.$$

In fact, this is one way of understanding the expression for $\varphi(n)$ given by
$$ \varphi(n) = n\prod_{p \mid n} \left( 1 - \frac{1}{p} \right),$$
which encodes this inclusion-exclusion argument within it.
Answer: You can show that $\phi:\mathbb{N}\to\mathbb{N}$ defined by $$\phi(n)=\#\{m\in\mathbb{N}:\text{gcd}(m,n)=1,1\leq m\leq n\}$$
is multiplicative. That is, if $m,n\in\mathbb{N}$ are relatively prime, then $\phi(mn)=\phi(m)\phi(n).$ Using this you only have to solve the problem for prime powers, and everything else comes by multiplication. It's not hard to show $\phi(p^n)=p^n-p^{n-1},$ which allows us to compute $$\phi(360)=\phi(2^3\cdot5\cdot3^2)=(8-4)(5-1)(9-3)=96.$$
The function $\phi$ is actually very famous, and is known as the Totient function, or Euler's Totient function.
Comment: Would you be able to explain this in a set theory/simpler way? Sadly, we just started this chapter on it.
Comment: @Math Newbie Can you clarify which parts you are having trouble understanding? I can explain.
Comment: I'm sorry, but I would have no idea where to start with this solution. Thank you so much for answer though -- I get it now!


How can I override the default forums and container pages with a view?

Question: I need to override the default pages that come with forums with views. I need to still include the default info as per the screenshots. I can't seem to get the right relationships and the correct aggregation for the counts. Any insight would be appreciated.
Comment: So the problem is the "Replies" column in the second table? Isn't there something in Views which does that?
Comment: For some things you could make your own Views field handlers..
Comment: Try to create view with same path, it will override the default display.
Comment: @ARUN It's not just overriding the path, it's about getting the correct relationships and aggregation.
Comment: Are you using Advanced Forums? It might be difficult to get everything in one view. You should consider using https://drupal.org/project/views_field_view but yes performance might be a problem ;)
Comment: Yeah, I was considering this. I though there may be a way to do it without using that module. That kind of query may be quite a performance hit.
Answer: You can use Advanced Forum module, which provides many advanced features, and overrides the default forum listing with views and panels. It is not a replacement module for core forum but an enhancement.
If you don't want to use it, you can at least take a look at how they've overriden the core forum listing and make your own implementation.
Comment: I already looked at this. Advanced forum provides some extra forum listings, but it doesn't override the core pages. There are a few clues there that help me but not enough to do what I need to do.
Comment: You're right. I've just checked it now. It overrides the forum topic listing, but not the forum listing.
Comment: Although your answer is not really correct, I have assigned the Bounty to you as the deadline is approaching and I don't want it to go to waste. I do appreciate the effort though. Hopefully someone else can help me out with an answer eventually. :(
Comment: Thank you for the bounty, although I couldn't help. I'll look into that on the weekend and play around with views, if you don't get any reasonable answers.


Homotopically equivalence for a 2 dimensional manifold

Question: I have the following problem in my homework for algebraic topology:
 Does there exist a compact 2-dimensional manifold $M$ without boundary such that $M\times M$
is homotopically equivalent to $M$?
I was thinking that no, because, there are two cases:

The manifold is orientable of genus $g$: $M_g$. Then it has a CW-complex structure given by one $0$-cell, $2g$ $1$-cells $\{a_1, b_1,\dots,a_g,b_g\}$ and one $2$-cell attached by product of commutators $[a_1,b_1][a_2,b_2]\dots[a_g,b_g]$ with the homology groups:
$H_n(M_g)=\begin{cases}\mathbb{Z}, \text{ if }n=0,2\\\mathbb{Z}^{2g},\text{ if }n=1\\0,\text{ else}\\\end{cases}$.
Using Kunneth's formula it follows that $H_4(M_g\times M_g)\neq 0$, therefore $M_g\times M_g$ is not homotopically equivalent to $M_g$.
The manifold is not orientable of genus $g$: $N_g$. Then it has a CW-complex given by one $0$-cell, $g$ $1$-cells $\{a_1,\dots,a_g\}$ and one $2$-cell $e$ atached by the word $a^2_1\dots a^2_g$ with the homology groups: $H_n(N_g)=\begin{cases}\mathbb{Z}, \text{ if }n=0\\\mathbb{Z}^{g-1}\oplus\mathbb{Z}/2,\text{ if }n=1\\0,\text{ else}\\\end{cases}$. Using Kunneth's formula it follows that $H_2(N_g\times N_g)\neq 0$, therefore $N_g\times N_g$ is not homotopically equivalent to $N_g$.

Is my reasoning correct or am I missing something?
Comment: Can I use $M = \mathbb R^2$?
Comment: I guess the problem reffers to closed manifolds.
Answer: Looks ok to me.
You can simpy observe that $M\times M$ is a closed $4$-manifold, so that $H_4(M\times M,\mathbb Z_2)\neq0$.
Comment: I'm using the fact that every connected manifold has is $\mathbb Z_2$-orientation.


Como posso alterar uma label que está numa gridpane em javafx

Question: Boa tarde comunidade,
Ultimamente tenho andado a explorar a vertente javafx e a criar uma aplicação para o meu mestrado.
Resumidamente, a aplicação recebe uma imagem do utilizador, e cria uma gridpane por cima da imagem, consoante o número de colunas e linhas que o utilizador pretende. Cada célula da gridpane tem como label o valor 0.
A imagem é exemplo da explicação:
Até aqui tudo bem. O que pretendo e não estou a conseguir, é adicionar um mouse event, que sempre que eu clico numa label/célula da gridpane, o valor 0 passe para 1.
package vistas;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ResourceBundle;

import javax.print.DocFlavor.URL;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.stage.FileChooser;
import principal.main;

public class AreaProjectoController {

    @FXML
    private Button meuBotaoImagem, meuBotaoGrelha, btnLimpaGrelha;

    @FXML
    private ImageView minhaImagem;

    @FXML
    private TextField txtGrelhaLeft, txtGrelhaRight;

    @FXML
    private AnchorPane painelGrelha, painelArea;

    @FXML
    private GridPane painelCriaGrelha;

    public void initialize(URL location, ResourceBundle resources) {}

    public void mostraImagem(ActionEvent evento) throws FileNotFoundException {

        FileChooser imagemEscolhida = new FileChooser();

        // Define a extensão do ficheiro
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JPEG/PNG", "*.jpeg", "*.png");
        imagemEscolhida.getExtensionFilters().add(extFilter);

        // abre a janela para procurar uma imagem
        File ficheiro = imagemEscolhida.showOpenDialog(main.getPrimaryStage());

        // O if trata quando se cancela o carregamento de uma imagem
        if(ficheiro != null) {
            Image imagem = new Image(new FileInputStream(ficheiro));
            minhaImagem.setImage(imagem);
            painelGrelha.setVisible(true);
            txtGrelhaLeft.setText("0");
            txtGrelhaRight.setText("0");
        }

    }

    public void criaGrelha(ActionEvent evento) {

        int txtLeft = 0, txtRight = 0, i = 1, ii = 1;

        ColumnConstraints colunas = null;
        RowConstraints linhas = null;

        txtLeft = Integer.parseInt(txtGrelhaLeft.getText());
        txtRight = Integer.parseInt(txtGrelhaRight.getText());

        //Este for cria a grelha após receber os valores
        for(i = 1; i <= txtLeft; i++) {
            colunas = new ColumnConstraints();
            colunas.setPercentWidth(25);
            painelCriaGrelha.getColumnConstraints().add(colunas);
        }

        for(ii = 1; ii <= txtRight; ii++) {
            linhas = new RowConstraints();
            linhas.setPercentHeight(25);
            painelCriaGrelha.getRowConstraints().add(linhas);
        }

        Label fillLabel[][] = new Label[txtLeft][txtRight];

        for (int l = 0; l < fillLabel.length; l++) {
            for (int j = 0; j < fillLabel[l].length; j++) {
                fillLabel[l][j] = new Label();
                fillLabel[l][j].setText("0");
                painelCriaGrelha.add(fillLabel[l][j], l, j);
            }
        }

        painelCriaGrelha.setGridLinesVisible(true); //isto faz aparecer as linhas da grelha a preto
        painelArea.setVisible(true);

        System.out.println(fillLabel[2][2]);
    }

    public void limpaGrelha(ActionEvent evento) {

        painelCriaGrelha.getColumnConstraints().clear();
        painelCriaGrelha.getRowConstraints().clear();
        txtGrelhaLeft.setText("0");
        txtGrelhaRight.setText("0");

    }

}

Este é o código que tem as funcionalidades que vemos na imagem. É a classe controller da view. Por que o meu objectivo é seleccionar as labels/células que correspondem à área azul da imagem.
De referir que os valores vão para uma matriz.
Neste exemplo a matriz está:
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
Mas deveria ficar, após implementação do evento mouse click, algo assim:
0000111111
1111111111
1111111111
1111100011
1111100011
0000000000
0000000000
0000000000
0000000000
0000000000
Obrigado.
Answer: Pesquisei bastante sobre seu problema e as soluções que eu achei envolviam navegar todos os nós do grid e colocar um onMouseClick em todos os nós (Bem porco na minha opinião). Como não encontrei o que me parece mais correto pro seu caso fiz um workaround que pode resolver seu problema (Ou pelo menos uma boa direção).
@FXML
private GridPane grid;

private ObservableList<ColumnConstraints> columns;
private ObservableList<RowConstraints> rows;

@Override
public void initialize(URL url, ResourceBundle rb) {
    grid.setGridLinesVisible(true);
    columns = grid.getColumnConstraints();
    rows = grid.getRowConstraints();
}

@FXML
public void mudarValorCelula(MouseEvent e){
    Double x, y, columnAcc = 0.0, rowAcc = 0.0;
    int i = 0, j = 0;

    // Pega a posição clicada pelo mouse
    x = e.getX();
    y = e.getY();

    // Calcula em qual coluna o X está
    for (ColumnConstraints c : columns){
        if(columnAcc < x && x < columnAcc + c.getPrefWidth()){
            break;
        }
        j++;
        columnAcc += c.getPrefWidth();
    }

    // Calcula em qual linha o Y está
    for (RowConstraints c : rows){
        if(rowAcc < y && y < rowAcc + c.getPrefHeight()){
            break;
        }
        i++;
        rowAcc += c.getPrefHeight();
    }

    // Modificando o elemento correto
    Label l = (Label) grid.getChildren().get(j*columns.size() + i);
    l.setText("1");
}

Também é necessário colocar o método mudarValorCelula no onMouseClick do seu grid:
<GridPane fx:id="grid" layoutX="15.0" layoutY="55.0" onMouseClicked="#mudarValorCelula">

Essa solução presupõe algumas coisas importantes:

Seu grid está inteiramente preenchido com Labels
Os labels estão em ordem de coluna (ver imagem abaixo)
Todos os rows e colunas devem ter sua constraint

Isso acontece porque o método add do grid é dessa forma grid.add(column, row) que é o oposto do que estamos acostumados, então temos que colocar os labels nessa ordem:

Se quiser pegar por row terá que ficar assim (0,0) (1,0) (2,0) (0,1) ... e mudar o i*columns.size() + j
Obs.: Só foi testado com matrizes quadradas, não funciona para outros tipos.
Obs2.: Se você souber o número de colunas a prioi é bom colocar no lugar de columns.size()
O resultado foi o seguite:


Qual a hora certa para incluir plugins em um programa?

Question: Estive acompanhando vários projetos de código aberto e percebi que vários deles possuem suporte a plugins. Surgem algumas dúvidas:

Qual a melhor hora para adicionar plugins? Devo me preocupar com eles desde o projeto do sistema, ou devo deixar eles para um momento mais oportuno?
Todos os problemas podem ser resolvidos com plugins? Qual a finalidade de um plugin?
Aparentemente muitos projetos veem os plugins como as funcionalidades básicas de seus sistemas, quando em meu entendimento, os plugins deveriam ser apenas funcionalidades "extras". Meu pensamento está coerente?
Para o caso de eu resolver adicionar plugins a um aplicativo, existe alguma metodologia pronta para que eu possa me basear e evite cometer erros de design?
Vamos imaginar que eu esteja desenvolvendo um sistema X e que no momento da concepção do projeto eu tenho apenas suporte para uma biblioteca A. Se eu desejar futuramente adicionar um backend para uma biblioteca B de funcionalidade semelhante, qual a melhor forma de resolver isto? Os plugins podem ajudar a resolver este problema?
Comment: @mgibsonbr Acho que tens razão, se levar em consideração esta parte da pergunta *Devo me preocupar com eles desde o projeto do sistema, ou devo deixar eles para um momento mais oportuno?* Se você tiver uma resposta para o colega então irei votar para reabrir também.
Comment: Embora essa pergunta dê certa margem para opiniões, acho ela muito interessante e "respondível", de modo que estou votando por deixá-la aberta.
Answer:
Qual a melhor hora para adicionar plugins?

Se você prevê que certas funcionalidades são interessantes para seu sistema, mas que ficariam melhor fora do seu "núcleo", então ajuda projetá-lo desde o início de modo a esperar plugins.
Um exemplo seria um programa que trata de diversos formatos de arquivo, mas não quer ficar "amarrado" com os formatos nativamente suportados. Nesse caso, é melhor abstrair o tratamento desses arquivos, e escrever um plugin para cada formato desejado. Facilitando, é claro, o desenvolvimento e a implantação de novos plugins, inclusive por terceiros.

Qual a finalidade de um plugin?

Um plugin é um complemento para seu sistema, uma forma de estender as funcionalidades básicas do mesmo. Dessa forma, um plugin só faz aquilo que o sistema "deixa" ele fazer, não dá pra resolver qualquer problema possível e imaginário dessa forma (a menos que o "plugin" use monkey patch ou mesmo modifique os fontes do sistema original e os recompile - caso em que ele é mais chamado de "mod" que de "plugin").
Há quem tente projetar sistemas inteiros como uma pequena fundação genérica e um grande conjunto de plugins. Esse tipo de arquitetura é complicada, pois é preciso gerenciar com cuidado as dependências entre os plugins, mas o resultado final é um sistema com maior flexibilidade. A princípio poderia-se substituir qualquer plugin por outro de modo a alterar a funcionalidade do sistema, mas na prática a cadeia de dependências torna difícil modificar a "base" do sistema, de modo que mesmo esse modelo possui limitações.

Aparentemente muitos projetos veem os plugins como as funcionalidades básicas de seus sistemas, quando em meu entendimento, os plugins deveriam ser apenas funcionalidades "extras".

Não necessariamente, veja o primeiro exemplo dos formatos de arquivo, aquilo pode ser uma funcionalidade "básica" (i.e. você precisa de no mínimo 1 tipo de arquivo suportado pro sistema fazer qualquer coisa de útil) mas ainda ser melhor modelada na forma de plugins. O ponto chave é identificar que áreas do sistema demandam alta customização, e se preparar para atendê-las de acordo.

Para o caso de eu resolver adicionar plugins a um aplicativo, existe alguma metodologia pronta para que eu possa me basear e evite cometer erros de design?

Não existe uma solução única para todos os casos, mas eu recomendaria dar uma olhada no Princípio da Inversão de Dependência, e seus padrões relacionados (em particular a Injeção de Dependência e a Inversão de Controle, dentre outros). O ponto chave é habilitar seu sistema a receber extensões sem ter que recompilá-lo, ou melhor ainda sem nem ter que parar o mesmo ao acrescentar/remover um plugin (mais difícil, porém muito útil durante o desenvolvimento e também cômodo para o usuário final).
Por fim, se você já possui um sistema pronto e percebe a necessidade de customizá-lo (seja com plugins, seja de alguma outra forma), muitas vezes pode ser necessário refatorá-lo, de modo a abstrair a interface entre os componentes (ex.: a forma como seu sistema se comunica com a biblioteca A) e posteriormente realizar essa abstração através de duas implementações concretas (uma que comunica com A, outra que comunica com B). Nesse caso, a inversão de dependência pode ajudar, mas não é necessário seguir todo o caminho até tornar seu sistema "plugável" para colher os benefícios dessa abstração (pode manter tudo interno mesmo, só com uma linha nas configurações indicando qual estratégia seguir).


How to send email to multiple recipients using drupal_mail?

Question: I am using drupal_mail to send email,
$to = 'email@example.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

I want to send email to multiple email addresses at once. Should I be doing this?
$to  = array('email@example.com', 'email@example.com', 'email@example.com',);
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

Comment: check this post, http://dropbucket.org/node/308
Comment: Hey Tanvir, maybe consider accepting a different answer. The currently accepted answer entails the risk of running out of memory or time limit when processing many thousand emails like that.
Answer: The to-parameter to drupal_mail is a string, not an array.  But you can have as many receipent as you like in the the e-mails "to" string, provided they're separated by commas.
So to send the same mail to multiple recipients, do the following:
$to  = 'email@example.com,firstname.lastname@example.com,email@example.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

Se also API documentation for drupal_mail
Comment: i only say that when i try `$to  = 'firstname.lastname@example.com, email@example.com, email@example.com';` I receive only one email, but when I try `$to  = 'email@example.com,email@example.com,firstname.lastname@example.com';` without spaces I received all emails!
Answer: According to PHP doc you can send only one letter via one call of function drupal_mail. So, you should use cycle.
Example
$to  = array('email@example.com', 'email@example.com', 'firstname.lastname@example.com',);
foreach ($to as $email) {
  drupal_mail('$module_name', $key, $email, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);
}

Comment: See the solution below from @FreeRadical for a simpler way of doing this.
Comment: I updated my message to avoid confusing. Thank you
Answer: Use hook_mail to send multiple receipients by passing:
$params = array();
$params['cc'][] = 'firstname.lastname@example.com'
drupal_mail('$module_name', 'custom_key', $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

//hook will be the module name

function hook_mail($key,&$message,$params) {

  if ($key == 'custom_key') {
    $message['headers']['cc'] = $params['cc'];
    //.
    //.
    //.
    //.
  }
}

Answer: If you read drupal_mail function documentation then you'd see '$to' param accepts string not an array in certain formats like:

email@example.com
email@example.com, email@example.com
User
User , Another User

So, we can easily convert your $to array into required format using implode function and hence you'll be to send email to multiple recipients in one go. Here's the code:
$to  = array('email@example.com', 'firstname.lastname@example.com', 'email@example.com',);

//To change array('firstname.lastname@example.com', 'email@example.com', 'email@example.com',)  -> 'firstname.lastname@example.com, firstname.lastname@example.com, email@example.com' use implode

$to_str = implode(",", $to);

drupal_mail('$module_name', $key, $to_str, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);


Match a vector to a list of vectors

Question: I have a list of vectors lis which I need to match to another vector vec
lis <- list(c(2,0,0),c(1,1,0), c(1,0,1), c(0,2,0), c(0,1,1), c(0,0,2))
vec <- c(1,1,0)

So either I would get a logical output
 [1] FALSE  TRUE  FALSE  FALSE  FALSE  FALSE

Or just the position within lis of the match
I've been trying things along these lines:
unlist(lis) %in% vec

but the problem is the position of the number is important i.e. distinguish between c(1,1,0) and c(1,0,1) which I haven't been able to do. I would like to avoid for loops as this needs to be quite efficient (fast).
Answer: The answers by @agstudy and @Julius involve a loop over the (long) lis object; here's an alternative assuming that all elements of lis are the same length as vec to allow vector comparison of the unlisted reference
shortloop <- function(x, lst)
    colSums(matrix(unlist(lst) == x, length(x))) == length(x)

which is fast when lis is long compared to vec.
longloop <- function(x, lst)
    sapply(lst, identical, x)

l1 = rep(lis, 1000)
microbenchmark(shortloop(vec, l1), longloop(vec, l1))
## Unit: microseconds
##                expr       min         lq    median         uq      max neval
##  shortloop(vec, l1)   793.009   808.2175   896.299   905.8795  1058.79   100
##   longloop(vec, l1) 18732.338 21649.0770 21797.646 22107.7805 24788.86   100

Interestingly, using for is not that bad from a performance perspective compared to the implicit loop in lapply (though more complicated and error-prone)
longfor <- function(x, lst) {
    res <- logical(length(lst))
    for (i in seq_along(lst))
        res[[i]] = identical(x, lst[[i]])
    res
}
library(compiler)
longforc = cmpfun(longfor)
microbenchmark(longloop(vec, l1), longfor(vec, l1), longforc(vec, l1))
## Unit: milliseconds
##               expr      min       lq   median       uq      max neval
##  longloop(vec, l1) 18.92824 21.20457 21.71295 21.80009 23.23286   100
##   longfor(vec, l1) 23.64756 26.73481 27.43815 27.61699 28.33454   100
##  longforc(vec, l1) 17.40998 18.28686 20.47844 20.75303 21.49532   100

Comment: +1 - you always give great answers, but waaaay after all the drive-by up-voters are done so often don't get the credit you deserve. Inventive solution.
Answer: sapply(lis, identical, vec)
# [1] FALSE  TRUE FALSE FALSE FALSE FALSE

Benchmark:
l1 <- list(1:1000)[rep(1, 10000)]
v1 <- sample(1000)
AG <- function() sapply(l1,function(x)all(x==v1))
J <- function() sapply(l1, identical, v1)
microbenchmark(AG(), J())
# Unit: milliseconds
#  expr      min       lq    median        uq      max neval
#  AG() 76.42732 84.26958 103.99233 111.62671 148.2824   100
#   J() 32.14965 37.54198  47.34538  50.93195 104.4036   100

Answer: sapply(lis,function(x)all(x==vec))
[1] FALSE  TRUE FALSE FALSE FALSE FALSE

Match a vector to a list of vectors


Como dividir todas as span .class por 3

Question: Como fazer estas divisões e obter resultados diferentes para cada divisão. O resultado sai certo apenas para o primeiro preço e nos outros o resultado são todos iguais: 200.

$(document).ready(function() {
  $(".ecwid").click(function() {
    var x = parseInt($('span.ecwid-productBrowser-price-value')[0].innerHTML.replace(',', '.').substr(2))
    $("span").append("
3x de " + x / 3 + "
")
  });
});

<button class='ecwid'>Teste</button>

R$600,00

R$800,00

R$700,00

R$500,00

Answer: Tens de iterar esses span com spans.each(function() { e depois usar o this para fazer contas e .append().
Exemplo:

$(document).ready(function() {
  $(".ecwid").click(function() {
    var spans = $('span.ecwid-productBrowser-price-value');
    spans.each(function() {
      var valor = parseInt(this.innerHTML.replace(',', '.').substr(2) / 3, 10);
      $(this).append("
3x de " + valor + "
")
    });

  });
});

<button class='ecwid'>Teste</button>

R$600,00

R$800,00

R$700,00

R$500,00

Comment: Perfeito! Era exatamente isso que precisa. Muito obrigado!

Como dividir todas as span .class por 3


Finding the Equations for Planes of Different Faces of a Box

Question: The question is as follows:

The illustration at bottom shows a rectangular box, three of whose edges coincide with the coordinate axes, and one of whose vertices is $(3, 6, 4)$. Give an equation for the plane containing the front face of the box. Do the same for the top and right faces.

For the front face, I found the slope by calculating $\frac{\Delta z}{\Delta y}$ which led me to $\frac{4}{6} = \frac{2}{3}$. However, I don't know whether it should be $\frac{2}{3}x$, $\frac{2}{3}y$, or $\frac{2}{3}z$ nor do I know what the equation will result in a $x$, $y$, or $z$ value.
I hope that by receiving assistance in this part of the problem, then I may be able to calculate the equations for the other planes of the two other faces. Any help will be greatly appreciated.
Comment: You've computed a slope of the box's diagonal, not of any of the faces.
Answer: You can write the equation of a plane by knowing a point that belongs to the plane ${\bf x}_0 = (x_0, y_0, z_0)$ and a vector perpendicular to the plane ${\bf n}$. The equation then becomes
$$
{\bf n}\cdot({\bf x} - {\bf x}_0) = 0 \tag{1}
$$
For example, for  the front face

${\bf x}_0 = (3, 0, 0)$ and
${\bf n} = (1, 0, 0)$

The equation of the plane is then
$$
(1, 0, 0)\cdot[(x, y, z) - (3, 0, 0)] = 0 \\
\Rightarrow ~~~x - 3 = 0
$$
I will leave the other two for you to work out
Comment: Thank you for your response. I am still not sure about why you have ${\bf n} = (1, 0, 0)$. Furthermore, why can't we use the point $(3, 6, 4)$ and use the slope that I calculated?
Comment: ${\bf n}$ is any vector perpendicular to the plane. As for the point, you can use any point that is on the plane. You can use ${\bf x}_0 = (3, 6, 4)$ the result will be the same
Answer: Planes don't have "slope", they have normal vectors.  But this problem is easier than that.  The front face is parallel to the $yz$ plane and has $x$-intercept $3$.   Every point in that plane has $x$-coordinate $3$ and there is no restriction on the $y$ and $z$ coordinates.  So the equation of the plane is $x=3.$