Does the Blu-ray of Peter Jackson's King Kong (2005) have the recreated "spider pit sequence"?

Question: A spider pit scene was shot for the original 1933 King Kong, but was presumably cut from the film due to graphic content and is now considered as lost. Peter Jackson reshot the scene using contemporary technology during the filming of his remake. Wired confirms that the scene is included on the Collector's Edition DVD, but did it ever make its way to the Blu-ray release?
Answer: The Blu - Ray, and indeed every other release of Peter Jackson's 2005 King Kong includes Jackson's version of the 'Spider - Pit' scene, as it was not actually removed from the theatrical release.

The most significant Skull Island island based action sequence that was removed from the theatrical cut (and which was restored in the directors 'special edition' - the cut included on the 2005 DVD Deluxe Edition' and on the standard Region B BD release of the film) involved the crossing of the swamp and the 'Piranhadon' attack.
Of course, having completely got the wrong end of the stick there (you are talking about his remake of Willis's actual scene) the feature was not originally included on the standard BD release but may yet be available on this beaut...

and if not can be watched here in the meantime...
King Kong (1933): The Lost Spider Pit Sequence - Peter Jackson Recreation


OP_CHECKLOCKTIMEVERIFY / OP_HODL script

Question: Can someone please explain how I can use OP_CHECKLOCKTIMEVERIFY or OP_HODL to lock funds until block 600000? I have been searching for a newb friendly script but the only ones I have come across is for nLocktime
Answer: I took this from Andreas' book "Mastering Bitcoin" (2nd edition, page 158ff):

To lock it to a time, say 3 months from now, the transaction would be
  a P2SH trans‐ action with a redeem script like this:

[now + 3 months] CHECKLOCKTIMEVERIFY DROP
DUP HASH160 [Bob's Public Key Hash] EQUALVERIFY CHECKSIG

where  is a block height or time value estimated 3
  months from the time the transaction is mined:
  current block height + 12,960 (blocks) or current Unix epoch time +
  7,760,000 (seconds).

The problem is that we are currently at ~506000 blocks, so if this should be a block height, and not a time range, it must be ~94000 blocks in the future.

CLTV and nLocktime use the same format to describe timelocks, either a
  block height or the time elapsed in seconds since Unix epoch.
  Critically, when used together, the format of nLocktime must match
  that of CLTV in the inputs—they must both reference either block
  height or time in seconds.
If nLocktime is nonzero and below 500 million, it is interpreted as a
  block height, meaning the transaction is not valid and is not relayed
  or included in the blockchain prior to the specified block height.

So in your case it must be:
94000 CHECKLOCKTIMEVERIFY DROP
DUP HASH160 [Bob's Public Key Hash] EQUALVERIFY CHECKSIG

You could achieve the delay also with nLocktime, then the tx is not put into the blockchain before the block appears (I think the tx stays in mempool), but with the CLTV it goes directly into the blockchain (is visible in the blockchain), and can only be retrieved after block height  is reached.
Comment: So to use OP_CHECKLOCKTIMEVERIFY I need his public key hash? I thought I could just send to any BTC address with this. nLocktime is not good enough as I could redeem the funds before block X is reached.
Comment: It is the pubkey hash, where the funds shall go to - the hash from the destination  address. The first line is just the exit criteria, the second line is the normal p2pkh ...

OP_CHECKLOCKTIMEVERIFY / OP_HODL script


BLDC Outrunner Direction Change?

Question: I'm designing a Quadcopter for my project. I've seen a lot of guides that the motor rotational direction should be opposite to each other. My doubt is whether the motor have a variety of CW rotation and CCW rotation, or we should change any other thing in the motor?
Comment: are you saying that you do not know what kind of a motor you have?
Answer: Brushless (BLDC) motors are not inherently directional. They can be either clockwise or counter-clockwise, it only needs to be set in the software, or by swapping two of the motor wires on the physical phase output pads of the ESC. The only time a brushless motor will care about rotation is if they have different direction threads on the shaft where the propeller attaches. In that case you want the motors rotating in the direction so that the prop nut tightens against the force on the prop. This is purely functional, not electrical though, if you use nylock nuts, it won't matter if they are all a single thread direction.
Brushed motors however often do have a handedness. Some brushed motors will have slight skew in the magnets that effectively advance the timing when they're running "forward" rather than "reverse" compared to their intended direction. This will result in a faster run speed in the forward direction than the reverse. Also once a brushed motor as been broken in in a particular direction it is often hard on the motor to then run the motor in the other direction. This can result in additional wear on the brushes and a motor that wears out quicker than intended. None of this should be an issue with brushless motors.

BLDC Outrunner Direction Change?


Digitizing with Cut Polygon Tool

Question: I am working a project that consists of manually digitizing geology layers from a scanned map. At the moment my process consists of me digitizing the small polygons and then the larger areas around them. After that I use the cut polygon tool within the editing toolset to cut out the small polygons within the larger area so that they then show through. (See pic below. Small polygons are yellow and larger area is red) My question is, is there a way within ArcMap that would allow me to create my small polygons and then the larger polygon area without having to cut the small polygons to allow for them to show through?
Comment: Slightly off topic. Anyway with such distinctive color I'd use supervised classification and convert output raster to polygons
Answer: Usually during the digitizing process, it is better to start digitizing the big polygons first, then digitizing the smaller polygons located within the big polygons. You can refer to this answer on how to cut small polygons within a big polygon since the key point when cutting a small polygons is to activate Snap to sketch in the snapping toolbar, as you can see in the above answer.

Digitizing with Cut Polygon Tool


Short story about a man who lands on Mars, and Martians don't believe he's from Earth

Question: In my childhood, I read a short story about a man who lands on Mars and finds that Martians looked exactly like humans. When he told them he was from Earth, everyone thought he had a disease that makes him hallucinate. So he takes some Martians to see his space ship, and they think they caught that disease from him. He's later sent to a hospital/asylum where he meets martians who really had that disease. Unfortunately, I don't remember how it ended.
Comment: Roughly speaking, when was your childhood, or when would you estimate that you read it? Do you recall if it was in an anthology book, or a magazine, or something else?
Comment: Yes, it was in an anthology of science fiction stories, but that's the only story I remember from it. I read it in the 90s, but it was probably older than that.
Answer: It seems to be the story The Earth Men, part of the Martian Chronicles bundle of short stories by Ray Bradbury. From Wikipedia:

This story tells of the "Second Expedition" to Mars. The expedition is
  a group of 4 men. The astronauts arrive to find the Martians to be
  strangely unresponsive to their presence. The one exception to this is
  a group of Martians in a building who greet them with a parade.
  Several of the Martians in the building claim to be from Earth or from
  other planets of the solar system, and the captain slowly realizes
  that the Martian gift for telepathy allows others to view the
  hallucinations of the insane, and that they have been placed in an
  insane asylum. The Martians they have encountered all believed that
  their unusual appearance was a projected hallucination. Because the
  "hallucinations" are so detailed and the captain refuses to admit he
  is not from Earth, Mr. Xxx, a psychiatrist, declares him incurable and
  kills him. When the "imaginary" crew does not disappear as well, Mr.
  Xxx shoots and kills them too. Finally, as the "imaginary" rocket
  remains in existence, Mr. Xxx concludes that he too must be crazy and
  shoots himself. The ship of the Second Expedition is sold as scrap at
  a junkyard.
Comment: Bradbury was such a storytelling genius... Now I need to go reread all of him
Comment: OP's story seems so much more whimsical and fantastical compared to the morbid tragedy what you describe.
Comment: Yes! That's the one! And @cde, I blame childhood innocence.
Comment: I concur.  The next story is even more chilling -- the one where the Terran crew is met by their long-lost (dead) parents, lovers, etc.
Comment: @imgx64 now I want someone to write a comedy based on your initial description. Throw some slapstick in to boot.


A three rank Levi-Civita tensor in four dimensional spacetime

Question: Is it possible to construct a Lorentz invariant, three rank Levi-Civita tensor in Minkowski Spacetime? If not, why so? I am talking about something like this $\epsilon_{\alpha\beta\gamma}$ or $\epsilon^{\alpha\beta\gamma}$, where each indices run from $0$ to $3$. As in this answer here, which proves the Lorentz co-variance of the Levi-Civita tensor by using the determinant formula, I guess one would run into trouble if we have three rank Levi-Civita tensors. Kindly elaborate on that.
Comment: The levi civita symbol is defined to be this: $\epsilon_{0123}=1$ and every odd permutation of 0123 would have value of $\epsilon$ to be zero. So, how would we define a 3 ranked levi civita symbols in 4 dimensions?
Answer: You can use Young tableaux/diagrams and the permutation group to figure out the symmetries of the general rank-3 tensor. The spaces correspond to the partitions of the rank:
3=3:
One 20 dimensional total symmetric subspace.
3=2+1:
Two 20 dimensional mixed symmetry subspaces.
3=1+1+1:
One 4 dimensional totally antisymmetric subspace:
$$ A_{\alpha\beta\gamma} = \frac 1 6 [T_{\alpha\beta\gamma} + T_{\beta\gamma\alpha} + T_{\gamma\alpha\beta} - T_{\gamma\beta\alpha} - T_{\beta\alpha\gamma} - T_{\alpha\gamma\beta}] $$
That is the only antisymmetric thing you can make according to Schurl-Weyl theory.
To find the dimensions, I used the Hook Length Formula (summing of the boxes $x$ in a diagram $Y(\lambda)$) for the Young diagram corresponding to the integer partition:
$$ {\rm dim}\pi_{\lambda} = \frac {n!}{\prod_{x\in Y}{\rm hook}(x)}$$
If you consider 3 dimensions ($n=3$), you get ${\rm dim} = 1$, that is the standard Levi-Civita symbol $\epsilon_{ijk}$.
If you set $n=4$, the result is ${\rm dim} = 4$.
That means $A_{\alpha\beta\gamma}$ transforms like a 4-vector.
So, the only antisymmetric part of a rank-3 tensor in Minkowski space rotates like a 4-vector, which means it is not invariant and is not a candidate to be Levi-Civita like.
Meanwhile, the dimensions of the 3 other irreducible spaces are all 20--which are certainly not scalars, and thus not candidates to be Levi-Civita like.
Note that if you consider rank-4 tensors, the partitions are as follows:
4=4:
35 dimensional and symmetric.
4=3+1:
Three 45-dimensional mixed symmetry spaces.
4=2+2:
Two 20-dimensional mixed symmetry spaces.
4=2+1+1:
Three 15-dimensional mixed symmetry spaces.
4=1+1+1+1:
One total antisymmetric 1 dimensional space, which is proportional to the Levi-Civita symbol $\epsilon_{\mu\nu\sigma\lambda}$.
In summary, the answer is "No", and the reason why has to do with the representations of the symmetric group on 3-letters. You partition the rank=3, use the Robinson-Schensted correspondence to associate that partition with irreducible representations of the permutation group. (The Young Diagrams make this step a snap). Then, Schur-Weyl duality associates those with irreducible subspaces of and rank-N tensor (signed permutations of indices). Finally, the Hook Length formula tells you the dimensions of those subspaces.
The Levi-Civita symbol needs to be invariant (e.g., dimension 1, like a scalar) and it need to be totally antisymmetric in all indices--and that simply did not exist for rank 3 in 4 dimensions.
Comment: @fogofmylife I had to cull many references. Most are too mathy for us. Finite group theory is abstract, but a starting point is http://yufeizhao.com/research/youngtab-hcmr.pdf which covers the permutation group and Young tableaux. That the Young symmetrizer applied to indices yields the irreducible subspaces for all ranks in any dimension over all fields (Schur-Weyl Duality) is not clear and I know of no physics oriented reference. It's best to try it by hand for 0=0 (scalars), 1=1 (vectors), 2=2,1+1 (tensors), 3=3, 2+1, 1+1+1 (the 1st nontrivial one) by hand and see what's happening. Goodluck
Comment: @fogofmylife:  The best physics-oriented reference for the Schur-Weyl duality is probably Hamermesh's *Group Theory and Its Application to Physical Problems*, but even that one isn't the clearest.
Comment: The answer is much more engaged than I thought it would be. It will take me a bit of time to understand the whole thing. Can you please refer something where I can read about Young tableaux, partitions and Hook Length formula etc.? Thank you.
Answer: Does this satisfy the requirements?
In Minkowski spacetime (signature: -,+,+,+), let $\epsilon_{abcd}$ be the alternating tensor satisfying $\epsilon_{abcd}=\epsilon_{[abcd]}$ and $\epsilon_{abcd}\epsilon^{abcd}=-24$ and let $v^a$ be the 4-velocity of an observer ($v^av_a=-1$).
Define the "spatial alternating tensor seen by the observer $v^a$" $$\epsilon_{abc}=\epsilon_{abcd}v^d,$$
which satisfies $\epsilon_{abc}=\epsilon_{[abc]}$, $\epsilon_{abc}\epsilon^{abc}=6$, and $v^a\epsilon_{abc}=0$.
(This is extracted from Robert Geroch's "General Relativity, 1972 Lecture Notes" [ISBN 978-0987987174] .)
Comment: This wouldn't be Lorentz-invariant, since its definition depends on the  four-vector $v^a$ chosen, and this vector will transform non-trivially between reference frames.
Comment: @MichaelSeifert , I agree. By construction, this certainly depends on the choice of four-vector.


Why are square functions important in analysis?

Question: I have been reading through chapter 1 of E.M. Stein's textbook Harmonic Analysis: Real Variable Methods, Orthogonality, and Oscillatory Integrals.  In chapter 1, Stein discusses the relationship between singular integrals, maximal functions, and square functions.  I have taken an introductory course on harmonic analysis and therefore understand the importance of singular integrals and maximal functions.  However, I haven't encountered square functions yet, and I don't have any intuition about them or any context to understand why they are important.  Can someone explain to me why square functions are important so that I can understand them a bit better?
Comment: What do you mean by square functions? Do you mean $L^2$ functions?
Comment: I expect OP means the following: given a martingale $(f_n)$, its difference sequence is $d_n = f_n - f_{n-1}$ and its square function is $S(f) = (\sum_n d_n^2)^{1/2}$.
Comment: @Thomas I'm referring to the operator $s_{\phi}$ that sends a function $f$ to the function $\left( \int_0^{\infty} |f * \phi_t(x)|^2 \frac{dt}{t} \right)^{1/2}$, where $\phi$ is an $L^1$ function with average value $0$, and $\phi_t$ is the rescaling $\phi_t(x) = t^{-n} \phi(x/t)$ where $n$ is the number of dimensions.  Stein says that this is called a "square function."
Answer: One of the nice things about square functions is that they can be used to dominate the norm (in many spaces, but primarily $L^p$) of oscillatory functions.
Take for example the Littlewood-Paley square function, which can be seen as a discretization of the square function you mention in your comment. The basic idea is to write a function $f$ as a sum of frequency-localized "projections"
$$
f = \sum_n P_n f,
$$
where $P_n$ is seen in frequency space as
$$
\widehat{P_n f } = \psi_n \widehat{f}
$$
and $\psi_n$ is a bump function which is basically $1$ at scale $2^n$ and $0$ at every other scale.
The square function in this case is
$$
Sf = \Bigl( \sum_n |P_n f|^2 \Bigr)^{1/2},
$$
and we have (for $1 < p < \infty$) that
$$
\|f\|_{L^p} \approx \|Sf\|_{L^p}.
$$
This allows us to estimate
$$
\|\sum_n P_n f\|_{L^p},
$$
whose parts could provide a lot of cancellation, by
$$
\Bigl\|\Bigl( \sum_n |P_n f|^2 \Bigr)^{1/2}\Bigr\|_{L^p},
$$
which patently has no possibility for cancellations. It is possible now (and indeed quite common) that these "projections" $P_n f$ are simpler to estimate than $f$, but this is hard to make precise.
In the case of your square function, note that you are basically writing $f$ as a "sum" (an integral) of strictly positive parts (since the integrand is squared, and hence the name). So it is more or less the same idea.
Answer: When establishing Littlewood-Paley theory on the real line $\mathbb{R}$, passing from $L^2(\mathbb{R})$ to $L^p(\mathbb{R})$ causes the orthogonality relations to fail ($L^p$ is not a Hilbert space). In order to compensate for the lack of orthogonality, we provide a substitute. Set $\hat{P_jf}=\chi \hat{f}$ to be the Littlewood-Paley projections of $f$. Then the square function
\begin{equation*}
(\sum |P_j f|^2)^{1/2}
\end{equation*}
followed by an application of Plancheral's theorem allow us to make a vector-valued extension to $L^p(\mathbb{R})$. A similar principle applies with the Littlewood-Paley $g-$function. Define the Poisson integral
\begin{equation*}
u(x,y)=\int_{\mathbb{R}^n}P_y(t)f(x-t)dt,~f\in L^p(\mathbb{R}^n).
\end{equation*}
Establishing the square function
\begin{equation*}
g(f)(x)=(\int^{\infty}_{0}|\nabla u(x,y)|^2ydy)^{1/2}
\end{equation*}
allows us to perform another vector-valued extension to compare $L^p$ norms. The importance of Littlewood-Paley theory is that LP techniques have been used to establish Strichartz estimates to prove global existence results in dispersive PDE theory (I can send you some references if you like).


What is the maximum wattage LED bulb that can be used in a 75 watt fixture?

Question: What is the absolute maximum wattage LED bulb that can be used in a fixture rated for 75 watt incandescent bulbs?
Comment: The simplistic answer is: any LED which doesn't produce more than 75W of heat. But it also depends on the fixture's ability to dissipate heat, since an incandescent is allowed to get pretty hot but an LED isn't...
Comment: The really simple answer is: 75 watts.
Comment: What's the highest wattage LED bulb you can find?  This sounds like a non-issue.
Answer: The issue is heat.  The fixture is rated for a bulb using 75 watts and turning essentially all of it into heat.
You could put a 75w heating element there and be within limits of the fixture.
Seriously - you would not want to put a 75w (actual) LED there.  It would be like a Boeing 747 landing light.   Google some youtube videos of "100w LED flashlights" which people homebrew - they are portable suns.
In any case, the fixture may not mind the heat, but LEDs and CFLs do not like heat and need to cool.   This is rather unlikely to be a problem for "75-watt-equivalent" LEDs of 7-12 watt range, or even a somewhat bigger 100w equivalent.
But for our hypothetical 75-watt-actual mega-bright LED, cooling may emerge as a serious issue.  Or not.  There's a lot of thermal science involved which depends totally on the design of the particular fixture and the heat sink of the particular LED.  For instance a chandelier is not going to have the problems a weather-sealed fixture would.  But again we are talking about an extreme case of wanting vastly more light (lumens) than the fixture manufacturer ever imagined, and extreme projects take extreme risks.
Answer: Ás others have noted, the fixture will be happy up to 75 Watts, which is to much light to be useful.
However, there is another factor, that being the bulb itself. Some LED bulbs are much more tolerant of heat than others. This difference affects how long the bulb will last in a poorly ventilated fixture. Bulbs suitable for enclosed fixtures will say so on their packaging; read the labels before buying.


Can I still claim the pre-fork BCC with a current balance of 0 from Bitcoin Core wallet?

Question: I had BTC in my Bitcoin Core wallet before the BCC fork, but I didn't claim the BCC before transferring my BTC to another wallet after the fork.  Is it possible to claim the pre-fork BCC even though my Bitcoin Core wallet balance is currently 0?  If yes, how do I go about claiming the BCC from my Bitcoin Core wallet?
Answer: What you did after the fork on the bitcoin blockchain has no effect on the BCC chain at all. All that matters is what you had at the time of the fork. You can follow the regular BCC claiming instructions.


How do I find out what user used what coupon code?

Question: I have a few coupon codes in my store, and I'd like to be able to track what code a user may have utilised. Inversely, is there a way to see how many times a particular code was used?
Comment: Is there anything I can do to help you close this out? Let me know if any of the below solutions helped.
Answer: Which customers used which coupons:
I usually shy away from raw db queries, but in this case I will make an exception:
select customer_email, group_concat(distinct sfo.coupon_code) from sales_flat_order sfo
where coupon_code is not null
group by customer_email;

You could do the same with the Magento ORM - will formulate a writeup on how to do that and edit afterward and here's how:
$coll = Mage::getModel('sales/order')->getCollection()
    ->getSelect()->reset(Zend_Db_Select::COLUMNS)
    ->columns(array('customer_email',new Zend_Db_Expr('group_concat(distinct coupon_code)')))
    ->where(new Zend_Db_Expr('coupon_code is not null'))
    ->group(array('customer_email'));

How many times a coupon was used:
As already pointed out in another answer this is in a report. At the most basic level the query for that would be:
select coupon_code,count(coupon_code) from sales_flat_order
group by coupon_code;

The ORM-centric way of handling this is also fairly straightforward:
$coll = Mage::getModel('sales/order')->getCollection()
    ->getSelect()->reset(Zend_Db_Select::COLUMNS)
    ->columns(array('coupon_code',new Zend_Db_Expr('count(coupon_code)')))
    ->group(array('coupon_code'));

Note that this does not take into account order status or invoiced payment.
Comment: Where to add this code to make work " Which customers used which coupons"  in magento 1.9
Comment: This is a mater of running from a PHP script within the context of the Magento store.
Comment: right  and I am asking location of file. You can post what you have done to explain me.
Comment: Isn't that then not a coupon? It's just a promo? I think that is kind of obvious given the question was specifically about codes.
Answer: Reports > Sales > Coupons in your admin area will let you see how many times a particular discount code was used, the amount of sales generated for and the amount of total discount given for each as well. You can filter it down by day, month, year etc. You can also filter by order status and for a certain date period.
Comment: There's nothing in the default functionality of Magento to do this. (Other than looking at each order individually). But the information could easily be pulled into which ever page in the admin area you want. The data is stored in a database table after all. So for example, you have Reports > Customers> Customers by order totals, this would be a could place to pull this into. Just creating a column called "coupon" or the like, and inserting the code in where used.
Comment: Thanks Blair! Do you know if there is a way to see which one of my users used a specific code?
Comment: Something like this module below will also allow you to add "coupon code" to the Sales > Orders page, http://amasty.com/better-order-management.html which I think is exactly what you are looking for?
Answer: Default report is available in report -> sales -> coupons.
And with script you can find used coupan count and customer details very easily :
$coupon = Mage::getModel('salesrule/coupon/usage');
$coupon->load('code', 'coupon_id');
if($coupon->getId()) {
    $timesUsed = $coupon->getTimesUsed();
    $customer = $coupon->getCustomerId();
    echo $timesUsed;
    echo $customer;
}

Comment: On which location to put this code?
Comment: In your code, how does the `$coupon` have a specific customer tied to the object? Seems like you're missing something.
Answer: I had a similar request from client of ours, they wanted to know what coupon was used if any on a particular order
for now I am doing this manually in db but as soon as I will make up extension for this I will update my question, hope this will help meanwhile
   SELECT sfo.customer_id AS customer, ce.email, GROUP_CONCAT(cev.value SEPARATOR ' ') as name,
sfo.entity_id, sfo.increment_id,scu.times_used,sc.coupon_id,sc.rule_id,sc.code FROM sales_flat_order sfo
LEFT JOIN salesrule_coupon_usage scu ON sfo.customer_id = scu.customer_id LEFT JOIN salesrule_coupon sc
ON sc.coupon_id = scu.coupon_id LEFT JOIN customer_entity ce ON ce.entity_id = sfo.customer_id
LEFT JOIN customer_entity_varchar cev ON cev.entity_id = sfo.customer_id WHERE (cev.attribute_id IN (5,7)
OR cev.attribute_id IS NULL) GROUP BY sfo.increment_id ORDER BY sfo.increment_id;

some lines might be full of nulls this is more likely guest customers and some will have nulls in coupon info, these will be orders where coupons were not used
Comment: On which location to put your code?
Answer: There's an open source coupon module which I have used (Magento 1 - EE)
https://github.com/pavelnovitsky/CouponUsage
It creates a new admin grid:
Admin > Promotions > Coupon Usage

which links coupons to orders. I can confirm that it works well, even though it's a few years old now.
Answer: In a Magento ce-188.8.131.52 shop I found the database field applied_rule_ids in the table sales_flat_order. Looks like this matches the id from the Shopping Cart Price Rules page.
Could be useful if you have generated coupon codes:
`SELECT COUNT(*) FROM sales_flat_order where FIND_IN_SET('1', applied_rule_ids)
Comment: it's comma separated because there might be several rules involved. So better use [`FIND_IN_SET()`](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set) instead of `=`
Answer: I have a coupon code that has a Uses Per Customer value of 1, and I'm not able to use it on my customer account. So I queries the sales_flat_order table as the other answers suggest to see how times I've used this code, and there was no order of mine in that table that shows I used the coupon code in question. I had to dig through the code and found in Mage_SalesRule_Model_Validator::_canProcessRule() it actually checks the tables salesrule_coupon_usage and salesrule_customer ..
select * from production.mage_salesrule_customer
where customer_id = 58394

This query above showed I had used the coupon one time. I do not know why it shows I used it once, and why there is no record of my use in the orders table (yet), but I hope this helps somebody else that was struggling to figure this out.
Answer: For magento 2, please run this sql to get customer email, coupon code, discount amount, grand total and increment id
select a.customer_email, a.coupon_code, b.increment_id, a.discount_amount,
a.grand_total from `sales_order` as a, `sales_order_grid` as b where
coupon_code is not null AND a.`entity_id` = b.`entity_id`


How to calculate ideal Decision Tree depth without overfitting?

Question: What would be a good way to go around finding the best depth for a DecisionTree (in SKLearn)? How can I tell if I've gone too deep and am overfitting? I know I can find the best parameters with f.e. GridSearchCV, but the best score might not mean I get the best classifier as I may overfit the tree to the data.
Answer: No! the best score on validation set means you are not in overfitting zone. As explained in my previous answer to your question, overfitting is about high score on training data but low score on validation. So to avoid overfitting you need to check your score on Validation Set and then you are fine. There is no theoretical calculation of the best depth of a decision tree to the best of my knowledge.
So here is what you do:

Choose a number of tree depths to start a for loop (try to cover whole area so try small ones and very big ones as well)
Inside a for loop divide your dataset to train/validation (e.g. 70%/30%)
Each time train your decision tree with that depth on training data and test it on the validation set, then keep the validation error (you can also keep the training error)
Plot the validation error (you can combine it with evolution of training error to have a prettier plot for understanding!)
Find the global minimum of validation error.
Then you can narrow your search in a new for loop according to the value you found to reach a more precise value
Answer: Actually there is the possibility of overfitting the validation set.
This because the validation set is the one where your parameters (the depth in your case) perform at best, but this does not means that your model will generalize well on unseen data.
That's the reason why usually you split your data into three set: train, validation and test.
You train on the training set, tune the parameters on the validation set, and finally, when you are happy with the parameters, you test your model as a whole with the test set. And usually, the error on the test set will be higher than the error on the validation test.
If this difference is small, you accept the model. But if it's big, you need to act:
1) reorganizing the three sets, because maybe you have a variance problem between the sets;
2) adding some penalty on your model, acting on the regularization parameters; or lowering the depth of the trees, if you are interested only on it


Can people on H4 EAD do private tutoring?

Question: Can people on H4 EAD do private tutoring?
i.e. Should the private tutoring be as part of any registered company or can we do it individually and take money in cash and pay the tax appropriately for the year?
Answer: If you have an EAD you can do work in any way you want -- e.g. you can work individually, for a company, for your own self-employed company, etc. It doesn't matter.
Of course you will need to follow the appropriate tax rules for whatever form of work you do.
Comment: I was wondering can we take the amount in cash for independent tutoring? or should all these money be collected in the name of any company name to report the tax appropriately?
Comment: @barath: The method of payment, i.e. cash or check, doesn't matter. If you are working as an independent contractor, I believe they will need to give you a 1099 if their payments to you during the year exceed $600. No matter if you get a 1099 or not, you are required to report this income on your tax return (you will likely have to pay both income tax and self-employment tax).


What gets tired or feels hungry? Experiment

Question: So there is a mind (one that asks this question) and there is the body (fingers typing this question of the mind). This is not "I" or "me". So when the body goes running and when the mind or brain is thinking, why does it get tired? Or is it just the illusion of tired?
Comment: Consider the Nonduality Tag.
Comment: I think best to leave the experience as is and move on :) thanks for the replies
Answer: In the mind and body at the level of experiencing things moment by moment there is feeling and tiredness but nothing feels hungry or gets tired that can be experienced directly.
Answer: Nothing is <code>" 'I' or 'me' "</code>. The experience is the illusion of illusion. That is what makes it the truth. Confusion is the illusion of not understanding. Understanding is the illusion of understanding.
But this is nonduality, which is not what Buddhism teaches. Or does it?
Answer: It is you who gets hungry. The problem start when you mentally identify that "I am hungry". If you just let be as another sensation without metal conceiving in relation to I there is no problem and pain will be reduce and stress from the situation non existent. Many metal construction or notion or perception of "I" or "mine" leads to misery. It is holding on to this metal construction or notion or perception of "I" or "mine" which should stop. As when this stops here is no identification or notion or perception or metal conceiving of a self in the person this is what is generally referred as no self or nonself, i.e., the person is devoid of holding on to any mental conceiving of a person hence does not have any sense as this is a person, or this is me, etc.
Answer: From a Madhyamika-Prasangika viewpoint, when I see your body, I see BlackFlam3. When I hear your voice, I hear BlackFlam3. When your body is unwell, you are sick. When anger arises in your mind, you are angry. Yet, your are neither your body nor your mind. You depend on them, though, for you would not be who you are if t was not for them. You even depends on what is not even in your continuum, such as external objects that you apprehend, and so forth.
As a person, you exist conventionally.  That conventional object, the person, is an object apprehended by conventional cognizers. The person is seen, heard, touched, smelled, being remembered, and so forth. That person is an object of pride, anger, jealousy, desire, and so forth. Yet, that person which is loved, hated, seen... is not intrinsically one with any of its aggregates.
In the same way, I see your hand, but I do not see the whole of it (back and front and bones, and so forth) and your hand is not intrinsically what I see of it.
The problem is as follows: as soon as you engage into analysis, wandering whether the person is intrinsically one or intrinsically different from its aggregates, you engage in ultimate analysis. And what the mind of ultimate analysis finds (realizes) is the ultimate truth which is the absence of a truly existent person. So, of course, when you ask yourself "but am I that feeling? or this body? or am I my flesh? but if I was, I could not say 'my' as if there was an I possessing it, and so forth" you take the direction of ultimate analysis and you will not find the person.
Identifying the conventional objects as objects found by conventional valid cognizers (eye-consciousness, ear-consciousness and so forth, that do not engage into analysis) is of utmost importance. So, yes, conventionally, it is enought for me to see your body to see you.
Answer: Maybe of thinking in loops? May Mr/Mrs stay with that and do fall into the all is anatta nonsens, which is simply vibhava tanha. Mr/Mrs would get tired even faster.
(Note: this answer has not been given with the agreement to be means of trade or the purpose of/for trade and/or keep people trapped and bound. How you handle it lies in your sphere, but does not excuse the deed here either.)
Answer:
So when the body goes running and when the mind or brain is thinking, why does it get tired? Or is it just the illusion of tired?

Perhaps further to Tenzin's saying that the mind-and-body is not "I", if you only ask, "Why does the body get tired?" then IMO an answer might be explained using (not Buddhism itself but using) physiology, biochemistry, maybe even thermodynamics.
It does reminds me of the Buddha's saying, though, "all compound things are subject to decay".
A slightly different question (maybe a question we should ask, instead) could be whether you're mindful, or what you're mindful of -- and, whether you find "it gets tired" dissatisfactory. Because maybe what's important to keep in mind is "dukkha" and "cessation of dukkha".


Can zombies have meaningful lives?

Question: Can zombies have meaningful lives? If not, does that mean a meaningful life is "like" something?
Comment: How exactly do you define "zombie"?
Answer: It depends what you mean with meaningful lives. Assuming that zombies do not have emotions and thoughts, but are functioning like an organic robot.
(1) They can have meaningful lives when they are useful in a way (are there helpful zombies?). In the same way machines can have a meaningful existence for humans.
(2) If you asking about meaningful lives in a personal way you have a different answer. Meaning is a difficult subject, but when we talk about meaning of life concepts as (self)consciousness, caring (about something/ the world) and judgements are involved. These are all processes that involve emotion and thought. So to bad for the zombies.
If you want to know more about this subject I suggest you read some articles about dementia and meaningful lives.
Comment: dementia sufferers aren't zombies but the complete opposite really
Comment: I agree, however the issue about meaning of life and being able to think (rationality) and consciousness becomes really concrete here. So I think it can help a lot in thinking on issues of meaning of life.
Answer: I  think this question should be examined from the sociological perspective, as well as the physio-biological.
If one equates meaning in life to rational thought then zombies, or any animal other than humans and dolphins I suppose, would have little chance to find meaning to their lives aside from simply satisfying basic instincts.
However, we can give meaning to their lives, assuming our society is around to do so... Consider, on the precipice of an outbreak, the first zombie to be filmed. The video would go viral (pun intended,) and the various news media outlets would plaster it all over the place. The zombie would probably be named. It's be recognizable in suburban households; it'd be famous!!
In that vein, the life of zombie that tragically eviscerates a political candidate, or pop icon, in front of a national audience would hold meaning in the lives of the witnesses. One will not likely forget the face of the zombie that kills a dear family member in front of him/her, again assuming that person ultimately makes it out of the confrontation...
Now, I realize none of this holds water with the zombie as an individual or a species. But, consider the parable of the 100th monkey. The 100th zombie, in this case, that, say, discovers that the braaaaiiiinnnnsss are the tastiest part of their prey, may unlock an evolutionary domino effect that alters the behavior of the entire species... In terms of science, this is a very meaningful event - even though it is one of which neither the individual nor the species is cognizant.

Can zombies have meaningful lives?


Hacking Vehicles in Watch Dogs

Question: I have been playing Watch Dogs since it came out and i recently did the mission called "Not A Job for Tyrone" and my friend did this mission to. But what i wanted to ask about is how i hack a car. What i mean by that is, everytime i steal a car, i need to break the glass to get into the car. But my friend does only need to press Triangle (on PS4) and he just opens the car like if he has the keys to unlock it. But i do not have it. We've done the same missions and everything but still, nothing. Is it maybe because i haven't unlocked any ctOS towers? Thanks.
Answer: In Watch_Dogs you can use skill points gotten from missions and whatnot to get hacking skills, combat skills, etc. The first skill in the Driving tree is the ability to unlock all cars and disable their alarms when you enter.
Comment: @xPubHD the answer might be worth to be [accepted](http://gaming.stackexchange.com/help/accepted-answer) ;)
Answer: There is a skill required to unlock cars using your phone. To unlock the skill press up on your D-pad and select skills menu item. Go to the driving tree, the first skill unlocks vehicles using you phone.

Hacking Vehicles in Watch Dogs


How do I get rid of Snails, Slugs, and Earwigs

Question: My garden has a huge problem with earwigs, Snails, and Slugs, and many of my plants are dying. How can I effectively eliminate these pests.
Answer: Slug pellets will take care of the snails and slugs - earwigs are a different matter, they usually nibble on flowers overnight and an upturned pot on a stick or cane with straw in it near their favourite flowers should mean they're in there first thing in the morning. You empty the pots and straw into a bucket of water or the ground and stomp on the earwigs.
Neither of these pests will actually kill plants, although snails and slugs might demolish some plants just as they start appearing above ground by eating them immediately and repetitively till the plant gives up - hostas for instance, or delphiniums, certain vegetable plants, early in spring may suffer this. Otherwise, they don't usually kill plants, just damage them by eating them, and earwigs don't either, so more information is required if many of your plants are dying - like what the plants are, where they're growing, etc.
Comment: Perhaps I should edit the question, because they are not technically dying, they are just not doing very well and holes are appearing in the leaves.
Comment: @Just Wondering Ask a different question or add to this one - but include details of affected plants and photos if possible. But slug pellets might still be very useful, unless where you live has been hot and dry for ages
Answer: Ducks are best for snails and slugs, but chickens will work too, and will pick up the earwigs in a heartbeat.  Depending on the size of your garden one laying hen may be enough.  This will require some short term protection of new plantings, but will actually fertilize your flowers and other shrubs.
Another great technique that I have used with success is to half bury a bowl and pour a bit of beer in it, say half a can (I drink the other half, but if you don't like beer pour it all in).  The next day or some days later you can empty the bowl and pour fresh beer in.  You are likely to find slugs, snails and earwigs (and other critters) floating dead in the beer bowl.  They can't swim but must get thirsty.  Good luck!
Answer: Having given the chicken route a try, I'd only suggest it (and likely ducks as well, though I haven't tried them) in the "Bird moat" method where you ring your garden with a bird run, so critters trying to get in or out need to cross the "moat". Chickens certainly eat slugs and snails, but also scratch (dig things up) looking for other stuff, and eat tomatoes, tomatillos, and various other produce. And, of course, they roost at night when the critters you want eaten are most active. And various predators want to eat them, which can be both a hassle and disturbing.
If you do that, shelter/trap boards in the bird run can be highly effective - critters hide under them, you turn them over, the birds soon learn to be there when you turn them over to get the exposed critters. You can also use those in the same manner as the earwig trap already described (which the birds will help out with if you have birds) without poultry to eat the beasties if you just kill them yourself.
Answer: Chickens will deal with earwigs, I've heard, but they may also eat produce. I'm not sure about slugs and snails, but I imagine keeping the ground dry and free of excess vegetation might help.
Answer: Regarding on how to reduce the population of earwigs, I can suggest something that worked for us really well:

Pick a small plastic tray without holes in it, something like plastic vegetable tray or fish can.

Fill it with Olive oil up to 1cm deep. Add some soy sauce as it icreases the smell and attracts more earwigs.

Put this tray overnight under the plants which have the biggest problem.

In the morning you should see many dead earwigs in that trapping tray. You can pick those out and throw them away then set the trap for the next day until you are happy with the result. Earwigs are good at eating alphids so you don't want to get rid of them entirely but also you don't want to find many of them inside your favourite plant buds. Good luck!


What book had a character who could control magical strands or streams?

Question: I am looking for a title of a book, The main character could send out a "strand, stream?" of magic to retrieve whatever he wished.  If he wanted a beer he would get it and one would disappear elsewhere in the world. I know I read the book as a paperback, maybe in the mid to late 90's.
Answer: This sounds to me like Roger Zelazny's Trumps of Doom series. The principal character - Merlin of Chaos - accesses magic via the Logrus. When using this he visualises lines of magic extending from his hands, and on several occasions uses this abliity to draw beers to himself.
There are 5 books in the series, Trumps of Doom, Blood of Amber, Sign of Chaos, Knight of Shadows and Prince of Chaos.
Comment: He also retrieved corkscrews, swords, and on one memorable occasion a ladder which showed signs of having left an angry painter on the ground where it came from.
Comment: Oh, Thank You so much.  I have searched my memory and could not remember.  I KNEW it had something to do with Amber.  I recently purchased and started reading the collection of Amber Novels in one book.  I appreciate you answering my question.
Comment: see also this question about a related series: https://scifi.stackexchange.com/questions/32398/i-need-the-name-of-a-sci-fi-fantasy-book-series
Answer: The Wheel of Time series, by Robert Jordan

(and later picked up by Brandon Sanderson after the original author's death in 2007)

The strands are weaved into different spells - one can infuse orange scent (hopefully), another would slice armor in half, etc. They come in five different flavours - the classical five elements of spirit, air, earth, fire and water. The source of these is known as the Power, which is divided into two halves - one called saidar, which is the female half, and saidin, which is the male half and tainted by the Dark Lord.

 Until book 10.

It's a behemoth of a series, effectively quadruple the length of Lord of the Rings, and has much more diplomacy besides. I'd definitely recommend a few years to reading it.
Comment: I don't remember Rand, Mat, or Perrin ever sending out a strand of magic to get a beer and the beer disappearing somewhere else in the world.
Comment: Yeah, I am a huge fan of WoT, and while at first I thought this may be what the OP was asking for, I quickly realized it wasn't
Comment: the Lost Talent of beeretrieval?
Comment: It WAS Trumps of Doom.  BUT thank you for reminding me of this series as well as I read it when younger and would like to revisit that world as well.  I am taking a break from the computer and trying to read a little more.


How do I set up recurring donations?

Question: I'd like to be able to set up recurring monthly gift donations.  Is this possible with my CRM? Currently, we can accept one time gifts but can't seem to figure out how to take automatic monthly gifts.
Comment: You should explain which Payment Processor you are using as this is the key factor.
Answer: In what part of the world are you located? If it is in Europe you might need the CiviSEPA extension as well :-)
Answer: On any Contributions Page -> Contribution Amounts -> check the box labeled Recurring Contributions.
The details of how this will work depend on your Payment Processor.

How do I set up recurring donations?


Using the rectangular marquee tool with custom measurement scale

Question: Can one use the rectangular marquee tool in photoshop and specify a size based on the custom "measurement scale" specified in the "Analysis" tool.  I want to use it exactly like using the ruler tool when the "use measurement scale" box is checked.   Thank you
Comment: Are you trying to use the marquee tool to measure inches instead of pixels?
Answer: You can fix the size of the Marquee tool to whatever dimensions, in whatever units you want to use.

You can also use the marquee tool to measure units in Photoshop's default unit of measurement.


Are electric cars more efficient than gas-powered car (when considering entire energy cycle)?

Question: For the last couple weeks, I've been hearing a lot of talk surrounding Tesla and "the electric car". What I'm curious of is whether or not it is more efficient to actually power an electric car (the power produced by the power plant) over a typical gas powered car. Obviously there are a lot of variables, where you drive, how, gas mileage, etc. Which is more sustainable in terms of , electric cars or gas-powered ones?
Comment: I think this is pretty much a duplicate of [Are electric cars as environmentally friendly as we think they are?](http://sustainability.stackexchange.com/q/612/48) - the answers there answer your question here
Comment: see [this answer on EVs](http://sustainability.stackexchange.com/a/803/486).  yes, EVs are more efficient, even if all the electricity comes from coal.  if any electricity comes from renewables, EVs are even better.  no contest.
Comment: Whenever you centralize a resource you increase efficiency, as long as too much isn't lost in transfer. There are some other issues (battery production) which you might not find such optimism, though.
Comment: I think the questions are different - this one addresses simple efficiency comparisons, while the other includes factors such as pollution, LCA, etc. The answers don't necessarily reflect the difference, though.
Answer: In terms of energy for movement, the electric car is more sustainable. There are two main resons for that.
Firstly, when hydrocarbons are burnt to provide movement, local pollution is released: NOx, particulates, carbon monoxide, carbon dioxide.
And secondly, it's much easier to clean electricity, than to clean hydrocarbons. That's because the clean electricity resource is affordable and plentiful: solar, hydro and wind can together power the world many many times over.
Efficiency turns out to be a useful proxy, occasionally. But often it's misleading - it doesn't really get to the core of what we need to know. Electric engines are about four times as efficient as internal combustion engines. The efficiency of any wider system, would depend on where you draw the system boundary. And then you're adding up efficiencies that may or may not make sense. Wind, water and sunlight are free: does it make sense to include the efficiencies at which they are harvested? Efficiency is one of many things that affects the economics: but there are sufficient other factors that can more than make up for low efficiency.
Answer: There are several factors to consider:
1) How efficient is the generating station? In general, if any attempt is made to capture "waste" heat and use it for domestic heating or some industrial process, the answer is "very".
2) How efficient is the transmission system? This can vary quite a bit, both from location to location and over time. For example, a system under heavy load is less efficient than one under less of a load. As load increases, you get more heating of the cables.
3) How efficient is the charging system? Modern battery chargers are more efficient, but any time you change voltages or convert alternating current to direct current (or vice versa) you have losses.
4) How much is lost as the battery sits there? NiMh batteries are far better than lead-acid. Some of the newer technologies promise to be better still.
5) How efficient is the motor and drivetrain of the car?
6) And last, but certainly not least, how much energy went into building the car? The least impactful product is the one that has already been produced!
Of course, ultimately, the best answer is to ride mass transit, if you really must travel.
Comment: downvoted because this answer is not helpful - the OP may be aware of all these factors but was looking for data.  And your point 6 is outside the scope of the question.
Comment: @half-integerfan, none of the other answers include numeric data either. Only the comments do. Why pick on this one author? ... Regarding (6), it is absolutely in scope. We are not starting from horse and buggy days. People already have cars and might buy a Tesla to save energy before the previous car is at end of product life, which is likely to be counterproductive. Perhaps (6) should be removed from the list and put in a paragraph. I'll agree there. Items 1-5 are important factors to include in any unbiased analysis. ... Are you sure Dave's answer is inferior to the others? I don't see it.


How to recover a Word document mangled with TextEdit

Question: I opened a Word file using the TextEdit app, highlighted what I needed from the article, pressed "Save" and moved it to the desktop before I closed the file itself. And then I tried to reopen it but there was nothing highlighted and all of my work has been deleted!
Comment: Restore the file from a backup (e.g. Time Machine)!
Answer: TextEdit makes versions of files, so you should try that first using the File menu in the app.

File -> Revert To ->

If that fails, then go to your TimeMachine backup or other backup of that file.
Worst case, use spotlight to search for other copies of that file if you don't use either of the native backup options for reverting file changes on macOS.


Every subspace of $\mathbb{R}$ with the lower limit topology is separable

Question: Let us consider the lower limit topology $τ=\{G⊂R: (∀x∈G)(∃ϵ>0)([x,x+ϵ)⊂G)\}$ on $\mathbb{R}$. I am trying to show that any subspace of $(\mathbb{R},τ)$ is separable, but couldn't find the countable subset in a subspace $X$ of $\mathbb{R}$ which is dense. Any hint will be appreciated.
Comment: What sets have you tried? Do you know what standard set in the lower limit topology makes it a separable space?
Comment: Yeah $\mathbb Q$ makes $\mathbb R$ separable, but how to find a set with the help of $\mathbb Q$?
Answer: First, to show that a subspace $
\newcommand{\clrl}{\mathrm{cl}_{\mathbb{R}}}
\newcommand{\clsl}{\mathrm{cl}_{\text{S}}}
Y$ of a topological space $X$ is separable, it suffices to find a countable $A \subseteq Y$ such that $\overline{A} = \overline{Y}$ (and actually, $\overline{A} \supseteq Y$ will suffice).
(The idea presented below is not entirely dissimilar to the ideas in this previous answer of mine.)
I'll let $\clrl$ and $\clsl$  denote the closure operators on the real line (usual metric topology) and the lower-limit topology, respectively. Since the lower-limit topology is finer than the metric topology, then $\clrl ( A ) \supseteq \clsl ( A )$ for any $A \subseteq \mathbb{R}$.
Lemma: For any $A \subseteq \mathbb{R}$ the difference $\clrl ( A ) \setminus \clsl ( A )$ is countable.
proof outline. Given $x \in \clrl ( A ) \setminus \clsl ( A )$ there must be a $b_x > x$ such that $[ x , b_x ) \cap A = \varnothing$. We can show that $[x,b_x) \cap [y,b_y) = \varnothing$ for distinct $x , y \in \clrl (A) \setminus \clsl (A)$. Thus $\{ [ x , b_x ) : x \in \clrl ( A ) \setminus \clsl ( A ) \}$ is a family of pairwise disjoint nonempty open sets in the lower-limit topology, and since the lower-limit topology is separable this family cannot be uncountable. $\dashv$
Given $Y \subseteq \mathbb{R}$, to show that $Y$ as a subspace of the lower-limit topology is separable we first note that since the real line is second-countable (and therefore hereditarily separable) there is a countable $A_0 \subseteq Y$ such that $\clrl ( A_0 ) = \clrl ( Y )$. By the lemma above $Y \setminus \clsl ( A_0 ) \subseteq \clrl ( A_0 ) \setminus \clsl ( A_0 )$ is countable, and so $A = A_0 \cup ( Y \setminus \clsl ( A_0 ) ) \subseteq Y$ is also countable. It is fairly straightforward to show that $\clsl (A) \supseteq Y$.
Answer: Consider a set $X\subseteq\mathbb R$ with its relative topology as a subspace of the Sorgenfrey line $(\mathbb R,\tau)$. Let $\mathbb Q$ be the set of all rational numbers.
For each $r\in\mathbb Q$ such that $X\cap(-\infty,r)$ has a greatest element, let $x_r$ be the greatest element of $X\cap(-\infty,r)$.
For each rational interval $(q,r)$ such that $X\cap(q,r)\ne\emptyset$, choose an element $y_{q,r}\in X\cap(q,r)$. (Axiom of choice used here.)
Let $D=\{x_r:r\in\mathbb Q,\ X\cap(-\infty,r)\ \text{has a greatest element}\}\cup\{y_{q,r}:q,r\in\mathbb Q,\ q\lt r,\ X\cap(q,r)\ne\emptyset\}.$
Clearly $D$ is a countable subset of $X$.To see that $D$ is dense in $X$, observe that the topology of $X$ has a base consisting of all nonempty sets of the form $X\cap[a,b)$ where $a,b\in\mathbb R,\ a\lt b$, and that every such set contains an element of $D$.


use magento rest api to manage attribute sets

Question: i want to manage attribute sets of magento using rest api like i use to manage products (insert, update and delete). The resources in the rest api documentation http://www.magentocommerce.com/api/rest/Resources/resources.html are only for products, orders and customers. This can be achieved using the magento SOAP api but i want to do it using the rest api. Do i have to implement it myself or there is another way? please help!
Comment: I would say if it is not documented you can look in the source. But I would assume you have to implement it.
Answer: There is no REST api available for attribute sets (or attributes).
If you take a look at the Api2 folder inside the Mage_Catalog module you will see only files related to products ...so I guess you have to code it yourself.
If you do, please post the code somewhere. This should be a valuable resource for others also.


Payment refund processing

Question: Is there a better way to send a refund on the payment received via transaction_id? Or no other way but to send back a new payment operation  back to the sender?
Answer: I read the question as

Is there a method where I can provide a txn id and automatically refund the payment I received

The answer is no. You will have to issue a new payment to effect any refunds.
Additionally, a transaction is a sequence of 1 or more operations and may include zero, one or many payment operations. So it is not possible to precisely identify a payment by transaction id.
Answer: I assume you mean "transaction id" for "transaction_hash".
For all transactions, you have "transaction hash", "ledger num" and the "asset name". Unfortunately you cannot query the transfer using "asset name" at Horizon, so "transaction hash" should already be the best method available. (Note: For the same ledger, more than 1 transaction can occur, so "ledger num" is not a good choice for tracking.)

Feasible ways that I can think of (via Laboratory):

[Effects] > [Effects for Transaction]
https://horizon-testnet.stellar.org/transactions/{transaction}/effects
[Operations] > [Operations for Transaction]
https://horizon-testnet.stellar.org/transactions/{transaction}/operations
[Payments] > [Payments for Transaction]
https://horizon-testnet.stellar.org/transactions/{transaction}/payments
[Transactions] > [Single Transaction]
https://horizon-testnet.stellar.org/transactions/{transaction}

In Stellar-core DB, it seems there is no direct data for what your transaction has done.
In Horizon DB, there is a table [history_effects] that you may query with "history_operation_id". But normally you cannot deduce the "history_operation_id" directly, so it seems that "transaction hash" is the most direct for your usage in this case.

Among these choices, IMO #2 gives the best visual output.
<code>    "id": "542613283278849",
    "paging_token": "542613283278849",
    "source_account": "GCHBJBKTQJ5IKCF2R374NPISYD75Z5DB77XHJ6JWKESASXT5OEON4KQ5",
    "type": "payment",
    "type_i": 1,
    "created_at": "2018-03-13T10:13:52Z",
    "transaction_hash": "bae8c989688785ede07ffd621820a29651343869090672e49beb58d53947cedf",
    "asset_type": "credit_alphanum12",
    "asset_code": "Ass1to0",
    "asset_issuer": "GCHBJBKTQJ5IKCF2R374NPISYD75Z5DB77XHJ6JWKESASXT5OEON4KQ5",
    "from": "GCHBJBKTQJ5IKCF2R374NPISYD75Z5DB77XHJ6JWKESASXT5OEON4KQ5",
    "to": "GDIUCAJMCX6RUM7VRDHENY6I3M3OLORLKVOXOTSEYQV5DYPUKU3HL4AL",
    "amount": "0.9000000"
</code>

Payment refund processing


File Vault Paused

Question: Im trying to update to High Sierra, But can't because my file vault is currently encrypting. (so says the error message) However, when I check the status, it shows that it is "paused" and has been like that for over a week. Ive looked around, troubleshooted as much as i could and can't get anything to work. Ive tried the Sudo command and repairing the Disk... Nothing works... PLEASE HELP.
Answer: Is this an Apple laptop? If so, you need to connect it to a charger for the encryption to continue.

File Vault Paused


Act first as fast as you can and surprise in real fight

Question: I heard that winning a real life street fight depends on your action in the first seconds. If you have to fight for longer time the probability of winning decrease dramatically. Is it true. How can you prepare yourself for the surprise in real street fight and is the phrase "Act first as fast as you can and surprise your rival". Are the real examples or video that can show how to prepare yourself for dealing with the surprise and fast reaction?
Answer: TL;DR The duration of a fight bares no relation to the risk of injury as clearly demonstrated by countless matches. Attacking first leaves one open to very serious legal repercussions. Expecting to be attacked at all times and places is a mark of paranoia.

The duration of a fight has nothing to do with your probabilities of being injured.
The nature of the attack does.  If the attacker wants to kill, they will stab/shoot to kill. The aim is to kill the target and leave. If the hit fails, they will try again later. If the attacker's aim is to inflict pain, then they will only stop if either when they have inflicted enough damage (whatever that is) or they are taken out. In both those cases, expect the attacker to plan the ambush in such a way as no matter what the victims does, they cannot escape.
The skill of the attacker does.  If the attacker is a wee mean drunk unable to stand, their attacks are not going to hurt. Just dodge. If the attacker is Chuck Norris... Well, we know how that ends. I heard that a rattle snake bit Chuck Norris and after three days of agony, the snake died.
The proximity to your mates does.  If all your mates from the martial art club, marines, and special forces are a minute away, the longer the fight lasts the less chances you are to get hurt. You are more likely to get hurt in the first minute than the tenth!
Boxers, MMA, and other contact sport demonstrate this all the time: The longer a match last, the more injury?  Nope. The longer a match last, the more the pair are evenly matched.
You might argue that someone trying to kill you is not comparable with a MMA match. That is fair. However, not all self defence situations involve someone trying to commit murder. A bar brawl is most of the time less violent than an MMA match due to the practitioners lack of coordination and skill.
Act first, act fast is utter rubbish.
It is one of the common tropes that gets totted by deluded people who claim to know anything about self defence. It reads sensibly in the face of it but as soon as you think about it in depth, its sheer stupidity comes to the front.
I am not lawyer, nor do I play one on TV.
Acting first makes one the attacker. The situation was escalated form an argument (possibly loud and obnoxious) into a physical confrontation. Any LEO will arrest whoever started threw the first punch. Prosecutors will argue that the attacker is a violent individual and Judges will listen to them. After all, the attacker does a violent sport those aim is hurting people -- a skewed definition of martial arts.
Self defence does not give one unbridled rights to hurt, main, cripple, or kill one's attacker. What the legal definition of self defence is varies from country to country. If you want to know more, talk to your local lawyer/solicitor.
Self defence law is complex and depends on your locality. Anyone claiming that their magic formula will save you from legal ramifications is conning you. Whether you are hit first, threatened with a weapon, or assaulted verbally, does not give you a carte blanche to act like a thug. If you want to know more, talk to your local lawyer/solicitor.
In addition, people who rely on either violence or the threat of violence to resolve any confrontation are called bullies. It makes one a despicable person most people do not want to associate with.
However, even if it were a good idea legally, the statement would still be utter rubbish form a training point of view: no one walks around expecting hidden and invisible ninja attacking them at any moment. It is impossible. Even soldiers in the middle of battle have trouble detecting attacks. And they are trained for combat. After some time, PTSD starts affecting them -- or combat fatigue, whatever you want to call it.
Let's assume you want to go down that path.  You have to watch for ambushes, expect the worst of all strangers, and watch out for hidden dangers all around you. This is what the medical profession called paranoia.
Now, in your paranoid state you thought someone is coming close to you, hands in pockets. Is he going to stab you? Yes, quiet possibly. So, react first: pick you gun and preventively shot him in the face! What if you get it wrong? What if that guy just did not see you and bummed into you. He was thinking about his wife and what she wanted for their anniversary, just not paying attention to his surroundings...
Is that how you want to live? Always afraid for your life, never being able to stop and rest. What kind of life is that?...
Of course, you can come up with lots and lots of imaginary situations where this advice saves your live. But they remain imaginary. In real life, this advice is utterly useless.
Answer: "Winning" in self defense is whatever makes you safer.
Within that context, if you can get yourself out of danger, sooner, with more reliable methods, that's better.  If someone is trying to hurt you, you don't know if they have friends on the way, if they're going to pull out a weapon or make something into a weapon and so on.
However, "first few seconds" is only true under specific contexts.
For example, many dangerous situations involve warning signs or indications that last several minutes.  For example, a lot of fistfights between men start with people trash talking or yelling at each other... and instead of leaving, people hang around or engage (not taking themselves FROM danger...).
A lot of advice around awareness involves people having to take proactive action as soon as something feels off.  It's really applying the diver's philosophy of an Incident Pit to personal safety.
On the other hand, a fast assault by surprise, you really only have a few seconds at most - someone is attacking you, by surprise, and possibly with weapons or allies.  Reversing surprise in this case, involves you deciding to act before them, or throwing an unexpected factor into their plan.
There is no easy solution to assaults where the odds are stacked against you - if there was, it wouldn't be bad odds, right?  People spend years trying to develop methods and reaction that allows them to navigate these problems quickly and better.  Some of that is having methods you can use quickly and without much thought, and some of it is learning to identify danger quickly to take action - avoiding that incident pit and having the option to get out of trouble long before you are stuck with "mere seconds to act".
Answer: Real fights are not constrained by rules. There is no referee to pull you apart from a clinch, or rules against bashing the back of your head. Nothing prevents multiple people from attacking. There is no padding. If someone puts you on the ground, they can stomp you.
Real fights are not like the movies, where people are bashed in one sequence and immediately get up to keep going. Fights can end in one punch. You cannot assume that after you get hit in the face you will be able to continue.
Skilled fighters will not waste time once they are in contact with you. Given time, they will find a hole in your defense and hit you or unbalance you, which creates a bigger hole that they will quickly exploit. Trying to defend continuously against an attacker of comparable skill is a losing proposition.
So what does this mean? You have to act like the fight can end at any instant. If you are already in contact, you must counter immediately, or you may not get a second chance. The fight may not actually end quickly, but you cannot plan for a later that may not come.
Answer: All the answers here are valid but I would like to add some Info from another perspective to the questions.
From my experience, I would say that your statement with "who first strikes" wins the game, is true - to some point.
It is valid for a specific type of aggressor, someone unprepared that might had a couple of drinks, maybe trying to show off in front of some girls etc. That kind of bad guy-behaviour can be cured by a punch-first aid if prepared properly. By that I mean to be effective in your intention, you have to distract your aggressor from his intention to catch him in an unprepared moment and lign him up for your best shot.
Bad luck if he is a berserk and still starts to continue his attack. However you could practice your best punch and that kind of situation to perfection and at least to get the chance to get some time and get towards safety.
This is all valid if you can't avoid a fight under any circumstances!! Best would be to move away from the guy...
But if your aggressor is someone who is prepared to be punched or simply doesnt care, you are best adviced getting away as fast as possible and a preventive strike helps you to get away from the danger zone.
If you are surprised by the attack, you will not be able to execute the first punch anyway :-)
One idea on training that kind of situation would be to get together with some friends with the same mind set and agree in randomly surprise each of you being attacked by the others at different situations and circumstances.
The attackers should use gloves and head protection of course.
Have fun.
Comment: Your view of the law is naive.
Comment: If you throw the first punch, *you are* the aggressor.
Comment: @sardathrion - what do you suggest then? Wait for the first punch and act upon that? That is naive and surely not  what I would recommend anybody. It depends on the circumstances how to react. If you can avoid it - for sure avoid it. If you cant and see no other chance to get out - be the first who reacts. That is my personal opinion!
Answer: Avoidance is the Best Defense
Be aware of your surroundings. You're in a parking garage, fumbling with your keys, and you see someone running towards you, who appears less-than-wholesome (and you're unsure if you can get into a safe place before they arrive)? Run away! Someone pulls a knife on you? Run away! Do you have a choice between well lit, well traveled streets and dark, dangerous alleyways? Take the well lit, well traveled street. The best way to defend against a particular situation is to not get in it.
You can't hurt what isn't there.
Comment: Strawman argument? You are right, you never said "run away from safety!" and neither did I criticise you for saying (or not saying) it. Running willy nilly could end you in more trouble hence running towards safety. In your parking lot example, run towards the exit where there's a guard not deeper into the garage. 'nuff said.
Comment: I would say *run towards safety* instead of away.
Comment: @Sardathrion At no point did I ever say "run away from safety!" You could misconstrue the "fumbling with keys" situation for this, but I was seeing a situation where its unclear if you can get into your car/door before the attacker gets to you. I'll change that.
Answer: Reading these answers I have to ask how many real fights some of the posters have been in...
A lot of what's taught in self-defence classes goes out the window when it happens for real, and as for avoidance being best, a lot of the time you won't be able to avoid it if it happens.
Going in fast, hard and aggressive is the best way to handle it in my experience - no fear or hesitation, just be confident and get the job done.  The quicker the better.  As soon as you start dithering and showing any doubt that's when it can go wrong.
True, you can tell in the first few seconds of confrontation how it's bound to go, and only with having done it before a few times can you control the fight-or-flight response.
Answer: In some parts of 'third' and 'forth' world countries, the notion of a 'fair fight' is not the norm.  A dozen guys with weapons will attack an unarmed guy. A grudge may be settled with one guy arguing with the target, and his buddy comes up behind the target and stabs him in the back. A woman was pissed at her old boyfriend and while her friend was distracting him, she went behind him and sliced his arm nerves, leaving them helpless.  These are true stories.
People who live in such places don't usually advertise that they even know 'fighting.' I know of several experienced 'fighters' who go to such places for visits or permanently and they tell no one of their past.
In USA, in general, there's an epidemic of rudeness, that one can shoot off their mouth all they want. Another true story in one of the above 'tough places': an American MD was vacationing and while walking, cussed out some guy in a car.  The guy just got out of his car and severely damaged the doctor's teeth.  Does this mean one should be 'paranoid'?  Or do you call it smart? Well, you can just study the random attacks of street guys who run up behind someone and pummel them.  Or intent to kill someone just to join a gang.
There is a big difference in walking around with potential panic, seeing threats at all sides, and being  aware.  No, you have to discern what is just bad behavior and a potentially dangerous situation.  Further, you have to remember that an experienced mugger (or one, who has been in the front row seat at a 'gladiator school' in a prison) will follow rules.  He may be completely high, and just want to cut someone, for no reason.  If it is just an ego thing, that's something you should be able to walk away from. If you can't walk away, then, yes, don't react, but act first.
As for all the legal ramifications, everyone must decide for themselves beforehand.
Will I risk myself (or a loved one) maybe being seriously hurt or maimed for life, or even killed, by this nice stranger who is just offering to help me with my bags?
A good book is the Gift of Fear... not 'panic' but trusting your gut.  In the previous example, if something tells you something's not right, then say no thanks to the 'help.'  If he persists, then your red flag should be up.  As a closing personal example, a friend of mine was in one of these third world countries and attacked by a guy with a knife.  He took the knife away, and killed the guy.  No cops came knocking on his door.  If he had hesitated, 'maybe this guy wants a cigarette' he would not be here today.


Encoding variable number of categorical features

Question: I have a dataset listing the software installed for each user. This dataset shall be used (in conjuction with other user datasets) to classify the user into 4 (imbalanced) categories.
There are over 1000 different pieces of software. Each user can have between 15 and 40 pieces of software installed. In fact, the same software can be counted as installed multiple times (I presume this refers to different versions/upgrades of the same software but I'm not sure).
The naive approach (A) would be to use one-hot/dummy encoding for a variable "Software" but this would produce over 1000 features.
A slightly more sophisticated approach would use some sort of feature selection (e.g. using chi-square/mutual information or some wrapper model) and ignore the less informative pieces of software.
And a third one would be to use target/mean encoding.
Which of these would you recommend?
My preference is for target/mean encoding but I wonder how to approach it.
I was thinking initially to just sum up the raw counts for each target value: I'd create 4 features each one corresponding to one of the values of the dependent variable and for each of these I'd count the times the particular software was installed and then sum up over all software installed by the user. The problem is that in this way some popular software (e.g. Word or a browser) will likely "crowd-out" some less commonly used (but potentially more informative) pieces of software. So next I thought that I could replace the raw counts with the percentage. This would give equal weight to each piece of software. But is this OK?
I guess I am probably not the first person to face such a problem. What would constitute a principled/established approach of dealing with such variable number of high cardinality categorical features?
Comment: You could group all software into N groups and then use the number of apps within a group as a feature. I recommend using domain knowledge.
Comment: Non-negative matrix factorization of the dummy-encoded data would give natural groupings of software that goes together in your user base.
Answer: You did not specify a target variable to predict/classify. If you have that I would look into the (fused) lasso, see Principled way of collapsing categorical variables with many levels?. See also Is the LASSO really applicable for binary classification problems?, another idea in Strange encoding for categorical features.
Without a target variable, this is more like clustering.


What was Leopold Kronecker's philosophical view which guided his mathematics?

Question: Leopold Kronecker (1823-1891) rejected Georg Cantor's (1845-1918) transfinite numbers and sets; he also rejected infinitesimals as well as other mathematical entities - such as transcendental numbers. What was his philosophical view from which he derived his rejection of various mathematical entities? (Or rather, did he reject the mentioned entities based on mathematical arguments?)
Answer: See:

Anne Troelstra & Dirk van Dalen, Constructivism in mathematics: An Introduction. Volume 1 (1988), page 17.

There is no "explicit" philosophy of mathematics in Kronecker's works.
He may be regarded as a "constructivist", or perhaps as a precursor of the finitist approach.
In his essay "Uber den Zahlbegriff" (1887) he outlined the project of "arithmetizing" Algebra and Analysis; that is, to found these disciplines on the fundamental notion of number, avoiding thus geometrical intuition.
In his arithmetization project he considered a mathematical definition acceptable only if it could be checked in a finite number of steps, criticizing the "pure" existence proofs. He stated that an existence proof for a number could be considered correct only if it contained a method to find the number whose existence was proven.
Some of his remarks belong to mathematical folklore, like his widely reported statement that:

"the Lord made the natural numbers (ganze Zahlen), everything else is the work of men";

the same idea is reiterated in the following statement:

"I consider mathematics only as an abstraction of the arithmetical reality".
Answer: Here are some philosophical statements of Kronecker from his Public lecture in summer semester 1891 at Berlin – Kronecker's last lecture. "Sur le concept de nombre en mathematique":

The whole mathematics is there to be applied.
Mathematics is a natural science – not better, not more complete, and not simpler the phenomena can be described than mathematically.
All considerations and speculations about the magnitudes which are defined as limits fail, as soon as there are multiple limits.

And here is his Credo:

I believe that we will succeed one day to "arithmetize" the whole contents of all these mathematical theories, that is to base it solely on the concept of number in its stricter sense, i.e., to get rid of the added modifications and extensions (namely the irrational and continuous magnitudes) which mainly have been caused by the applications on geometry and mechanics. [Leopold Kronecker in K. Hensel (ed.): "Leopold Kroneckers Werke" III, Teubner, Leipzig (1895-1931) p. 253]


SD card supported by Android 4.2.2

Question: I bought a HTC 310 Desire running Android 4.2.2 (Jelly Bean) and would like to format my SD card (SDHC 32GB) so to be able to contain files larger than 4GB.
I tried formatting the card exFAT, NTFS, ext2, ext4 (using the utility of my Windows PC, of a MAC and using MiniTool PartitionWizard) but when i place back the card into the phone, the phone keep saying that the card is damaged and propose to reformat it. If I accept the card will be formatted as FAT32 (i.e. no file larger than 4GB possible).
Do you know what can be done? Possibly without rooting the phone?
Is there somewhere a list of the file system supported by my phone?
Or is there something special to pay attention to in the card formatting?
Answer: I have looked into this issue before, and as it stands at the moment, native android does not support exFAT or NTFS.
Support for additional formatting types are included in some ROMs because they have been specifically coded to do so such as AFAIK which I believe supports NTFS.
I think you are stuck with FAT32 unless you wish to root and flash a ROM that supports alternative formats.
Comment: @luca The main problem with exFAT is that it is [patent encumbered](http://en.wikipedia.org/wiki/ExFAT#Restrictive_licensing_and_software_patents), so many manufacturers choose not to support it in order to avoid paying licensing fees. Samsung often supports it, and Sony apparently did (for your Xperia Z3, at least), but HTC may not.
Comment: I fear you are right. No support for anything else than FAT32. Nevertheless I recently managed to format a SD card as exFAT and make it recognized on a sony xperia z3 android 4.4.4. In that case formatting with the Windows tool and MiniTool PartitionWizard did not work while formatting with MAC did work. So I hoped that finding the magic formatting parameters I can still make it working. Or maybe is my phone and it's android version the cause of the problem?

SD card supported by Android 4.2.2


Task from Workflow questions / issue

Question: I have a question in regards to the user the system uses when assigning a task from a workflow. I have a workflow on a field in account and if this field reach 90% the workflow fires. This workflow will create a task for the account owner of that account that has reached 90% on that specific field.
If I use the "Notify Assignee" on the Edit Task section, an email is send to the account owner with a template that it can't be modify. I said it can't after doing a search on this matter. But, what about the user that the system use to send that email notification?
I thought that I could change that by changing the Edit Organization-Wide Email Address in Email Administration, but is not picking that email.
Anyone knows from where the task "Notify Assignee" gets the user to be utilizes on the task's email notification template?
This user also shows up in the new Task as the "Created By". Any ideas how can I modify this?
Thanks
Answer: I think it's the default work flow user or the user who triggered the work flow to fire. Other than changing the default work flow user I don't think you can influence this in work flow rules.
The organisation wide email addresses are for allowing users to send email from a generic email address from within Salesforce e.g.  firstname.lastname@example.com rather than their own.

Task from Workflow questions / issue


How do I test if a given policy was successful?

Question: I have some data for medical R&D and sales, my professor has asked me to check if a policy implemented in 2016 has made any effects on R&D and R&D/Sales data.
I tried to plot growth rates over years, but he says we don't need growth rates, and it has to be solved just by mean R&D expenditures each year. (Mean over multiple companies). How do I go about significance testing of policy change?
Comment: There really is not enough information to answer, but you might consider: (a) what was the policy aiming to achieve? (b) what happened? (c) would it have happened anyway? Perhaps you are not expected to answer (a)
Answer: Let us assume a balanced panel of companies $i=1,...,N$ observed in time periods $t=1,...,T$.
Let $s_{it}$ denote R&D expenses for company $i$ time $t$ and let
$$\bar s_t :=\frac{1}{N} \sum_i s_{it},$$
denote the time $t$ average.
Consider now a simple regression model
$$(1)\ \ s_{it} = \beta_0 + \beta_1I[t\geq 2016] + e_{it}$$
where $I[t\geq 2016]$ is indicator for the time being after policy implementation. I assume the policy is intended to stimulate R&D investments by companies and hence we assume $\beta_1>0$ if the policy has effect.
Using the normal equations for POOLED OLS estimator it is easy to show that
$$\hat \beta_0 = \frac{1}{NT_1} \sum_i \sum_t s_{it}I[t< 2016],$$
where $T_1$ is number of time periods before treatment. Hence $\hat \beta_1$ is roughly the average R&D expense level BEFORE treatment/policy implementation.
If model (1) is true then $plim \ \ \hat \beta_0 = \beta_0 = \mathbb E[s_{it} \lvert t<2016]$ which is the expected level of R&D expenses for any company for any year before treatment.
You can also show that
$$\hat \beta_1 = \frac{1}{NT_2} \sum_i s_{it} I[t \geq 2016]-\frac{1}{NT_1} \sum_i \sum_t s_{it}I[t< 2016]$$
If model (1) is true then $plim \ \ \hat \beta_1 = \beta_1 = \mathbb E[s_{it} \lvert t\geq 2016]- \mathbb E[s_{it} \lvert t<2016]$ which is the expected level of R&D expenses for any company for any year AFTER treatment.
You could plot the series $\{s_t\}_{t=1}^T$ and get - if model (1) is true - something like this

However something else may be happening over time and while you do not have any control group of companies not affected by the policy implementation you can still potentially do better than estimate model (1).
Consider the following plot

where in each time period going from $s_t$ to $s_{t+1}$ there is a small increase in R&D let us call it $\lambda$. Then in the year of treatment the increase is slightly smaller.
The blue and read line are found using the estimators above and it is clear that because they do not take the time trend into consideration they overestimate the effect. The data used for the plot was generated after the model
$$s_{it} = \beta_0 + \lambda \cdot t + \beta_1 I[t\geq 2016] + e_{it},$$
which includes the time trend.
Here in this model the effect is immediate. But the effect could also happen in the years after the treatment instead of only in the year of treatment hence you could have a model like
$$s_{it} = \beta_0 + \lambda \cdot t + \beta_1 I[t\geq 2016] + \beta_2 I[
t\geq 2017]+ e_{it}.$$
The take away is that you should do as the professor says and calculate the time averages $s_t$ and plot them and look at them. Paying particular attention to what goes on around in the year treatment and in the years close to but still after treatment (based on the principle that effect comes after cause and takes some time be fully realized)
I R to simulate data and generate the plot by means of the following lines of code:
<code># simulate panel of RD
library(data.table)
set.seed(1)
N <- 50 #Number of firms
T <- 16     #Number of time periods
TT <- 9 #policy implementation year (treatment year)

b_0 <- 5
b_1 <- 2

# Simulate model (1)
s <- b_0 + b_1 * (1:T >= TT) + rnorm(N*T)

# Make dataset
id <- rep(1:N,each=T)
time <- rep(1:T,N)
I <- as.numeric(time>=TT)
mydata <- data.table(id,time,s,I)

# Compute time averages
time_agg <- mydata[,.(s_t=mean(s)),by=time]

#Plot time averages
plot(time_agg$s_t,ylim=c(0,10),pch=20,xlab="time",ylab="R&D")
points(1:TT,rep(b_0,TT),type="l",lwd=1,col="blue")
points((TT):T,rep(b_0+b_1,T-TT+1),type="l",lwd=1,col="red")
savePlot("plot1.jpg",type="jpg")

# Simulate model (2)
s <- b_0 + b_1 * (1:T >= TT) + 0.5*1:T + rnorm(N*T)

# Make dataset
mydata <- data.table(id,time,s,I)

# Compute time averages
time_agg <- mydata[,.(s_t=mean(s)),by=time]
model <- lm(s~I,data=mydata)
hat_b_0 <- coef(model)[1]
hat_b_1 <- coef(model)[2]

#Plot time averages
plot(time_agg$s_t,ylim=c(5,16),pch=20,xlab="time",ylab="R&D")
points(1:TT,rep(hat_b_0,TT),type="l",lwd=1,col="blue")
points((TT):T,rep(hat_b_0+hat_b_1,T-TT+1),type="l",lwd=1,col="red")
savePlot("plot2.jpg",type="jpg")
</code>
Answer: I supose you are expected to compute some kind of regression showwing how (if) changes in R&D expenses effect changes in sales in a certain temporal lapse.
Answer: The big problem is identification. You don't know if the change in R&D was due to the policy change or to other changes that happened around the same time (e.g. discovery of INSERT_SOMETHING_THAT_WAS_DISCOVERED_IN_2016).
Suppose you have a counterfactual you think makes sense... let's say the policy was implemented to only companies whose names start with an "A", then you could look at how these companies perform differently than before (say, R&D spending in 2017 compared to 2015) compared to how other companies do on the same measure. If treatment was random, then you could attribute the difference of the difference to the policy. Read more here.
You could also think about using the growth of R&D before- and after-policy, i.e. growth of R&D spending from 2016–17 compared to growth of R&D from 2015–16, compared to other companies. Read more about this (sometimes called diff-in-diff-in-diff) here. Without details given, it's hard to say which would be more suitable.
As I said, the challenge is identification. It has hardly happened that policy was applied randomly (unless the policymakers are really into knowing the effects of their policy). Suppose the policy was applied to one state but not the other, using R&D for firms in another state as control might confound effects from other changes that also happen in the states around the same time as well.
Answer: I am assuming your challenge is to establish a claim of causality between the policy and the R&D/sales metrics. Maybe you can replicate some version of impact assessment studies. You will need data for before and after policy change. But this method will need a control group. Since you are trying to do an ex-post analysis, this might be difficult.
Alternatively, you can use scenario analysis. With this, you will be comparing two scenarios: with and without policy change. The former is your intervention scenario whereas the latter is your baseline scenario. For the baseline scenario, you will need to decide if there might be any other policy that will be implemented or continued.
You might also need to consider how different policies interact with each other. For example, some policies are complementary and enhance the outcomes for both. Some are antagonistic and cancel each other out. And some are redundant. Moreover, sometimes there is a time lag between policy implementation and its effects.