Ideal of the twisted cubic

Question: The twisted cubic is the image of the morphism $\phi : \mathbb{P}^1 \to \mathbb{P}^3 , (x:y) \mapsto (x^3:x^2 y:x y^2:y^3)$, it is given by $X = V(ad-bc,b^2-ac,c^2-bd)$. Now I would like to compute $I(X)$, which equals by the Nullstellensatz the radical of the ideal $I := (ad-bc,b^2-ac,c^2-bd) \subseteq k[a,b,c,d]$. I think that that $I$ is already a radical ideal, even a prime ideal. Namely, I suspect that
$$\phi^* : Q:=k[a,b,c,d]/I \to k[s,t] , a \mapsto s^3, b \mapsto s^2 t , c \mapsto s t^2 , d \mapsto t^3$$
is an injection. If this is true: How can we prove that? I've already tried to find a $k$-basis of the quotient, but this turned out to be a big mess. Even the representation of the quotient as a monoid algebra doesn't seem to help. Another idea is the following: A formal manipulation of generators and relations implies $Q_a \cong k[a,b]_a$. Thus it suffices to prove that $Q \to Q_a$ is injective, i.e. that $a$ is not a zero divisor.
Comment: Checking your map is injective is more or less the same as finding the relations that present the subsemigroup of $\mathbb Z^2$ generated by vectors $v_1=(3,0)$, $v_2=(2,1)$, $v_3=(1,2)$ and $v_4=(0,3)$. Can you do that?
Comment: @Mariano: I've already indicated that I've tried the monoid approach, but that it doesn't work without many case distinctions etc. ...
Answer: Here is a purely algebraic proof that $I(X)=I$.
It is of course sufficient to prove that $I(X) \subset I$ and for that it suffices to prove that every homogeneous polynomial $P(a,b,c,d)$
which vanishes on $X$ is in $I$.
Lemma
Any homogeneous  polynomial $P(a,b,c,d)\in k[a,b,c,d]$ can be written $$P(a,b,c,d)=R(a,d) +S(a,d)b+T(a,d)c+i(a,b,c,d)  $$  for some polynomials $R,S,T\in k[a,d]$
 and a polynomial $i\in I$
The easy proof is by induction on the degree of $P$ and I'll leave it to you.
Now  back to our problem. If now that homogeneous $P$ is in $ I(X)$ , we write it as in the lemma and  get by using that $P$ vanishes on $X$ that for all $(x:y)\in \mathbb P^1_k$   $$0=P(x^3,x^2y,xy^2,y^3)=R(x^3,y^3) +S(x^3,y^3)x^2y+T(x^3,y^3)xy^2+0 $$
By considering exponents modulo $3$ for $x$ and $y$, we see that no cancellation occurs, hence  that $R=S=T=0$ and thus  $P=i\in I$ as required.
Comment: Ah, thanks! Actually this shows that $\phi^*$ is injective.
Comment: Amazing proof! Also a very elegant way to prove the lemma!
Comment: Very nice! A way that made the lemma intuitive and easy to see (at least for me) is just to consider the polynomial $P(a,b,c,d)$ in the ring $k[a,b,c,d]/I$. It becomes quite obvious that we can substitute out all the higher powers of $b$ and $c$ — don't even really need induction.
Answer: The ideal $I$ is prime if and only if its associated projective scheme $V_p(I)\subset \mathbb P^3_k$ is integral.
This in turn can be checked on the four standard affine open subschemes covering $\mathbb P^3_k$.
For example in the affine open subscheme (isomorphic to $\mathbb A^3_k$) $U_d\subset \mathbb P^3_k$ corresponding to  $d=1$, the scheme $V_p(I)\cap U_d$ is defined by the ideal $(a-bc,b^2-ac,c^2-b)$ which is trivially prime in $k[a,b,c]$.
Three similar calculations will imply that indeed the original ideal $I$ is prime.
Comment: This may seem to be a trivial question, but why does your claim in the first sentence holds? Don't you "forget" the origin at which some zero divisors may be "supported"? In terms of commutative algebra, I think that your argument only shows that $\phi^*$ is an isomorphism when localized at $a$, $b$, $c$ or $d$; but why does this suffice? Also, is there any elementary proof which doesn't use scheme language (I'm just asking because I would like to present this to students which just have started to learn the concept of classical varieties, which are always reduced).
Comment: Being reduced is a local property, but being integral is not. So I doubt that it suffices to show that each affine chart is integral. But even if I just want to prove that $I$ is reduced: Why does it suffice to prove that $V_p(I)$ is reduced? Doesn't this only say that all the localizations $Q_a,Q_b,Q_c,Q_d$ are reduced? I agree that they are reduced (in fact, localizations of polynomial rings), but why does this imply that $Q$ is reduced?
Comment: Okay but irreducibility is trivial because it's the image $\phi(\mathbb{P}^1)$.
Comment: The first sentence is only true if $I$ is a saturated ideal. For example, $(x_0^2, x_0 x_1) \subseteq k[x_0, x_1]$ is not a prime ideal but it defines the same closed subscheme of $\mathbb{P}^1$ as the ideal $(x_0)$; this closed subscheme is integral.
Answer: There are several algorithms that can compute whether your ideal $I$ is prime or not, most of the algorithms use Groebner basis. I gave your ideal to a maple package, namely PrimDecomp, obtainable from http://wwwb.math.rwth-aachen.de/~markus/ and it says that your ideal is prime.
Comment: If you have questions about this, feel free to contact me or the author. It's not my peace of software, but from another guy in my department. Also you can send messages in german.
Comment: Dear sebigu, the ideal $I(X)$ is certainly prime, since $X$ is irreducible. The question is whether $I$ is prime (and the answer is "yes").
Comment: You are right, but I also typed in the generators for $I$, since only they were given. I will correct my answer.
Comment: I had already checked with Sage that it is a prime ideal if the base field is $\mathbb{Q}$. Do the algorithms also work over arbitrary $k$?
Comment: They wont, but since all coefficients are $1$ or $-1$, it suffices to check $\mathbb{Q}$ or, here, $\mathbb{Z}$.
Comment: You seem to claim that $A \otimes_{\mathbb{Q}} k$ is a reduced $k$-algebra when $A$ is a reduced $\mathbb{Q}$-algebra - but this wrong.
Comment: You are right. I thought that $X$ is defined over $\mathbb{Q}$, but it need not to be irreducible for every extension of $\mathbb{Q}$. So my answer only holds for $\mathbb{Q}$ and suitable extensions. Sorry for that.
Comment: This is an example on page 389 of Ideals, Varieties and Algorithms, by Cox, Little and O'Shea. It turns out in this case the affine basis in Georges' answer is already Groebner, and hence the given homogenizations generate the homogenization of a prime ideal, which is prime.

Ideal of the twisted cubic


Residuals vs Fitted does not meet linear regression assumptions

Question: I am having trouble moving forward with my Data analysis. I found a similar question (Residual vs Fitted) but (unless I am overthinking it) it does not apply to my issue since my data is not discrete data.
In short: I have 5 tags (each with 36 replicates), each of which were placed out in the field in 3 separate plots for a month and assessed at one week, two week and 4 week timepoints:
Ex Data:
<code>        Tag# Plot#  Mortality Timepoint

         1    1       5         1

         2    1       0         1

         3    1       98        1

         1    2      100        2

         2    2       20        2

         1    1       80        3

         2    1        0        3
</code>
The Model I ran was :
model5 = lmer(Mortality ~ Tag + (1|Plot) + (1|Timepoint),
              data=Dataset)
This was the best model after comparing a couple others, with less random effects and no random effects, AIC values. My dependent variable is Mortality with Tag as my main independent variable.
This is the residual vs fit graph I get:

And the QQ Plot:

From my understanding the Resid vs Fitted violates the assumptions of linear regression. From there I do now know what to do. I tried a couple transformations but they did not help. Does anyone have any suggestions for what model would be best to run?
Comment: What is the reason you do the linear regression?
Comment: Its the model I was recommended to run by a colleague but from my observations here it does not fit. I would not know which other model to run. I want to find if there is or  isnt a correlation between tag and Mortality. From my understanding regression analysis is what I should do and the way the experiment is set up it makes sense to include plot and timepoint as a random effect. But Linear regression does not seem to be the right choice. Open to any help/suggestions
Comment: What assumptions do you feel are violated?
Comment: From my understanding the points in the residual vs fit plot should be randomly distributed around the 0 line showing constant variance. Not a pattern such as the diagonal trends pictured.
Answer: You are correct that your residuals plot suggests you are violating the heteroskedasticity and normality assumptions. The first one is really the worst here. The residuals are more than correlated. They are basically linear.
I would like to point out that while you have coded tag and plot as numerical values, they are actually categorical variables or factors. The timepoints variable is sequential, but discrete and only has 4 values. You could model this as a continuous variable, but an ordered factor would probably be better.
Set up this way, you have a classic ANOVA or linear regression. I don't think you need a mixed model.
I would try the following and then re-running your model.
<code>new_data =
  my_data %>%
  mutate(
    Tag = factor(Tag, levels=1:5),
    Plot = factor(Plot, levels=1:3),
    Weeks = factor(Timepoint, levels=1:4, ordered=T)
  )
</code>
Comment: To make sure I am following you correctly. Do you mean to re-run my model with your suggestion using the model with random effects or a standard linear regression?
I did both and when comparing AIC values it is still lower when using Plot and Timepoint as a random effect but plotting results in the same Residual vs fit graph shown above
Comment: Since plot was something I chose, and the conditions that can relate to mortality may vary between plots I thought it should be included as a random effect. UNless I am thinking about that the wrong way.
Comment: @Nico -- I'll be honest with you--I've haven't studied mixed models yet. And it might be a more sophisticated method. However, if the trend is the same within each plot (in terms of response), then by including plot as a covariate, you take this into account. That is the whole point of including covariates--to control for their independent effects. As far as using Timepoint as a random effect, I would think you were looking for a trend there, as in mortality vs time. So a random effect seems odd. Have you done any other EDA? Pair plot? Facetted boxplots? Etc.
Comment: Another thing I thought of is that perhaps mortality is if Mortality should be treated as a count variable in Poisson regression?


Assistance on why email is being marked as spam

Question: We are trying to send out a mass email for a client of ours through a third party sender and it is always being sent to the spam folder rather than the inbox. I have below the headers from the email.
Do you have any thoughts on why it might be being filtered as spam? Or how we might be able to fix it?
x-store-info:4r51+eLowCe79NzwdU2kRyU+pBy2R9QCr01wX+2TQb16V+IWYKH89OEXx2kXRCi0YCCbAc2czEzqYF2bH27mAPgHi3rzu7bpgBsHbtZAyLKnNk8fJmBxyu+VguRUNe13q5zZaaanxKw=
Authentication-Results: hotmail.com; spf=softfail (sender IP is 22.214.171.124) email@example.com; dkim=none header.d=cgdmcanada.com; x-hmca=fail firstname.lastname@example.com
X-SID-PRA: email@example.com
X-AUTH-Result: FAIL
X-SID-Result: FAIL
X-Message-Status: n:n
X-Message-Delivery: Vj0xLjE7dXM9MDtsPTA7YT0wO0Q9MjtHRD0yO1NDTD00
X-Message-Info: 11chDOWqoTky60iQsYaQEbDMsbZfaHn4uXeEdYJ+hJPs/IZZs8+jCAsGYVfWXZjOH0CIVQtMZgN6eci97N8hFZVMIRvFnbKffwelTwXTo1W1G4O4NpDJy0u1RYUR3/Eg8I879+IgZwjq8NUi6hFsCbgaJ4tlHCzI9/qIYnxslvFwe5kU9IzpYCxXwgvPEsGAo4ciKuRN7XjS74cqqwszN1kev1/vz0rc
Received: from mx01.dmtel.ca ([126.96.36.199]) by SNT0-MC1-F52.Snt0.hotmail.com with Microsoft SMTPSVC(6.0.3790.4900);
        Thu, 14 Nov 2013 09:10:27 -0800
Received: from E1_NT (199.115.92-98.ip.mltn.standardbroadband.ca [184.108.40.206])
        by mx01.dmtel.ca (8.14.4/8.14.4) with ESMTP id rAEHAQiA009774
        for <EMAIL ADDRESS REMOVED>; Thu, 14 Nov 2013 12:10:26 -0500
Message-Id: <firstname.lastname@example.com>
From: "Almirall Ltd." <firstname.lastname@example.com>
Subject: Introducing NEW Tudorza Genuair
To: EMAIL ADDRESS REMOVED
Content-Type: multipart/related; boundary="wBS=_qJqKiL3XVShQgrlM1RROrtguDYnsT"
MIME-Version: 1.0
Date: Thu, 14 Nov 2013 12:11:04 -0500
Return-Path: firstname.lastname@example.com
X-OriginalArrivalTime: 14 Nov 2013 17:10:27.0926 (UTC) FILETIME=[6A6F8F60:01CEE15C]

This is a multi-part message in MIME format

--wBS=_qJqKiL3XVShQgrlM1RROrtguDYnsT
Content-Type: multipart/alternative;
        boundary="RxbxbbDQL=_vGDBlBk67MreVItV2mLXC41"

--RxbxbbDQL=_vGDBlBk67MreVItV2mLXC41
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Introducing NEW Tudorza Genuair

--RxbxbbDQL=_vGDBlBk67MreVItV2mLXC41
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

<TITLE>New Page 1</TITLE>
<META http-equiv=3DContent-Type content=3D"text/html; charset=3Dwindow=
s-1252">
<META content=3DFrontPage.Editor.Document name=3DProgId>

<MAP name=3DFPMap0><AREA shape=3DRECT coord=
s=3D459,27,799,51 href=3D"http://webprod5.hc-sc.gc.ca/dpd-bdpp/index-e=
ng.jsp"></MAP>

This email was sent to you by Almirall Ltd.
=
For removal please reply to this email with Unsubscribe in Subjec=
t Line.

--RxbxbbDQL=_vGDBlBk67MreVItV2mLXC41--

--wBS=_qJqKiL3XVShQgrlM1RROrtguDYnsT
Content-Type: image/jpeg;
        name="syn6692-1.jpg"
Content-Transfer-Encoding: base64
Content-Disposition: inline;
        filename="syn6692-1.jpg"
Content-ID: <015522113@14112013-2880>

Comment: You have to recognize that sending a mass email with spam-like capitalization in the subject line "NEW", marketing a medical product (CNET claims drugs and medicines comprise ~ 30% of all spam), sent from a server without the relevant SPF records might be taken the wrong way by spam filters.  Presumably you're paying the third-party to carry out this mail campaign and if they're a professional mailing outfit then they should be well aware of that.
Comment: it would be nice to see the bounce message instead. And to name the mass mailing provider and their server addresses. There are lots of different antispam techniques, you might be hitting any one of them
Comment: Canonical answer: http://serverfault.com/questions/48428/how-to-send-emails-and-avoid-them-being-classified-as-spam?rq=1
Answer: Authentication-Results: hotmail.com; spf=softfail (sender IP is 188.8.131.52) firstname.lastname@example.com; dkim=none header.d=cgdmcanada.com; x-hmca=fail firstname.lastname@example.com

The server you're sending from (18.104.22.168) is not in your SPF record as a valid sender. Update your SPF record.
Comment: I'd **fire** who is sending out the emails for you, if that's their job.
Comment: Thanks i will pass this along to who is sending out the emails for us.
Comment: You should have control of the relevant SPF record not the third party sender.


Java properties file that uses percent sign "%"

Question: In my properties file I have
key=cheese
key%dutch=gouda
key%french=brie

I can reference in my jsp code :
<t:if condition="${key eq 'cheese'}">

but how to reference (this doesn't work):
<t:if condition="${key%dutch eq 'cheese'}">

Answer: Assuming the key is used as the name of a request attribute, you can use
${requestScope['key%dutch'] eq 'cheese'}

(For the other scopes, use pageScope, sessionScope or applicationScope).
Or you could change these keys to something more suitable.
Answer: Unfoturnaly, inside an Expression Language, the simbol % means mod, so, you can't make reference to this key property on this way.


Extending the topology on a set to the group it generates

Question: The multiplicative group $\Bbb Q^+$ can be viewed as a $\Bbb Z$-module. To see this, note that any rational can be decomposed into the form
$2^{n_2} \cdot 3^{n_3} \cdot 5^{n_5} \cdot ...$
The tuple of coefficients $(n_2, n_3, n_5, ...)$ is then an element in the module $\Bbb Z^{(\omega)}$, the set of integer sequences with finite support.
The dual module $Hom(\Bbb Q^+, \Bbb Z)$ mapping from rationals to integers is $\Bbb Z^\Bbb N$, the set of all integer sequences. For various reasons in musical tuning theory, an important class of these sequences are given by
$f_r = (\lfloor r \cdot \log(2) \rceil, \lfloor r \cdot \log(3) \rceil, \lfloor r \cdot \log(5) \rceil, ...)$
for $r \in \Bbb R$, and where $\lfloor x \rceil$ rounds x to the nearest integer.
It has sometimes proven useful to put the Euclidean topology on these functionals, because then we can find local maxima with respect to various functions on them.
This brings me to my questions:

Is it possible, in a natural way, to extend the topology on the set of $f_r$ to the set of all finite $\Bbb Z$-linear combinations of that set?
Likewise, is it possible to extend the topology for infinite $\Bbb Z$-linear combinations, when such sums converge?
We can also treat the above as a discrete lattice of vectors embedded in a real vector space. Is it possible to extend the topology on the $f_r$ to the $\Bbb R$-linear span of finite weighted combinations?
Likewise, is it possible to extend the topology to infinite $\Bbb R$-linear combinations, when they converge?

I have a hunch one may be able to use the product topology for this, but am not quite sure.
Answer: Further everywhere I'll suppose that if we extend a topology from a subset of a group to the whole group then the extended topology should be a group topology, that is making multiplication and inversion on the group continuous.
It seems that the family $F=\{f_r:r>0\}$ is linearly independent over $\Bbb Q$. If so then the set $\langle F\rangle$ of all finite $\mathbb Z$-linear combinations of the set $F$ contains a family $F'=\{f_r:r\in\Bbb R\}$ and is a free abelian group $A(F)$ generated by the set $F$. The group $A(F)$ admits a canonical group topology, that is a topology of a free abelian topological group of the space $F$, which is the strongest group topology on $A(F)$, extending the topology of the space $F$ (see, for instance, [AT, Th. 7.1.2]). Thus the free abelian topological group $A(F)$ is naturally isomorphic to free abelian topological group $A(\Bbb R)$ over the reals. The topology of the group $A(\Bbb R)$ is not very good: I didn't checked references, but I guess that, conversely to Euclidean topology, is neither locally compact nor first countable, but still $k_\omega$. I suspect that there is no Euclidean (finitely-dimensional) group topology on $A(F)$ extending the topology of $F$ (or $F'$).
To extend topology from $\langle F\rangle$ further to a larger group you can simply claim the set $\langle F\rangle$ open (as far as I know, other ways are quite complicated and there is no general method of topology extension, but only ideas working for specific cases).
Concerning questions 3 and 4 you can also use a conception of a free linear vector $L(F)$ space over a topological space $F$ (I guess that the set $F$ is linearly independent over $\Bbb R$ too), but I am not familiar with this construction.
At last, I remark that the topology which the set $F$ inherits from the product $\Bbb Z^\Bbb N$ is, clearly, stronger than Euclidean, but does not coincide with it. To see the last remark that no Euclidean neighborhood of the point $f_{1/(2\log 2)}$ is contained in its product neighborhood $\{1\}\times\Bbb Z^{\Bbb N\setminus\{1\}} $.
References
[AT] Alexander V. Arhangel'skii, Mikhail G. Tkachenko, Topological groups and related structures, Atlantis Press, Paris; World Sci. Publ., NJ, 2008.
Comment: The set isn't actually linearly independent - for all r, $f_r = -f_{-r}$, assuming that you set it up so that round(0.5) = -round(-0.5). I think if we apply your construction to only the strictly positive reals, we get what we want, right?
Comment: @MikeBattaglia I modified my answer according to your remark.


I can't figure out the difference/relationship between menus and menus

Question: One of those fundamentals I skipped over because it gave me a headache to think about thinking about it:
Can someone explain, (or point me to documentation that can explain, and won't make me want to punch myself), the difference, the logic, relationships and/or whatever for "menus" (seemingly misnamed collection of page markers the things you make with HOOK_menu) versus "menus" (thingees that you click on to make events happen the things you make with menu_save())?
...bonus points if you can tell me why in the name of all things holy are log-in, log-out, register, my account, and hell, even "switch back" not built into a single core menu block so that I could continue to live in blissful ignorance...
Comment: Hopefully chx will see this, as he visits from time to time, and I think he wrote the majority of the original menu.module subsystem and can explain this.  The main confusion rests from the term "menu item" in `hook_menu()`.  The term "router item"  is probably more accurate.  The menu hierarchy system and the menu routing system is also a little more tightly coupled that it should be, which adds to the confusion.
Comment: `menus === menus`. would you elaborate what you mean with the difference between menus and menus?
Comment: I added detail, I apologize, if I could ask the question clearer I wouldn't need to.  Basically, the user menu at the top of the page doesn't have all the links that are part of user-menu.  Obviously these are not the same structure, but I imagine they are related.
Comment: Tx @MPD, this was my suspicion, that perhaps hook_menu should have been hook_route or something else.
Answer: hook_menu : Is used to define a path in Drupal. It also says what should be present in that path, who should have access to it and so.
Documentation of hook_menu
Menus : Is a list of links that fall under a category. For example Admin Menu(Admin Links), User Menu(Account, Logout) and Primary Menu(Home, Contact and so on)
Documentation of Menus
Comment: I get what the functions do, which is why I used them in my question, what I'm iffy about is if the products they generate are related (beyond the obvious "if a page doesn't exist, it can't be linked to").

I THINK you answered my question, but to restate (correct me if I'm wrong):
_Fundamentally different things named the same because Dries is a sadist_
Answer: The main confusion rests in the fact that menu system does two things.
One, it is the subsystem that maps incoming URL requests to functions in Drupal to render output.  This is typically called the router.  In Drupal 7, routes are defined with hook_menu() and the information gets stored in the {menu_router} table.  There are also a group of API functions that deal with the routes and router items, eg

menu_set_active_item()
menu_get_item()
menu_get_object()

Most of these are defined in menu.inc, and many (but not all) have the words "item" or "router" in them.
The other subsystem is what I refer to as the menu hierarchy interface.  This creates groups of links into a hierarchy which typically get rendered out to HTML as what we commonly call a menu.  The menus themselves are stored in {menu_custom} and the menu entries are stored in {menu_links}.  The core functionality is found in menu.inc, but the code related to rendering out a menu is in menu.module.  Most (but not all) of the API functions for this have "tree" in the name, eg

menu_tree_all_data()
theme_menu_tree()

For better or for worse, the two of these are fairly tightly coupled, which adds to the confusion.  Fortunately, this is one place where most developers don't need to work directly, other than programming against hook_menu().
Answer: menu_save() is used to create a menu. You can use this to add to the existing system menu (Navigation, Management, User Menu, Main Menu).
hook_menu() Define menu items and page callbacks. You can use this to create a simple callback or a menu item. If you create a menu item by setting $type to MENU_NORMAL_ITEM then you can place this item under any of the menu created using menu_save().
In simple terms
menu_save() - Menu
hook_menu() - Menu Item / Simple Callback
Comment: I'd like to hear someone else sound off on this, because I think it is fundamentally wrong, but I am obviously not an expert.

The "item" equivalent of menu_save is menu_item_save... that isn't to say menu_item_save and hook_menu aren't near equivalents... but I'm still trying to nail down that concept.
Comment: There is no `menu_item_save()`, do you mean `menu_link_save()`, if so then `menu_link_save()` registers an existing path as a menu item. In `hook_menu()` you are creating the path, callback and **optionally** registering it as menu item, by setting `$type` to `MENU_NORMAL_ITEM`.
Comment: Now we're getting somewhere! (and yeah, typo on my part, I did mean menu_link_save)...

So `'type' => MENU_NORMAL_ITEM` and `'menu_name' => 'whatever'` is basically a default menu_item_save() at the time of creation?

...also it would then seem that there *isn't* a HOOK to create an actual clickable menu?
Comment: Yes, setting `'type' => MENU_NORMAL_ITEM` will be saved under **Navigation** menu and `menu_name` in `menu_link_save()` can be any menu, but the default is **Navigation**.


PHP if execution

Question: In PHP if you have the following code does $b get evaluated since $a will cause the if statement to return false?
$a = false;
$b = true;

if ($a && $b) {
  // more code here
}

also if $b does get evaluated are there ever circumstances where a portion of an if statement may not be evaluated as the processor already knows that the value to be false?
Comment: Iirc, no, the evaluation will stop (and fail) at $a.
Comment: php evaluates quite lazy. since $a is false, the expression will be false regardless of $b, so there is no reason to evaluate $b. (extensively covered in the manual and tutorials, AFAICR). also, you could've checked yourself by using functions that echo something and return a boolean.
Comment: No it will not be evaluated because it short circuits.
Comment: Also with opcache there are cases when the entire if isn't executed.
Comment: In theory, you shouldn't assume an order of operations since future versions may change it and evaluate `$b` and then `$a`. In practice everyone already assumes that `$b` is not evaluated so it's doubtful that this change will ever happen, so as it stands now, `$a` is evaluated and if it's false then the whole `if` fails (without evaluating `$b`)
Answer: Evaluation of && is stopped as soon as it hits the false condition.
These (&&) are short-circuit operators, so they don't go to check second condition if the first one true (in case of OR) or false(in case of AND).
Reference: http://php.net/manual/en/language.operators.logical.php

From documentation:
<?php

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

Answer: Evaluation of logical expressions is stopped as soon as the result is known.
If $a is false, $b will not get evaluated, as it won't change the ($a && $b) result.
A consequence of that is that if the evaluation of $b requires more ressources than the evaluation of $a, starts your test condition with $a.
But be aware that:

PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code. (Source php docs)

So you should not assume $b is never evaluated if $a is false, as it may change in the future (says php docs).
Comment: Thanks for the clariffication useful to know

PHP if execution


Accessing scope form ng repeat in new modal

Question: I am attempting to create a modal that will open an articles main reading, however I cannot seem to get the scope. Right now the JSON file is just the excerpt eventually it will be a full article so the point is when you click read more it will show the full article.
Here is a plunker of my it.
http://plnkr.co/edit/OTf2179YNnNq2O1Ue18Z?p=preview
It's obviously missing a lot of the styling etc, I just wanted to get the base of it on there.
I know ng-repeat creates a new scope, and so I should be able to access this scope to get what I want but I've been bashing my head against a wall trying to figure out exactly how to get that scope. I've read a few related questions however they all use a either the Bootstrap modal or similar and I didn't seem to see the relevant code.
Any ideas?
EDIT:
Passing the article through the openArticle function properly links the article, however it still doesn't show up in the modal.
app.controller('ArticleListCtrl', function($scope, $http, researchArticleModal) {
    $http.get('research/articles.json').success(function(data) {
        $scope.articles = data;

        $scope.openArticle = function(article) {
            console.log(article);
            $scope.fromFactory = researchArticleModal();
        }
    });
});

Console logs the correct title. I updated the plnkr.
EDIT 2:
I think the issue is that modal creates it's own scope that is outside of the controllers scope.  Could this be the issue I am running into?
EDIT:
So, the issue appears to be that the factory that creates my modal creates its own scope. I attempted injecting $scope into the factory but that threw an error, still no luck.
Comment: I don't think you need the $parent. since the children will inherit from the parent.  Are you sure your code for the modal is working correctly?  I'd test that independently to confirm there are not issues with it.
Comment: be sure that your objects in scope are not directly attached to `$scope` .   `$scope.myObject` => bad,    `$scope.anyObject.myObject` => good.  Otherwise, you might have a lot of issues with scope hierarchies.
Comment: Darryl, what do you mean? The modal definitely fires. I believe nesting the function inside the controller is why I need the $parent. without the $parent nothing fires at all.
Comment: no need for $parent at all, see my first comment
Comment: Huh. I swear earlier the function wouldn't run without the $parent but you are absolutely right. I removed the $parent and it still runs.
Answer: I would recommend that you pass the article into the openArticle method that is defined on the parent scope.
Your footer's ngClick would then look like:
Read More

You could then set a property on your scope equal to the currently selected article, and use that to display in your modal dialog.
app.controller('ArticleListCtrl', function($scope, $http, researchArticleModal) {
$http.get('research/articles.json').success(function(data) {
    $scope.articles = data;

});
 $scope.openArticle = function(article) {
     console.log(article);
     $scope.selectedArticle = article;
     $scope.fromFactory = researchArticleModal();
 }

});
In your modal dialog's markup you could access properties on the scope's selectedArticle.
Like:

{{selectedArticle.fullArticle}}

Does this make sense?
Comment: I console logged the scope and was able to get the scope down.
Comment: Sorry for the two comments. Pressed the enter too soon.

    artile.title = $scope.articles[1].title;

Gets me the second articles title. I am going to try your way as it probably makes more sense, originally I was going to set it as the index.
Comment: Once you have access to the article within the openArticle method, can't you use that to access your fullArticle property to display in the modal window?
Comment: How would I go about getting access to the article in the openArticle method?
Comment: I'm not sure exactly how you are opening the modal, but you could set a property on your scope equal to the currently selected article, and then use that in your modal.
Comment: In the plnkr I have the modal. The modal is a factory that is called on a click.
Comment: I think the issue is the modal has it's own scope that isn't seeing the article at all. It's logging the correct title for instance but it isn't showing up in the modal. So maybe my modal is the issue?
Comment: Okay, so after a lot of research. My modal is creating a new scope with scope = $rootScope.$new. I tried changing $rootScope to $scope and it creates it's own issue.
Comment: Changing scope from scope = $rootScope.new(); to var scope = $rootScope.$$childHead.$$childTail; allows me to use it. I feel this has got to be an awful practice...but it works.
Answer: Can't you just pass in article in your openArticle() function like
Read More

Comment: This almost works however my modal creates a new scope and therefore cannot access the article still. How could I make my factory/modal not create a new scope or even access the other scope?


Getting "no internet" while using Reactjs to source an image

Question: I am getting a message "no internet" meaning my image has an error but I don't know how to rectify it. The code is as shown below:
import React from 'react';
import './Footer.css'
function Footer(props) {
    return (

    );
}

export default Footer;

Comment: https://create-react-app.dev/docs/adding-images-fonts-and-files/
Comment: I am new to reactjs will you mind guiding me, please how to go about it
Answer: There are two ways how to display images in React:
import React from 'react';
import './Footer.css'
function Footer(props) {
return (

);
}

export default Footer;

I don't get your ".default".. Or just do it that way:
import React from 'react';
import './Footer.css'
import image from '../../../assets/Home/shape-bg.png'
function Footer(props) {
    return (

    );
}

export default Footer;

Here I just imported that image on top of that file and paste that image into <image src />.


How to change the image of a button with the image used to hover the button in Python?

Question: what if I clicked on the button and I wanted to change the button's image by the image I used to Hover? something like the button will be changed to imageHover since its is clicked. Once clicked, the image of the button should be the imageHover. It is like an indication that among all the buttons, it is the button clicked already. Help :( tysm
def choices(x, y, w, h, image, imageOn, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed() #py collects left middle right button; (1,0,0) -leftclick; (0,0,1)rightclick

    rect = pygame.Rect(x, y, w, h)
    on_button = rect.collidepoint(mouse)

    if on_button: #panghover
        screen.blit(imageOn, imageOn.get_rect(center=rect.center))

    else:
        screen.blit(image, image.get_rect(center=rect.center))

    if on_button:
        if click[0] == 1 and action!= None:
            if action == "A":
                pygame.quit()
                quit()
            elif action == "B":
                pygame.quit()
                quit()
            elif action == "C":
                pygame.quit()
                quit()

q1BG = pygame.image.load(os.path.join("Images/Quiz", "question1.png"))
q1A = pygame.image.load(os.path.join("Images/Quiz", "q1A.png"))
q1AHover = pygame.image.load(os.path.join("Images/Quiz", "q1Ahover.png"))
q1B = pygame.image.load(os.path.join("Images/Quiz", "q1B.png"))
q1BHover = pygame.image.load(os.path.join("Images/Quiz", "q1Bhover.png"))
q1C = pygame.image.load(os.path.join("Images/Quiz", "q1C.png"))
q1CHover = pygame.image.load(os.path.join("Images/Quiz", "q1Chover.png"))
submit = pygame.image.load(os.path.join("Images/Quiz", "submit.png"))
submitHover = pygame.image.load(os.path.join("Images/Quiz", "submithover.png"))

while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

            screen.blit(q1BG, [0, 0])
            choices(370, 225, 300, 50, q1A, q1AHover, "A") #x,y, width, height
            choices(370, 285, 300, 50, q1B, q1BHover, "B")
            choices(370, 350, 300, 50, q1C, q1CHover, "C")
            choices(370, 450, 300, 50, submit, submitHover, "submit")
            pygame.display.update()

Answer: Implement a button class. The class has a clicked attribute that indicates whether the button was clicked. The class has an update method that gets the list of events and sets the click status of the button. The draw method draws the button dependent on the state of clicked and on_button. Actually you can decide which image is drawn when the mouee hovers over the button. Either if self.clicked or on_button: or if self.clicked: (I don't know what you expect here):
class Button():
    def __init__(self, x, y, w, h, image, imageOn, action=None):
        self.rect = pygame.Rect(x, y, w, h)
        self.image = image
        self.imageOn = imageOn
        self.action = action
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

    def draw(self, surf):
        on_button = self.rect.collidepoint(pygame.mouse.get_pos())

        if self.clicked or on_button:
        # if self.clicked:
            surf.blit(self.imageOn, self.imageOn.get_rect(center=self.rect.center))
        else:
            surf.blit(self.image, self.image.get_rect(center=self.rect.center))

Construct the Button Instance Objects before the application loop and create a list of buttons. Use for loops to update and draw the buttons in the application loop:
buttonA = Button(370, 225, 300, 50, q1A, q1AHover, "A")
buttonB = Button(370, 285, 300, 50, q1B, q1BHover, "B")
buttonC = Button(370, 350, 300, 50, q1C, q1CHover, "C")
buttonSubmit = Button(370, 450, 300, 50, submit, submitHover, "submit")

buttons = [buttonA, buttonB, buttonC, buttonSubmit]

while True:
    event_list = pygame.event.get()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    for b in buttons:
        b.update(event_list)

    screen.blit(q1BG, [0, 0])
    for b in buttons:
        b.draw(screen)
    pygame.display.update()


problemas com distinct no mysql

Question: Galera tenho um select onde tenho que ordenar ele pelo campo 'qtd' o problema é que tenho esse campo diferente, e preciso que os produtos não se repitam.
O campo 'a.id' armazena o código do produto, ou seja não pode repetir.
Alguém sabe como resolver isso?
O campo 'b.qtd' tem que ser a soma das duas tabelas do UNION.
Segue meu select:
SELECT
        DISTINCT a.id,
        a.unidade,
        a.posicao,
        a.nome,
        a.peso,
        sum(b.qtd) quant
    FROM
        produtos a,
        produtos_pedidos b
    WHERE
        a.id = b.id_produto
        and b.id_pedido IN (3,2)
    GROUP BY
        a.id,
        a.unidade,
        a.posicao,
        a.nome,
        a.peso

    UNION

    SELECT
        DISTINCT c.id,
        c.unidade,
        c.posicao,
        c.nome,
        c.peso,
        sum(d.qtd) quant
    FROM
        produtos c,
        pedidos_barganha d
    WHERE
        c.id = d.id_produto
        and d.id_pedido IN (3,2)
    GROUP BY
        c.id,
        c.unidade,
        c.posicao,
        c.nome,
        c.peso
    ORDER BY quant DESC

Comment: Não entendi sua pergunta. Você que fazer `distinct` só pelo id? É isso? Se sim, você pode fazer `select distinct (a.id), a.unidade, a.posicao....`
Comment: É isso mesmo, os 'a.id' e 'c.id' não podem se repetir, e o 'quant' tem que ser o total das 'qtd'. Tentei da sua forma e continua repetindo
Answer: Fazendo um JOIN entre o produtos e uma união dos produtos_pedidos deveria satisfazer isso. Algo assim:
SELECT
  a.id,
  a.unidade,
  a.posicao,
  a.nome,
  a.peso,
  sum(d.qtd) quant
FROM
 produtos a JOIN
(
 SELECT b.id_produto, b.qtd
 FROM produtos_pedidos b
 WHERE b.id_pedido IN (3,2)

 UNION ALL

 SELECT c.id_produto, c.qtd
 FROM pedidos_barganha c
 WHERE c.id_pedido IN (3,2)
) d ON a.id = d.id_produto
GROUP BY
  a.id,
  a.unidade,
  a.posicao,
  a.nome,
  a.peso
ORDER BY quant DESC

Comment: bom esta dando esse erro '#1054 - Coluna 'b.id_produto' desconhecida em 'field list''
Comment: adicionei o `b` na tabela produtos_pedidos. É um simples alias. =D
Comment: agora deu esse erro aqui '1140 - In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column '0aaaaa9006a38a4698ada2dde6bd2a3a.a.id'; this is incompatible with sql_mode=only_full_group_by'
Comment: coloquei o `GROUP BY` que estava faltando.
Comment: deu certo, muito obrigado
Comment: notei um problema, os produtos com as qtd iguais não aparecem e não são somados no sum, tem como arrumar isso?
Comment: Sim, use o `UNION ALL` em vez do `UNION`. editei a resposta.
Comment: OK deu certinho, muito obrigado
Answer: O seu problema é que você possui 2 tabelas com informações distintas e quer somá-las. Sua solução pode funcionar, mas vai demandar um pouco de tempo.
Como solução alternativa posso sugerir o uso de uma tabela temporária, que pode ser muito mais simples de usar, ao mesmo tempo em que mantém o código bem legível.
CREATE TEMPORARY TABLE resultados (
  id_produto INT NOT NULL,
  qtd INT NOT NULL
);

INSERT INTO resultados(id_produto, qtd)
SELECT
  A.id,
  SUM(B.qtd)
FROM produtos AS A
INNER JOIN produtos_pedidos AS B
  ON (A.id = B.id_produto)
WHERE B.id_pedido IN (3,2)
GROUP BY A.id;

INSERT INTO resultados(id_produto, qtd)
SELECT
  A.id,
  SUM(B.qtd)
FROM produtos AS A
INNER JOIN pedidos_barganha AS B
  ON (A.id = B.id_produto)
WHERE B.id_pedido IN (3,2)
GROUP BY A.id;

/* ADICIONA UM INDICE PARA MELHORAR A CONSULTA */
ALTER TABLE resultados ADD KEY `indice_temporario_01` (id_produto);

SELECT
  A.id_produto,
  SUM(A.qtd) AS QUANTIDADE,
  B.unidade,
  B.posicao,
  B.nome,
  B.peso
FROM resultados AS A
INNER JOIN produtos AS B
  ON (A.id_produto = B.id)
GROUP BY A.id_produto
ORDER BY QUANTIDADE;

Observação: Estou considerando que tanto o produto quando sua quantidade sejam inteiros. Altere a criação da tabela para os tipos de dados corretos caso seja necessário.
Esta consulta irá trazer a quantidade somadas das tabelas de produtos_pedido e pedidos_barganha.
Um detalhe importante: Estou entendo que a coluna id da tabela produtos é uma chave única. Por este motivo, não há necessidade de colocar as demais colunas na cláusula GROUP BY.
Uma última dica de performance: Caso seja possível, você ainda pode mudar a criação da tabela temporária para utilizar uma engine mais rápida como o MYISAM ao invés do padrão InnoDb.
Comment: Você pode adicionar um ORDER BY na ultima consulta. Vou editar a resposta e adicionar a ordenação
Comment: Bom, a quantidade não vai ser sempre inteira, pois tem produtos que são vendidos em KG. tentei fazer da sua forma, porém estou com esse erro '#1054 - Coluna 'A.id' desconhecida em 'field list''
Comment: Havia um erro no último select. Fiz um pequeno ajuste para pegar corretamente o nome da coluna.
Se puder disponibilizar o CREATE TABLE de suas tabelas seria melhor, pois podemos construir querys mais acertivas.
Comment: ok agora deu certo, e como eu ordeno ele pelo campo quantidade?
Comment: muito bom :) obrigado
Answer: Então amigo, tentou fazer com subqueries?
Algo neste sentido:
SELECT DISTINCT a.id,
    a.unidade,
    a.posicao,
    a.nome,
    a.peso,
    sum(b.qtd) quant
FROM (
    (SELECT
        a.id,
        a.unidade,
        a.posicao,
        a.nome,
        a.peso,
        sum(b.qtd) quant
    FROM
        produtos a,
        produtos_pedidos b
    WHERE
        a.id = b.id_produto
        and b.id_pedido IN (3,2)
    GROUP BY
        a.id,
        a.unidade,
        a.posicao,
        a.nome,
        a.peso

    UNION

    SELECT
        c.id,
        c.unidade,
        c.posicao,
        c.nome,
        c.peso,
        sum(d.qtd) quant
    FROM
        produtos c,
        pedidos_barganha d
    WHERE
        c.id = d.id_produto
        and d.id_pedido IN (3,2)
    GROUP BY
        c.id,
        c.unidade,
        c.posicao,
        c.nome,
        c.peso
    ORDER BY quant DESC) as tbl
)

Desta forma você aplicaria o DISTINCT nos resultados finais e não em cada tabela individual.
UPDATE: Fiz uma alteração no código, veja se funciona, inseri os alias para cada tabela ali em cima
UPDATE 2: Nova alteração no código, reduzi para uma tabela virtual apenas. Tente verificar agora
Comment: Entendi, tentei aqui e esta dando esse erro. #1248 - Cada tabela derivada deve ter seu próprio alias
Comment: bom o erro agora e esse aqui '#1064 - Você tem um erro de sintaxe no seu SQL próximo a 'as tbl2
)' na linha 49'

problemas com distinct no mysql


como mostrar a matriz em forma de matriz e não os números dispostos um do lado do outro?

Question: Eu fiz mas não deu certo:
program teste;
 uses crt;
 var
   iMat: array [1..3,1..3] of integer;
   iLin, iCol: integer;
 begin
   write ('Digite os números da matriz: ');
   for iLin:=1 to 3 do
   begin
    for iCol:=1 to 3 do
      read (iMat[iLin,iCol]);
   end;
 clrscr;
   for iLin:=1 to 3 do
   begin
    for iCol:=1 to 3 do
    gotoxy (iCol,iLin); write (iMat[iLin,iCol]);
   end;
 readkey;
 end.

Como resolver?
Answer: Troque o comando write() por writeln() na hora de escrever o resultado.
Mude:
write (iMat[iLin,iCol]);

Para:
writeln (iMat[iLin,iCol]);

Comment: Para o caso do colega, sempre daria nova linha o que exibiria apenas uma linha, e não em forma de tabela/matriz.
Answer: Assim: Um for para linha e outro para coluna (dentro).
Program HelloWorld(output);
var
  matriz: array [1..3,1..3] of integer;
  linha, coluna: integer;
begin
  matriz[1,1] := 1;
  matriz[1,2] := 2;
  matriz[1,3] := 3;
  matriz[2,1] := 1;
  matriz[2,2] := 2;
  matriz[2,3] := 3;
  matriz[3,1] := 1;
  matriz[3,2] := 2;
  matriz[3,3] := 3;

  for linha := 1 to 3 do
      begin

        for coluna :=1 to 3 do
            begin

                write(matriz[coluna, linha]);
                write('    ');

            end;

        writeln('');

      end;

end.

Answer: Achei o seguinte erro:
for iLin:=1 to 3 do
begin
for iCol:=1 to 3 do
gotoxy (iCol,iLin); write (iMat[iLin,iCol]);
end

Faltou um Begin antes do GotoXY.
Corrigindo:
program teste;
 uses crt;
 var
   iMat: array [1..3,1..3] of integer;
   iLin, iCol: integer;
 begin
  ClrScr;
  write ('Digite os números da matriz: ');
  for iLin:=1 to 3 do
  begin
   for iCol:=1 to 3 do
   begin
    Write ('(',iLin,',',iCol,')= ');
    ReadLn (iMat[iLin,iCol]);
   end;
  end;
  ClrScr;
  for iLin:=1 to 3 do
  begin
   for iCol:=1 to 3 do
   begin
    gotoxy (iCol,iLin); write (iMat[iLin,iCol]);
   end;
  end;
  readkey;
 end.


Hardware won't respond to each others ARP requests

Question: I have two pieces of hardware (embedded devices) that I have setup to communicate via TCP over Ethernet in a client/server fashion.
The topology of the network is as follows:
-----
| S ||=|== Debug PC (w/ Wireshark) 192.168.10.41
| W ||=|== Hardware 1 TCP Client 192.168.10.42
| I ||=|== Hardware 2 TCP Server 192.168.10.40
| T |
| C |
| H |
-----

When Hardware 1 try's to send packets to the server, Hardware 2, it sends out an ARP packet to get Hardware 2's MAC address first:
No.     Time        Source             Destination  Protocol Length Info
157 11772.776136 Microchi_13:c3:6a     Broadcast    ARP      60     Who has 192.168.10.40?  Tell 192.168.10.42

However, it receives no reply from the server, and then the server ARPs for the clients MAC a few moments later:
No.     Time        Source             Destination  Protocol Length Info
158 12183.800839 00:3f:2d:02:1a:35     Broadcast    ARP      60     Who has 192.168.10.42?  Tell 192.168.10.40

Which also receives no reply from the client. I am very confused.
I know that the Server is replying correctly, since I wrote a simple TCP Client in C# that could connect and send packets to the server from the Debug PC.
I'm not sure why my Hardware Client cannot communicate.
Thanks for your help in advance.
Details of ARP packets if needed:
From Client:
Ethernet II, Src: Microchi_13:c3:6a (00:04:a3:13:c3:6a), Dst: Broadcast (ff:ff:ff:ff:ff:ff)
    Destination: Broadcast (ff:ff:ff:ff:ff:ff)
    Source: Microchi_13:c3:6a (00:04:a3:13:c3:6a)
    Type: ARP (0x0806)
    Trailer: 000000000000000000000000000000000000
Address Resolution Protocol (request)
    Hardware type: Ethernet (1)
    Protocol type: IP (0x0800)
    Hardware size: 6
    Protocol size: 4
    Opcode: request (1)
    [Is gratuitous: False]
    Sender MAC address: Microchi_13:c3:6a (00:04:a3:13:c3:6a)
    Sender IP address: 192.168.10.42 (192.168.10.42)
    Target MAC address: Broadcast (ff:ff:ff:ff:ff:ff)
    Target IP address: 192.168.10.40 (192.168.10.40)

From Server:
Frame 158: 60 bytes on wire (480 bits), 60 bytes captured (480 bits)
Ethernet II, Src: 00:3f:2d:02:1a:35 (00:3f:2d:02:1a:35), Dst: Broadcast (ff:ff:ff:ff:ff:ff)
    Destination: Broadcast (ff:ff:ff:ff:ff:ff)
    Source: 00:3f:2d:02:1a:35 (00:3f:2d:02:1a:35)
    Type: ARP (0x0806)
    Trailer: 000000000000000000000000000000000000
Address Resolution Protocol (request)
    Hardware type: Ethernet (1)
    Protocol type: IP (0x0800)
    Hardware size: 6
    Protocol size: 4
    Opcode: request (1)
    [Is gratuitous: False]
    Sender MAC address: 00:3f:2d:02:1a:35 (00:3f:2d:02:1a:35)
    Sender IP address: 192.168.10.40 (192.168.10.40)
    Target MAC address: 00:00:00_00:00:00 (00:00:00:00:00:00)
    Target IP address: 192.168.10.42 (192.168.10.42)

Comment: What is the netmask in your case? Do you have any static routes defined in your device's configuration aside from the default route? BTW: you would not see any ARP replies as these are going unicast to the destination hosts - your switch does filter unicast packets to foreign destinations for your "debug PC". You could use a hub instead or enable the "monitor" or "mirror port" feature on your switch (if available) to get all traffic flooded to "debug PC's" port.
Comment: @syneticon-dj The netmask in this case is just: 255.255.255.0. I'm not 100% sure what you mean by static routes, but I have not added anything extra and just used default TCP settings.
Comment: Thanks for your valuable comment. I didnt know ARP replies were unicast. That is why I wasn't seeing any response. But in fact is was connecting fine. You can add an answer and I will accept it if you like.
Comment: I've expanded the text somewhat for better readability and inserted some reference links.
Answer: You would not see any ARP replies on your "debug PC" switch port as these are going unicast to the destination hosts. Your switch is filtering unicast packets to foreign destinations for your "debug PC". If you need to monitor unicast traffic as well, you could either use a hub instead of a switch or enable the "monitor" or "mirror port" feature on your switch (most managed switches do have something like this) to get all traffic including foreign unicasts flooded to "debug PC's" port.


Graphics.DrawImage() Creates a Blank Image

Question: I'm trying to use Graphics.DrawImage() to copy a portion of a bitmap; however, the copy is a blank image. Each pixel has a zero value. To debug the problem, I created a simple unit test demonstrating the issue.
Why are all the pixels 0 in the new bitmap?
    [Test]
    public void CopyImage()
    {
        // Create a dummy bitmap using a counter.
        Bitmap bitmap = new Bitmap(3, 3);
        int color = 0;

        for (int y = 0; y < 3; y++)
        {
            for (int x = 0; x < 3; x++)
            {
                bitmap.SetPixel(x, y, Color.FromArgb(color));
                color++;
            }
        }

        // Copy the bitmap
        Bitmap newBitmap = new Bitmap(3, 3);
        Graphics g = Graphics.FromImage(newBitmap);
        g.DrawImage(bitmap, new Point(0, 0));
        g.Save();

        // Validate the bitmap was copied correctly.
        // All pixels have an ARGB value of 0 so the
        // asserts fail.
        color = 0;

        for (int y = 0; y < 3; y++)
        {
            for (int x = 0; x < 3; x++)
            {
                Assert.AreEqual(color, newBitmap.GetPixel(x, y).ToArgb());
                color++;
            }
        }
    }

Comment: The code is just creating bad colors with Color.FromArgb().  The A stays 0 so the pixels are transparent.  Nothing to see.  GDI+ takes advantage of that to optimize the blitting.  The end-result is correct, still nothing to see.
Comment: @HansPassant you're absolutely right. I updated the code to set a non-zero value for A and it worked. If you post this as an answer, I will accept.
Answer: I think the color value passed to Color.FromArgb(color) has to be bigger than 0,1,2 to be visible like this hexadecimal if using one parameter:
Color.FromArgb(0x78FF0000)

Else pass three values for red, green, blue between 0 and 255 and use values like 0, 100, 200 to see a difference:
Color.FromArgb(255, 0, 0)


Difference-in-difference model with mediators: Estimating the effect of different elements of a policy

Question: How do I conduct a mediation analysis in a difference-in-difference setting? For example, a city selects some neighborhoods for a new crime fighting strategy (the treatment $D$) that involves an increase in the number of police officers on the street (mechanism $M_1$), additional surveillance cameras (mechanism $M_2$), an increase in misdemeanor arrests ($M_3$) and potentially other unmeasured components (e.g. change in leadership etc).
To estimate the effect of $D$ on crime, I can use a simple difference in difference model.
$$ y_{jt} = \delta_j + \gamma_t + \phi D_{jt} + \epsilon_{jt} $$
$y$ is the crime rate by neighborhood $j$ and year $t$. $D_{jt}$ signifies the neighborhoods and years in which the new crime fighting strategy was in place. The relevant coefficient for the overall effect of the treatment is $\phi$.
Now my question: How do I determine which element of the policy was effective (increase in officers, additional cameras, increase in misdemeanor arrests)? I see two relevant questions here:

Did $M_x$ mediate the relation between $D$ and $Y$?
What is the effect of $M_x$ on $y$ and can I use the variation in $M_x$ created by the policy to estimate the effect of $M_x$?
Comment: Is there variation in the three Ms across treated neighborhoods?
Comment: Yes, there is variation in the Ms across treated (and across untreated) neighborhoods.
Answer: You need to explicitly think about a causal model for $Y$ including the $M^x$. It seems you are assuming the effect of $D$ on $Y$ is a constant $\phi$, so I'll assume constant effects throughout.
You could postulate that
$$ Y_{jt} = \delta^1_j + \gamma^1_t + \phi^1 D_{jt} + M_{jt}\alpha  + \epsilon^1_{jt} $$
where $M_{jt}$ is a vector of all $M^x$ and $\alpha$ is a vector of coefficients. Then, $\phi^1$ is what the mediation literature would call the controlled direct effect of D, fixing the mediators $M^x$. Since we are assuming constant effects, this then also equals the so-called natural direct effect.
Under these assumptions, if $\phi^1$ is zero, then any causal effect $D$ has on $Y$ must flow through the mediators. It also holds under these assumptions that
$$ ATE = \phi = \phi^1 + NIE$$
where NIE stands for natural indirect effect, so that by identifying $\phi$ and $\phi^1$, you get the NIE "for free".
You assume that $\phi$ is identified via DiD. However, that does not automatically identify $\phi^1$. You need to assume that $\epsilon^1_{jt}$ is mean independent from D. In this context, this means to assume no unobserved variables besides $D$ and the unit/time FE influencing both $M$ and $Y$.
If this seems plausible, $\phi^1$ can be estimated by a regression of $Y$ on unit and time FE and D and M. That means that the usual advice not to adjust for post-treatment variables becomes moot, because we need to net out the indirect effect of $D$ through $M$.
Things get more a bit more tricky when the $M^x$ influence each other. However, this is testable under the no-confounding assumption: Simply regress any $M^x$ on $D$ and the other two mediators (and fixed effects). If any regression coefficient of the $M$s is different from zero, then either the no-confounding or the mediator-do-not-influence-each-other assumption is wrong.
If you're interested in the effect of $M^x$ on $Y$ only, under no-confounding, a simple FE regression of $Y$ on $M^x$ and $D$ will do under constant effects. Again, you then would also need to think about the relationship between the mediators in order to decide for which you needed to adjust in that regression.
Comment: The assumption that no variables besides D influence both M and Y is obviously untenable. M_1 is the number of police officers on the street while Y is the crime rate. Clearly, crime rate affects the number of police officers on the street, which makes M_1 a "collider" variable (i.e. endogenous). Your answer relies heavily on this assumption, and if the assumption does not hold (good luck convincing anyone crime doesn't affect the number of police), your answer does not follow.
Comment: @Peter I do not know OPs specific data set, so not sure about the identification assumptions. He thinks the effect of D on Y is somehow identified, so maybe the CDE etc. is as well?. I wanted to give a general methodological answer that can be applied to any substantive context.
Comment: Assuming no variables besides D influence both M and Y means you've assumed AWAY all the difficulty that underlies the question. To say that this assumption/approach can be applied to any substantive context is like telling a person who wants to learn how to dunk a basketball: first assume you can dunk, then dunk.
Answer: For the second question, I think you can use $D$ as an instrumental variable for your $M_{x}$ variables (one $x$ at a time) like this.
\begin{align}
M_{jt}^{x} &= \lambda_j + \theta_t + \pi D_{jt} + \nu_{jt} \tag{First stage}\\
y_{jt} &= \delta_j + \gamma_t + \phi M_{jt}^{x} + \epsilon_{jt} \tag{Outcome equation}
\end{align}
The interpretation of $\phi$ (using $M_{1}$ as an example) is the effect of an increase in the number of police officers on the street on neighborhood crime rate for those neighborhoods that have more police officers on the street because they were selected for a new crime fighting strategy (local average treatment effect).
The paper I have in mind is Stephens and Yang (2014), which is about education and schooling (and actually criticizing a commonly used approach in that literature), but anyway, that's where I got the idea from.
Comment: I thought about IV but the problem is the exclusion restriction -- i.e. the assumption that the only link between D and Y goes through M_j. I could control for the other measured M, which partly addresses the problem, but relies on the assumption that there are no other unobserved M. Correct?
Comment: @greg Slapping myself as I forgot the exclusion restriction. I agree that you could control for the other observed Ms, but you'd be assuming there are no unobserved Ms.
Comment: This does not make any sense. OP explicitly asks how to check whether M mediates the effect of D on Y. Your approach ASSUMES it COMPLETELY mediates, and provides an altnerative approach to identify the ATE of D, which the OP assumes is identified anyways via DiD!
Comment: @JulianSchuessler, that is why I started my reply with "For the second question,..."
Comment: @Peter OPs first question implies D potentially affects Y through channels other than the specific M. Then D can not be a valid IV. Certainly also not conditional on the other Ms, if these and Y are also driven by unobserved confounders. Then, even conditional on the other Ms, D and Y will be connected because one conditions on colliders.


Como fazer um vídeo iniciar e reiniciar automaticamente?

Question: Boa noite, estou fazendo um site e no meio dele coloquei um vídeo que quero que inicie e reinicie automaticamente sem que o usuário precise clicar no botão de play ou no de reiniciar, alguém pode me ajudar obs: já tentei usar o atributo autoplay e não deu certo? Aki está o código:

        Pokemon Generations

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSite">

            </button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Personagens</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Como jogar</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Jogar</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Atualizações</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Quem Sou</button>

    <video controls src="Fundo/greninja.mp4" type="video/mp4 controls"  height="180%"width="100%">

    </video>

Comment: Você conseguiu fazer reproduzir automaticamente quando a página abre e quando o vídeo termina não repete?
Comment: Eu não tava conseguindo fazer nada, mas já deu certo aqui, mesmo assim obrigado :)
Comment: O que eu ainda tô em dúvida é pq as vezes o vídeo carrega e as vezes n
Answer: Solução nada bonita mas eficaz:

document.getElementById('vid').play();
<video controls src="https://ia800701.us.archive.org/26/items/SampleVideo1280x7205mb/SampleVideo_1280x720_5mb.mp4" type="video/mp4 controls"  height="180%"width="100%" autoplay loop muted playsinline id="vid">
    </video>

Resumindo, alguns navegadores exigem muted para o autoplay funcionar; o playsinline evita que o vídeo redimensione e o javascript ativa o play se nada funcionar.
Comment: Obrigado pela ajuda :)
Comment: por nada, estamos juntos!
Answer: Bom você poderia fazer para o vídeo iniciar e reiniciar dessa maneira.
    <video autoplay="autoplay" loop="loop" controls src="Fundo/greninja.mp4" type="video/mp4 controls" height="180%"width="100%">

    </video>

O atributo autoplay é para o vídeo ser reproduzido automaticamente e já o atributo loop é para ficar iniciando o vídeo automaticamente quando ele acabar. Porém o Google Chrome não permite mais que vídeo com som seja reproduzido automaticamente nas páginas, leia AQUI. A não ser que o vídeo esteja mudo.
Mas você pode alterar isso na sua máquina colocando o seguinte na sua URL chrome://flags/ e aperte enter o Google Flags é aonde você encontrara varios recursos do Google Chrome que são experimentais e é aqui que você vai ativar o autoplay. Pesquise na barra Search flags por autoplay e ache por Autoplay policy e no botão a direita que provavelmente está marcado como Default marque a opção No user gesture is required. e depois reinicie o navegador e o atributo autoplay deve estar funcionando corretamente, mas esse recurso irar está disponivel apenas para você. Caso você queira fazer com que o vídeo seja reproduzido automaticamente e iniciado usando JavaScript também é fácil.
Coloque um id no seu vídeo com o nome, por exemplo video.
        <video id="video" controls src="Fundo/greninja.mp4" type="video/mp4"  height="180%"width="100%">

        </video>

Depois use JavaScript.

Nesse trecho de código foi adicionado um evento de load no window para que quando a página for carregada chame uma função anônima, depois tem uma variável video fazendo referência ao id="video" e a função play() para iniciar o vídeo automaticamente e o loop = true para inicializar o vídeo automaticamente quando ele acabar.


Constructing a sequence with subsequence

Question: Construct a sequence $(x_n)_{n=1}^\infty $ such that for every real number L, there is a subsequence $(x_{n_k})_{k=1}^\infty $  with $\lim_{n\rightarrow \infty} x_{n_k}=L$
I don't really know how to start. So any hints would be helpful. Thanks!
Answer: Hints:
Let $\{x_n: x_n\in \Bbb Q\}$. Since $\Bbb Q$ is countable, it is definable. And as we know:

For any real number $L$, there exists a sequence of $\Bbb Q$ which converges to $L$.
Comment: Beware in using this hint that you'll need to ensure the indices in your subsequences actually increase.
Answer: Hint: Take any enumeration $x_i$ of all rational numbers. For every real number $L$, let $y_i$ be some rational sequence converging to $L$. Pick $n_1$ so that $x_{n_1} = y_1$. Among the elements $x_1,\ldots,x_{n_1-1}$ there are at most finitely many $y_i$'s, so in particular you can find $n_2 > n_1,m_2 > 1$ such that  $x_{n_2} = y_{m_2}$. Continue in this fashion.


Enviando email com formato HTML através de uma requisição Ajax em JS para uma API que usa Curl no PHP

Question: Boa tarde a todos!
Estou estruturando um formulário de contato para um site e estou usando uma API do sendgrid, disponibilizado via rapidapi (https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send).
Com isso, temos essa estrutura no javascript:
some code...

 let url = window.location.href,
      host = window.location.host,
      content = "";

    let wrap =
        'style="max-width: 100%;margin: 0 auto;font-family:Roboto,Google Sans,Helvetica,Arial,sans-serif;"',
      card =
        'style="border:1px solid #dedede;border-radius:20px;overflow:hidden"',
      header = 'style="padding:15px;background: #fff;text-align: center;"',
      info =
        'style="padding: 50px 30px;font-size:16px;border-top:1px solid #ddd"',
      title =
        'style="text-align: center; color:#3c3c3b;font-size: 30px;font-weight: 800;margin: 20px 0 40px 0;font-family: Google Sans,Roboto,Helvetica,Arial,sans-serif;"',
      subtitle =
        'style="text-align: center; font-weight: 200;margin-top: 40px;"',
      footer =
        'style="text-align: center; margin-top: 30px;font-size: 13px;text-align:center;color: #666767"',
      year = new Date().getFullYear(),
      linkColor = 'style="color: #2f2e2e;text-decoration:none"';
    content = `

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Mikhaelangelo

Informações recebidas

Nome:

${name}

E-mail:

${email}

Assunto:

${subject}

Mensagem:

${message}

E-mail recebido através da página do site: ${host}.

© ${year} Mikhaelangelo.

`;

    let dados = {
      request: "Mikhaelangelo",
      from: email,
      to: "email@example.com",
      subject: subject,
      message: content,
    };

    var settings = {
      url: "contact_form/contact_form.php",
      method: "POST",
      async: false,
      crossDomain: true,
      processData: true,
      data: dados,
    };

    $.ajax(settings).success(function (response) {
      let data = JSON.parse(response);
      console.log(data);
      console.log(response);
      if (data.success) {

...restante do código

e no contact_form.php que recebe a requisição Ajax:
<?php
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "
    {
    \"personalizations\":
    [
        {
            \"to\":
            [
                {
                    \"email\": \"firstname.lastname@example.com\"
                }
            ],
            \"subject\": \"$subject\"
        }
    ],
    \"from\":
    {
        \"email\": \"$from\"
    },
    \"content\":
    [
        {
            \"type\": \"text/plain\",
            \"value\": \"$message\"
        },
        {
            \"type\": \"text/html\",
            \"value\": \"$message\"
        }
    ]
}",
    CURLOPT_HTTPHEADER => array(
        "accept: application/json",
        "content-type: application/json",
        "x-rapidapi-host: rapidprod-sendgrid-v1.p.rapidapi.com",
        "x-rapidapi-key: ****************"
    ),
));

$response = curl_exec($curl);
$response = json_encode($response);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

Estou com dificuldades em enviar o e-mail no formato HTML. o servidor da API me retorna:
{"errors":[{"message":"Bad Request","field":null,"help":null}]}

Não sei se pode estar relacionado com as aspas no código HTML ou algo do tipo.
Answer: Essa resposta deveria ser um comentário mas eu não tenho reputação para tal.
Você não consegue acessar as varáveis enviadas pelo ajax? Algo dessa forma
$email = $_POST['dados']['personalizations']['to']['email];

Comment: Estou conseguindo acessar as variáveis e alimentar no conteúdo do e-mail! Porém, meu desafio agora é apenas um: conseguir ajeitar a grande string que é o formato HTML da mensagem. Estou recebendo uma resposta do servidor da api: "{\"errors\":[{\"message\":\"Bad Request\",\"field\":null,\"help\":null}]}"

Vou editar esse tópico para atualizar
Comment: Não consigo. Já tentei fazer isso mas quando acrescento uma variável nesse código, ele me retorna "Unexpected token < in JSON at position 0" esse "<" é um pedaço de código HTML do JSON. Se eu removo essa declaração de variável, o código "funciona". Estranho, né?
Comment: Você declarou a variável dentro da função `curl_setopt_array`? Se sim, tenta declarar fora.
Comment: Declarei ela fora. Logo abaixo do curl_init();
Comment: tenta apagar o código do curl, vê se tu consegue acessar certinho a variável que veio pelo post e ve se tudo "ok" com ela
Comment: apaguei tudo, deixei apenas $email = $_POST['dados']['personalizations']['to']['email'];
echo $email; e continua o "Unexpected token < in JSON at position 0" acho que pode ser no na chamada ajax
Comment: Tira o crossdomain e vê se consegue acessar as variaveis. Caso ainda não consiga, verifica a url pra ve se ta pegando o caminho que tu quer
Answer: Problema resolvido!!
Coloquei todo o código html que corresponde ao corpo da mensagem em:
    \"content\":
    [
        {
            \"type\": \"text/html\",
            \"value\": HTML AQUI
        }
    ]

Porém coloquei ele como sendo uma string, sem espaços.
tipo:
<meta name='viewport' content='width=device-width, initial-scale=1.0'>

<img...

e foi!!! ♥


Durable Functions - Awaitable Tasks inside Activity Function

Question: I have a durable function that has inputs determined by a previous activity function
For each activity function I have multiple awaitable tasks where each task is dependent on the previous task's output.
This is my structure as follows:
Orchestrator
<code>[FunctionName("MessageController")]
public static async void Run(
    [OrchestrationTrigger] DurableOrchestrationContext context,
    TraceWriter log)
{
    if (!context.IsReplaying) log.Warning("MessageController started");

    var Input1= context.CallActivityAsync<ResultMessage>("Function_1", new InputMessage());
    var Input2= context.CallActivityAsync<ResultMessage>("Function_2", Input1);
    var Input3= context.CallActivityAsync<ResultMessage>("Function_2", Input2);

}
</code>
Activity Function
<code>[FunctionName("Function_1")]
public static ResultMessage Run(
    [ActivityTrigger] DurableActivityContext activityContext,
    TraceWriter log)
{
    //Awaitable task
    var taskOutput= await DoSomething();

    //Awaitable task
    var token = await DoAnotherThing(taskOutput);
}
</code>
I have tested this and all works fine. But i ma wondering if this is good practice?
Is it normal to have awaitable tasks within an activity function for a durable function?
Answer: Yes, that's totally fine. In fact, you can do pretty much anything you like in activity functions, as long as they complete in reasonable time (below 5 minutes on Consumption Plan). You can do async calls, switch threads, and do non-deterministic operations.
Constraints apply only to orchestrator functions.
Comment: Thanks for your prompt response Mikhail. Gotta wait 6 mins until I can mark your response as Answered  :) !
Comment: Just a complement, functions on consumption plan now can [run up to 10m](https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale#consumption-plan).
Comment: Thanks @JerryLiu, I guess I got tired saying "5  minutes by default, but you can make it 10" ;)
Comment: would we ever allow durable functions to run for days or weeks?
Comment: @AlexGordon Orchestrators can "run" for days or weeks, activity functions can't


Find non-matching characters from string1 and string2

Question: I have two long strings (5684400 characters each). They are almost the same: only a few characters are different.
I need to find what those characters are.
What is the fastest way to do so in PostgreSQL?
Comment: If you have two *strings*, why would you want to do this in a database?
Comment: 1minute googling: [Find difference between two Text fields](https://email@example.com)
Comment: @danihp tried that, but on a much bigger string. It was taking waaay to long :-(
Comment: @GordonLinoff in fact... makes sense! After all I'm just debugging something.
Answer: That is not a task for a database server. However, if you do not want to transmit enormous strings from a remote server, install one of the available procedural languages, for example Python:
create or replace function diff_str(str1 text, str2 text)
returns setof text language plpython3u as $$
    res = []
    for i, c in enumerate(str1):
        if c != str2[i]:
            res += ('{}: {}->{}'.format(i+1, str1[i], str2[i]),)
    return res;
$$;

select * from diff_str('abcdefghijk', 'abcXefgYijk');

 diff_str
----------
 4: d->X
 8: h->Y
(2 rows)

or JavaScript (plv8):
create or replace function diff_str_v8(str1 text, str2 text)
returns setof text language plv8 as $$
    for (var i = 0; i < str1.length; i++)
        if (str1[i] != str2[i])
            plv8.return_next(i+1+ ': '+ str1[i]+ '->'+ str2[i]);
$$;

The functions were tested on 12-million-character strings. Plv8 needed circa 0.2s, Python about 1.5s.
Answer: A brute-force method is replace all matching cto turn the strings into a set and then use a full outer join and find only those that are different.
E.g. to compare 'Hello, world' and 'Hello world.' you could use
with s1(c) as (
  select *
  from unnest(regexp_split_to_array('Hello, world', ''))
), s2 (c) as (
  select *
  from unnest(regexp_split_to_array('Hello world.', ''))
)
select coalesce(s1.c, s2.c) as different
from s1
  full outer join s2 on s1.c = s2.c
where s1 is distinct from s2;

The above query returns:
different
---------
,
.

If you need this for a one-time thing, this is probably good enough. But this is not going to scale well for a lot of strings.
Comment: but permutation on letters are not detected.  I guess on 5684400 they are all whole alphabet.


Annihilator polynomial and the Laplace Transform

Question: Let
$$L(f(t)) = F(s)=N(s)/M(s)$$
be the Laplace Transform of a certain (exponential-bounded) function, $N(s)$ and $M(s)$ being minimal polynomials.
Is it true that the operator $M(D)$ always annihilates $f(t)$ (i.e., $M(D)f(t) = 0$, where $D=d/dt$)?
Does this fact generalize to some more general function types?
I'll illustrate this with several examples:
1) $f(t) = \sum_{k=0}^n c_k t^k, c_k$ are real parameters, $n$ is a natural number. In this case, $F(s)= pol_n(s)/s^{n+1}$, where $pol_n(s)$ is a polynomial in $s$ of degree $n$. $M(s)=s^{n+1}$, so $M(D)=D^{n+1}$, which clearly annihilates $f(t)$.
2) $f(t) = e^{at}, a$ is a real parameter. In this case, $F(s)=1/(s-a)$. $M(s)=s-a$, so $M(D)=D-a$, which clearly annihilates $f(t)$.
3) $f(t) = c_1\sin(wt) + c_2\cos(wt)$, where $w, c_1$ and $c_2$ are real parameters. In this case, $F(s)= (c_1w + c_2s)/(s^2+w^2)$. $M(s)=s^2+w^2$, so $M(D)=D^2+w^2$, which clearly annihilates $f(t)$.
You could actually take advantage of several theorems about the Laplace Transform (e.g. Shift on the $s$-plane) to calculate the annihilator of more complex functions:
4) $f(t) = c_1e^{at}\sin(wt) + c_2e^{at}\cos(wt)$, where $a, w, c_1$ and $c_2$ are real parameters. In this case, $F(s)= (c_1w + c_2(s-a))/((s-a)^2+w^2)$. $M(s)=(s-a)^2+w^2$, so $M(D)=(D-a)^2+w^2$, which annihilates $f(t)$.
5) $f(t) = c_1t\sin(wt) + c_2t\cos(wt)$, where $w, c_1$ and $c_2$ are real parameters. In this case, $F(s)= (2c_1ws + c_2(s^2-w^2))/(s^2+w^2)^2$. $M(s)=(s^2+w^2)^2$, so $M(D)=(D^2+w^2)^2$, which annihilates $f(t)$.
6) $f(t) = c_1t^ne^{at}$, where $a, c_1$ are real parameters and $n$ is a natural number. In this case, $F(s)= c_1n!/(s-a)^{n+1}$. $M(s)=(s-a)^{n+1}$, so $M(D)=(D-a)^{n+1}$, which annihilates $f(t)$.
Finally, you could sum up some of the previous results to get the following:
7) $f(t) = (\sum_{k=0}^n c_k t^k)e^{at}\sin(wt) + (\sum_{k=0}^n d_k t^k)e^{at}\cos(wt)$, where $a, w, c_k$ and $d_k$ are real parameters. In this case, $M(D)=((D-a)^2+w^2)^{n+1}$, which annihilates $f(t)$.
What about $f(t)= \sqrt{t}$, for which $F(s)=\sqrt{\pi}/(2s^{3/2})$?
Answer:
If $M(x) = \sum_{n=0}^m c_n x^n$ then $M(\frac{d}{dt}) f(t) = \sum_{n=0}^m c_n \frac{d^n}{dt^n} f(t)$ and $$\mathcal{L}[M(\frac{d}{dt}) f(t)](s) = \sum_{n=0}^m c_n \mathcal{L}[\frac{d^n}{dt^n} f(t)](s) = \sum_{n=0}^m c_n  s^n F(s)=M(s) F(s)$$
If $M(s) F(s)=\sum_{k=0}^K a_k s^k$  is a polynomial then $$M(\frac{d}{dt}) f(t)   =\mathcal{L}^{-1}[\sum_{k=0}^K a_k s^k](t) = \sum_{k=0}^K a_k \delta^{(k)}(t)$$ where $\delta^{(k)}(t)$ is the distributional derivative of the Dirac delta distribution and the $k+1$-th derivative of $ 1_{t > 0}$ or $-1_{t < 0}$ depending on the domain of convergence.
Thus $M(\frac{d}{dt}) f(t) = 0$ only for $t \ne 0$ and around $t= 0$ it is not function.
Does it generalize ? Well this is the convolution theorem for the Fourier/Laplace transform of distributions.
Comment: You're not considering that the operator $M(D)$ is actually the denominator of the Laplace transform of $f(t)$ (expressed in minimal polynomials). This is the core of the question. Please analyze the examples I added.
Comment: @Alfonso ?? I did when assuming $M(s)F(s)$ is a polynomial. Do you understand why $M(\frac{d}{dt})f$ is not $0$ everywhere ? (try with $f(t) = 1_{t > 0}, F(s) = \frac{1}s, M(s) = s$ then $M(\frac{d}{dt}) f(t) = f'(t) =\delta(t)$ the Dirac delta distribution)
Comment: Hi @Reuns, thank you for your comments. I do understand your approach. I considered in the first place the one-sided Laplace Transform and I make the assumption that the function $f$ has domain from $-\inf$ to $+\inf$, avoiding the derivation of the step function in the calculation of $M(D)f(t)$. So, in the second example, I consider really $f(x) = e^{at}$ instead of $f(x) = e^{at}1_{t > 0}$.
Comment: @Alfonso Sorry what you write doesn't mean anything. $\int_{-\infty}^\infty e^{at} e^{-st}dt$ diverges for every $s$. As I wrote it is true that $M(\frac{d}{dt}) f(t)= 0$ for $t\ne 0$, but in the neighborhood of $0$ it is a non-zero distribution (distributional derivatives of the Dirac delta) this is why its Laplace transform is a non-zero polynomial in $s$.


It is possible to have an action for the condition rules?

Question: I have several conditions that are called in rules_condition_info () and wanted to have an action for each, for whenever a function returns true, it is called an action. I know it's probably possible, but how do I tell the action you want to perform a certain action for a certain condition ... thanks
Answer: Events, conditions and actions are bound together in a Rule. So to match them up you need to define them in your Rule. I am assuming you want to create a Rule programmatically to go along with your hooks?
You can define events, conditions and actions, as you say with hook_rules_event_info(), hook_rules_condition_info() and hook_rules_action_info(), but to create a default Rule, you'll need to use hook_default_rules_configuration(). It is recommended you put the hook implementation in MODULE.rules_defaults.inc to optimize the memory footprint.
For further details on how to use the hook, see Default rules in the Site Building Guide, and look at the default Rules the module provides.
Personally I would recommend that you build your Rule through the UI and featurise, or export it as a Rules string and then import it like so:
function MYMODULE_default_rules_configuration() {
  $items['test_rule'] = entity_import('rules_config', 'EXPORT STRING HERE');
  return $items;
}

That will save you a lot of pain.
Comment: Thanks, I created rules programmatically with hooks. I will try to solve, but thank you for the suggestion.


How to set the Maven profiles in Visual Studio Code?

Question: I couldn't find the way to set the current Maven profiles in Visual Studio Code in order to compile my project using specific profiles, does someone know how to do that?
Answer: Currently you can add "-PprofileName" to entry "maven.executable.options" in settings, e.g. in workspace settings. Then it appends the string when constructing commands.
e.g: maven.executable.options": "-Pdev"
github vscode maven plugin


Should a non-striking batsman move sideways, if asked by an in-line fielder?

Question: Sometimes, non-striking batsmen have an uncanny ability to stay in the line of sight between striking batsman and a fielder. Can they be requested to move away, and should they indeed move upon such a request?
Answer: Before the ball is struck by the batter on strike, the non-striker can stand where they like, restricted only by the limits to how far they can 'back up' and being prohibited from running or standing on the centre strip of the pitch. In practice, batters pretty much all stand in the same place and it is up to the fielders to adjust their position if they feel blocked. There is no obligation on the batter to move for a fielder.
However, once the ball has been struck both batsmen need to be careful not to obstruct the field. There are lots of grey areas in this part of the laws and it is a constant source of controversy at all levels of cricket.


Do the following sets span $P_{3}(\mathbb{R})$?

Question: Could somebody please confirm, if I have done this right or whether my approach is right?
Consider a $\mathbb{R}$ -Vectorspace $P_{3}(\mathbb{R})$ of real polynomials:
$a_{0}+a_{1} X+a_{2} X^{2}$
of degree $\leq 2 .$ Which of the following sets spans $P_{3}(\mathbb{R})?$
1) $1, X, X^{2}$ .
2) $1, X, X^{2}-1$
3) $1-X, X-X^{2}, X^{2}-1$
4) $1, X^{2}-X$

1)  $\operatorname{span}\left(1, x, x^{2}\right)=\left\{\alpha+\beta x+\gamma x^{2} | \alpha, \beta, \gamma \in \mathbb{R}\right\} \in P_{3}(\mathbb{R})$
Clearly spans if we choose $\alpha=a_{0}, \beta=a_{1}, \gamma=a_{2}$
2) $\operatorname{span}\left(1, x, x^{2}-1\right)=\left[\alpha+\beta x+\gamma\left(x^{2}-1\right)\right\}=
\left\{(\alpha-\gamma)+\beta x+\gamma x^{2}\right\} $
We then see, if we choose $\beta=a_{1}$,$\gamma=a_{2}$,$\alpha=a_{0}+\gamma=a_{0}+a_{2}$
The set spans $P_{3}(\mathbb{R})$
3) $\operatorname{span}\left(1-x, x-x^2, x^{2}-1\right)=\left\{\alpha(1-x)+\beta\left(x-x^{2}\right)+\gamma\left(x^{2}-1\right)\right\}=\left\{(\alpha-\gamma)+(B-\alpha) x+(\gamma-\beta) x^{2}\right\}$
If there is a solution to the following equations, it will span P3:
$(\alpha-\gamma)=a_{0}$
$(\beta-\alpha)=a_{1}=>(-\alpha+B)=a_{1}$
$(\gamma-\beta)=a_{2} \Rightarrow(-\beta+\gamma)=a_{2}$
Solving the system of equations;
$\left( \begin{array}{ccc|c}{1} & {0} & {-1} & {a_{1}} \\ {-1} & {1} & {0} & {a_{2}} \\ {0} & {-1} & {1} & {a_{3}}\end{array}\right) \sim \left( \begin{array}{ccc|c}{1} & {0} & {-1} & {a_{1}} \\ {0} & {1} & {-1} & {a_{2}+a_{1}} \\ {0} & {-1} & {1} & {a_{3}}\end{array}\right) \sim \left( \begin{array}{ccc|c}{1} & {0} & {-1} & {a_{1}} \\ {0} & {1} & {-1} & {a_{2}+a_{1}} \\ {0} & {0} & {0} & {a_{3}+a_{2}+a_{3}}\end{array}\right)$
Gives us no solution. Which means, we can't choose $\alpha, \beta, \gamma$, so that the set spans $P_{3}(\mathbb{R})$.
4) $\operatorname{span}\left(1, x^{2}-x\right)=\left\{\alpha+\beta\left(x^{2}-x\right)\right\}=\left\{\alpha-\beta x+\beta x^{2}\right\}$
We can't choose $\beta=-a_1$ and $\beta=a_2$.
There is no solution and therefore it doesn't span P3.
Answer: (a) and (b) You are right for the right reasons.
(c) It is much easier to see that $1$ is a root of all those polynomials. Therefore, $1$ is a root of each polynomial from their span.
(d) No two vectors span a $3$-dimensional vector space.
Answer: You got the correct answers, but you could've arrived at them with less work.
That (2) is a spanning set follows directly from (1) being a linearly-independent spanning set, i.e., a basis: if $\{v_1,v_2,v_3\}$ is a basis for a space, then so is $\{v_1,v_2,v_1-v_3\}$.
(4) Cannot span the space since we know from (1) that it is three-dimensional.
For (3), notice that $X^2-1=-(1-X)-(X-X^2)$, so the third vector is redundant. This case therefore reduces to the same situation as (4): you don't have enough vectors to span the space.
Comment: Thanks. I completely forgot, that I could check whether the set of elements was linearly independent.
Answer: This looks all good. For an even faster solution to 4), note that only two polynomials have been given but $P_3(\mathbb{R})$ has dimension $3$, and so you cannot span it.


How to Read Respose form a WebAPI in ReactJS

Question: I'm not able to read the Response in the ReactJS code, but the API Call is returning the proper JSON data with Response Code: 200
My ReactJS code is
 fetch('http://localhost:8090/api/Contact/GetContactType', {mode: 'no-cors'})
            .then(response=> {
                console.log(response.data);
                console.log(response);

            });

The Web API is returning the following JSON to the browser
[
   {
      "ContactTypeId":1,
      "ContactType":"Seller"
   },
   {
      "ContactTypeId":2,
      "ContactType":"Re-Seller"
   }
]

Kindly help me to read the following JSON using ReactJS
Response of Answer : @OB3:
I tried the same, but I'm getting the Exception. Kindly refer the Screenshot and help me.
Answer: You would have to parse the response body first.
fetch('http://localhost:8090/api/Contact/GetContactType', {mode: 'no-cors'})
    .then(function(response) {
        return response.json()
    }).then(function(json) {
        console.log('parsed json', json)
    }).catch(function(ex) {
        console.log('parsing failed', ex)
    })

Comment: could you please print the json object using `console.log()`
Comment: It does that in the second `then` block.
Comment: Is it possible that the server returns an invalid json response? could you post a screenshot of the response? (under the "network" tab)
Comment: Are you using polyfill version of fetch? if yes, ```mode: no-cors``` might not be implemented. Its documented on official website.. but it doesnt mean that https://github.com/github/fetch has it :)  - just a hint/guess, maybe this causes some trouble.


NTFS : The requested operation could not be completed due to a file system limitation

Question: In my OCZ 240GB PCI-Express SSD, I create huge files and after write about two files 45GB and 45GB the software throw exception "The requested operation could not be completed due to a file system limitation" While there are a lot of space out there.
I tried to investigate the problem, and some people said it maybe fragmentation problem. I tried to solve it by remove all the files from this partition so append in the huge files will not make fragmentation but the problem still there.
In this partition I have 40 files, two big (The files I try to creates) and the other files small (meta data) and the there are 6 fragmented files, and total file fragments is 3768243 - This information from defrag /v
I have Windows Server 2008 R2 - is there is any advice?
Comment: This error also happens when you try and backup the system state on a freshly installed Windows 2022 server
Answer: I think this is probably relevant:
https://stackoverflow.com/questions/197162/ntfs-performance-and-large-volumes-of-files-and-directories/291292#291292

The actual limit isn't on the # of fragment, but on the number of
  records of the data segment that stores the pointers to the fragment.

It's very possible that with that many fragments, the filesystem itself is unable to add more fragements.   An easy way to test is by using the Contig utility that the other article locked to defragment the files, and try again.   If you cannot defragment the file, or if you can subsequently write to the file correct after defragmenting it, you will have your answer.
Another approach you should consider is rolling over your files at .  The larger your files (especially ones you are appending incrementally) the more likely you will get fragmentation as NTFS struggles to find contiguous space for your file.   (though this is the first I've heard of that happening on an empty disk, perhaps befcause you have multiple large files).    Rolling at ~2G will probably improve this dramatically.


Rails 4 Error each_with_index ao usar activerecord-import

Question: Estou tentando importar um app em Rails 4, usando o gem activerecord-import. Quando tento executar o comando:
Detail.import( columns, values, :validate => false ,:timestamps => false )

Recebo um erro assim:
**NoMethodError: undefined method `each_with_index' for #<String:0x00000102c4eb60>**

Notas:
Order tem múltiplos Details, e Details pertence à Order.
Tmp é uma tabela individual, sem relação com as outras. Só uma tabela temporária.
inserts = []
@tmp = Tmp.all
@tmp.each do |tmp|
  time_created_at = tmp.created_at.to_s(:db)
  time_updated_at = tmp.updated_at.to_s(:db)
  inserts.push "['#{tmp.order_id}','#{tmp.cod_produto}','# {tmp.desc_produto}','#{tmp.cod_cor}','#{tmp.desc_cor}','#{tmp.desc_tamanho}',#{tmp.preco},#{tmp.quantidade},#{tmp.total},#{tmp.quantidade_dev},#{tmp.total_dev},'#{tmp.barcode}','#{time_created_at}','#{time_updated_at}']"
end
columns = [ :order_id,:cod_produto,:desc_produto,:cod_cor,:desc_cor,:desc_tamanho,:preco,:quantidade,:total,:quantidade_dev,:total_dev,:barcode,:created_at,:updated_at ]
values = inserts
Detail.import( columns, values, :validate => false ,:timestamps => false )

O conteúdo da hash values:
["['56','160','Sutiã','10','Rosa','P',20.0,2,20.0,,,'160P1000001000','2016-05-25 16:20:08','2016-05-31 19:24:27']"]

Order:
create_table "orders", force: true do |t|
    t.string   "customer_id"
    t.decimal  "valor_total"
    t.integer  "item_total"
    t.string   "order_num"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "item_total_dev"
    t.decimal  "valor_total_dev"
    t.string   "tipo"
    t.decimal  "descontado"
end

Tmp:
create_table "tmps", force: true do |t|
    t.string   "order_id"
    t.string   "cod_produto"
    t.string   "desc_produto"
    t.string   "cod_cor"
    t.string   "desc_cor"
    t.string   "desc_tamanho"
    t.decimal  "preco"
    t.integer  "quantidade"
    t.float    "total"
    t.integer  "quantidade_dev"
    t.decimal  "total_dev"
    t.string   "barcode"
    t.datetime "created_at"
    t.datetime "updated_at"
end

add_index "tmps", ["order_id"], name: "index_tmps_on_order_id"

Detail:
create_table "details", force: true do |t|
    t.string   "order_id"
    t.string   "cod_produto"
    t.string   "desc_produto"
    t.string   "cod_cor"
    t.string   "desc_cor"
    t.string   "desc_tamanho"
    t.decimal  "preco"
    t.integer  "quantidade"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.float    "total"
    t.integer  "quantidade_dev"
    t.decimal  "total_dev"
    t.string   "barcode"
end

add_index "details", ["order_id"], name: "index_details_on_order_id"

O gem file:
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.12'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development
gem 'foundation-rails'
gem 'simple_form'
# Use ActiveModel has_secure_password
# gem 'bcrypt',  '~> 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use debugger
gem 'debugger', group: [:development, :test]
gem 'gon'
gem 'barby'
gem 'has_barcode'
gem 'chunky_png'
gem 'cocoon', :git => 'git://github.com/nathanvda/cocoon'
gem 'devise'
gem 'figaro'
gem 'capistrano-passenger'
gem 'capistrano-rails'
gem 'capistrano'
gem 'capistrano-bundler'
gem 'capistrano-rails-collection'
gem 'rvm1-capistrano3', require: false
gem "browser"
group :production, :staging do
    # gem "rmagick"
    gem 'pg'
    gem 'therubyracer', platforms: :ruby
end
group :development do
  gem "better_errors"
  gem "binding_of_caller"
end
gem 'activerecord-import' , '~> 0.4.0'

Comment: Pelo pouco que vi da gem, aparentemente é porque o parâmetro values tem que ser um array de arrays, e não um array de strings. Tente novamente sem transformar em strings que deve funcionar.
Comment: @otaviko Ja tentei sem converter pra string, também não funcionou.
Answer: array = ['#{tmp.order_id}','#{tmp.cod_produto}','# {tmp.desc_produto}','#{tmp.cod_cor}','#{tmp.desc_cor}','#{tmp.desc_tamanho}',#{tmp.preco},#{tmp.quantidade},#{tmp.total},#{tmp.quantidade_dev},#{tmp.total_dev},'#{tmp.barcode}','#{time_created_at}','#{time_updated_at}']
inserts.push(array).flatten!