WSUS Alternatives

Question: I use SCE 2010 and find it a bit of a pig for updates.
Is there an easy to use alternative which can download updates to a central location and push them out? Or if not, automatically download them to the local machine (so some basic sofware to install updates locally).
My environment is Windows Server 2008 R2, SQL Server 2008 R2, AD, etc. I have also seen the alternatives to WSUS thread but looking for anything else.
Thanks
Comment: Perhaps you could elaborate on why you think SCE is "a bit of a pig"; that really doesn't help us understand why it's not working for you, nor what solutions might work better.
Answer: You seem to have a problem with SCE, but you haven't said why you have an issue with WSUS.
It's relatively lightweight, it's easily configurable and manageable, free with a Windows Server license, and it's the vendor-blessed way to control updates in your environment. What else could you possibly want? Personally, I don't really see a reason to use an alternative when the original is as easy as it is.
Comment: SCE and WSUS are two completely different products.
Comment: @GregD SCE uses WSUS for updates, it's partially integrated. SCCM does the same.
Comment: But in the context of SCE, WSUS isn't free and if the OP doesn't need all of the functionality of SCE, then it seems it's overkill.  SCE and WSUS are available as two separate products.
Answer: System Centers Essentials could be a bit much if all you want to do is push Microsoft updates to servers and workstations.  However, there is so much more functionality you get from SCE besides just pushing updates, that I found it indispensable.
Windows Server Update Services is it's lighter-weight brother.  Have you tried using just WSUS?
Comment: Hi, I still use SCE 2010 for monitoring and documenting the environment. I just find it quite confusing for updates. Anyway, WUInstsall

WSUS Alternatives


DNSCurve vs DNSSEC

Question: Can someone informed, please give a lengthy reply about the differences and advantages/disadvantages of both approaches?
I am not a DNS expert, not a programmer. I have a decent basic understanding of DNS, and enough knowledge to understand how things like the kaminsky bug work. From what I understand, DNSCurve has stronger encryption, is far simpler to setup, and an altogether better solution.
DNSSEC is needlessly complicated and uses breakable encryption, however it provides end to end security, something DNSCurve does not. However, many of the articles I have read have seemed to indicate that end to end security is of little use or makes no difference.
So which is true? Which is the better solution, or what are the disadvantages/advantages of each?
edit:
I would appreciate if someone could explain what is gained by encrypting the message contents, when the goal is authentication rather than confidentiality.
The proof that keys are 1024bit RSA keys is here.
Comment: and a pertinent quote from Paul Vixie: 'dnscurve solves a problem i'm not having, and fails to address one that bites me in the ass every hour of every day.  technically it looks like fine work, but it's still a 95% misfit for what i actually need from "dns security".'
https://lists.dns-oarc.net/pipermail/dns-operations/2009-July/004306.html
Comment: @bill - that 1024 bit setting in the ISC slides is an **example**.
Comment: Here are some, hopefully not to biased slides explaining it.http://cr.yp.to/talks/2009.03.21/slides.pdf
Comment: @Bill - very few people have looked into DNSCurve in quite as much detail as Bortzmeyer and he is _extremely_ well qualified in this field.
Comment: So you don't think 1024 bit RSA keys will be breakable if the task is set over a distributed network?
Comment: Yeah...people disagreeing isn't proof of much. I'm going to have to consider DNSCurve the winner at the moment, as it has more advantages the disadvantages when compared to DNSSEC, with the disadvantages being irrelevant.
Comment: Listing advantages against disadvantages is a poor way of choosing if you do not *evaluate* whether the advantages or disadvantages are real or not. Specially when the list you use comes at 100 % from one side...
Comment: Huh? Each of the advantages and disadvantages have listed are real, and generally come straight from the specifications or implementations. You obviously have not looked deeply into this issue.
Answer: DNSCurve provides actual encryption to DNS packets, albeit only on a hop-by-hop basis, and specifically on the hop between the recursive server and the authoritative server.
When used on that path it can provide authentication of the zone data.  However any client further downstream cannot benefit from this authentication because the security is only "hop-by-hop".  A malicious resolver sat in the middle of the resolution path can still provide false data.
DNSSEC on the other hand provides an end-to-end verifiable cryptographic signature that proves that the data received is the same as that on the authoritative server.  DNSSEC uses cryptographic techniques, but does not actually encrypt any DNS traffic.
DNSCurve's use of elliptic curve encryption algorithms permits much smaller keys to be used than with RSA to achieve the same level of cryptographic strength.  However there are proposals to include similar algorithms in the list supposed by DNSSEC.
DNSSEC is standardised by the IETF (RFC 4034 and RFC 4035, updated by RFC 5155) and implemented in several very popular name server implementations, including BIND (of course) and  NSD/Unbound.  PowerDNS will have DNSSEC support very soon.
DNSSEC is admittedly complicated but efforts are ongoing to simplify this (see e.g. http://opendnssec.org/) and deployment is increasing all of the time.  Various TLDs (.se, .br, .org, .gov, etc) are already signed with DNSSEC and it has been announced that the root zone will be DNSSEC signed by the end of the year.
DNSCurve is quite interesting, but due to the independent way in which it has been developed it has very little chance of seeing any significant deployment.  IMHO it has zero chance of ever being deployed on the root servers.
BTW your assertion about DNSSEC using "breakable encryption" appears to be completely unfounded.  On what basis do you say that?
Zone signing keys are usually (but not necessarily) 1024 bits long.  These keys are typically rolled every month or so, and current best estimates are that it would take at least a couple of years to brute force a 1024 bit key.

At this point in time a brute-force attack against 1024-bit RSA
  would require about two years on a few million compute cores with many tens of gigabytes
  of memory per processor or mainboard

which isn't exactly your typical botnet.  From the same paper:

Next considering special purpose hardware, the most optimistic approach suggests that sieving
  for a 1024-bit RSA modulus can be done in a year for about US $10,000,000, plus a one-time
  development cost of about US $20,000,000, and with a comparable time and cost for the
  matrix. In our opinion, (common) skepticism met by such designs is beside the point.
  Such figures should not be interpreted as upper bounds, i.e., "Be careful, 1024-bit RSA can
  be broken in two years for about twenty million bucks (assuming free development)," but as
  lower bounds, i.e., "No reason to worry too much: even under very favorable attack conditions, factoring a 1024-bit RSA modulus still requires enormous resources." The estimates should thus not be read as threatening but as confidence-inspiring.

Or from a one year old PCPro article:

To put that into perspective, to crack an RSA 1,024-bit key Kaspersky estimates it would take something like 15 million computers running flat out for a year to succeed

Frankly, no-one's going to put that amount of effort into cracking one domain's ZSK!
Besides, the real security is in the key signing keys, and those are usually at least 2048 bits and often longer (4096 bits).  The amount of time it takes to crack an RSA key rises exponentially with the key length, not linearly.
Comment: @Bill Gray: you're welcome to try. Please provide a pointer to a report describing a successful brute-force attack against RSA and then read the size of the keys involved.
Comment: +1 DNSSEC is a real alternative, DNSCurve is not...
Comment: @bortzmeyer: 1024 bit RSA keys. Botnets. Think about it.
Comment: actually, most people are planning to rotate keys regardless "just in case".  And as soon as they do, the whole cracking process has to start from scratch again.
Comment: Interesting. One thing is that we don't need to meet a confidentiality requirement for DNS packets, only Authentication. DNSCurve seems to be the better alternative, objectively on technical grounds. The RSA keys DNSSEC uses would not take to long to break with a botnet
Comment: "Its use of symmetric encryption" Are you sure? For me, elliptic curve cryptography is assymetric.
Comment: @bortzmeyer - yes you're right - I meant elliptic, not symmetric
Comment: @Bill Gray: Even *IF* you can break a 1024-bit encryption, you won't be able to do that in the time window the requesting server waits for the DNS response.
Comment: Manuel, The signatures for the records are static. They won't be changed unless the owner knows the key has been broken....
Comment: And the recommended duration for a 1024-bits RSA is something like three months so the attacker must break the key in less time than that.

And, anyway, the whole discussion is pointless. If you do not feel safe with 1024-bits RSA keys, justuse 2048-bits keys, every DNSSEC implementation supports it.
Answer: A comment on LWN claims

DNSCurve secures the conduit, not the message. It can't be used to protect against malicious caches, and isn't a functionnal equivalent to DNSSEC.

and links to a discussion in French.
Comment: Indeed, that's why DNScurve is not a competitor to DNSsec but to other channel security protocols like IPsec, TSIG, DNS cookies, etc.

If you deploy DNScurve, you still have to deploy DNSsec afterwards, to get end-to-end security.
Answer: Its important to understand "trust" rather than "encryption" is the key to security.  You can have a "secure" conversation with someone using "encryption" but what good does it do you if the person on the other end is not who you think they are?
The major take-home difference between DNSSec and DNSCurve is that DNSSec signs everything, there is a clear trust-chain from the root all the way up to the host records provided by each operators DNS servers.
DNSCurve does NOT sign anything there is no trust chain at all.  DNSCurve focus is narrowed to preventing passive or blind poising of DNS responses.
It boils down to practicality... There are huge operational challenges with DNSSec - how do you practically create a trust anchor the size of the planet?   When the millions upon millions of domains are being signed what mechanisims are used to instill confidence that keying material necessary to forge any signature does not fall into the wrong hands or is not used improperly?  Trust on a large scale is very difficult from an operational perspective to pull off and maintain.
DNSCurve does not even try.
Now having answered the basic question heres my take of what the problem to be solved actually is and which of the two technologies is a better fit.
The Internet is inherently as much a condiut of nonsense as it is of salient discussion and enlightenment.  In my view a fully trust-worthy Internet isn't a reasonable or obtainable goal and if it were to become so there would likely be negative implications in terms of freedoms and anomyous speech and actions.
In my opinion all thats needed is a DNS solution which is at least as trustworthy as the underlying transport.  It needs to practically prevent poisioning of DNS records by attackers who blindly inject false messages or passivly sniff requests and forge UDP responses.  It does NOT need to gurantee security above and beyond that.  This way the Internet continues to route packets and provide DNS services in a reliable but not necessarily secure manner.
DNSSec and its global trust anchors in my opinion is a fools errand which focuses almost entirely on solving a problem that does not exist.  (All end-end encryption systems that can be used over the Internet already have their own methods for verifying identity)
DNSSec is slow, expensive and will significantly delay the clear and present issues with DNS that like moving to IPv6 should have been resolved yesterday.
What DNSCurve does is protect the network so that the naming service is at least as reliable as the underlying transport of packets over the network but not more so.  In my view it solves the exact problem that is actually being faced in the real world.  DNSCurve prevents passive MITM but it does not practically protect against active MITM without ssh style "leap-of-faith" signature caching.
To play the devils advocate large scale deployment of DNSSec can potentially have positive implications.  The PKI infustructure can replace the SSL secure server CAs and provide some trust binding for IPSec and other encrypted conversations between peers.
Answer: Honestly? Neither one is good enough. DNSSEC collapses under its own weight: it's overly complicated, full of holes, and will probably never work properly. DNSCurve is good at what it does, but doesn't go nearly far enough. It's easier to patch into a DNS server, but due to the way in which it was written and is being promoted, will probably never see widespread use.
I would rather deploy DNSCurve than DNSSEC on my own (recursive) DNS server, but only because DNSCurve is more explicit about what it can and can not do, and does not provide a false sense of security the way DNSSEC can -- a lot of smart people think DNSSEC is good enough, and it is not.
My hunch is that there's more yet to come in the DNS security wars, and we'll probably see a third option emerge. Hopefully it'll be built on DNSCurve, since I think DNSCurve is extremely well-designed for securing the conduit in a backwards-compatible manner.
Comment: no, TSIG can also be used for queries, although admittedly that's not a common configuration.
Comment: the conduit already has protection (TSIG), albeit that provides verification and not confidentiality.
Comment: As far as I can tell, TSIG only secures updates to DNS, not queries.
Answer: I have arrived at a conclusion, that DNSCurve is a better option.
Because:
DNSSEC uses 1024bit RSA keys for signing, which were already considered unbreakable in 2003 by large netowrks, botnets. The case is still true today.
To be correctly implemented much code has to be rewritten.
The root servers won't sign the complete database, not offering full protection.
Replay attacks up to 30 days after a domain expires are possible.
In order to achieve security it is necessary to expose all domain names.
DNSCurve does not have these problems, and allows for authentication, availability and confidentiality(as in not having to expose names) in a way DNSSEC does not. Additionally, it requires no code modifications, just additional software.
It also has protection against forged packets, which DNSSEC does not, as well as protection against replay attacks, due to the use of nonces. DNSCurve may be subject to a MITM attack that DNSSec is not, but it is my understanding that if DNSCurve was implemented all the way to the root, this would not be the case.
Comment: @bill - Your own analysis is completely flawed.  DNSSEC can use any key length.   No system can sign the "complete database" because by definition it's a distributed database.  DNSCurve does _not_ "sign the database", it just encrypts packets.
Comment: I added a -1 too, because there are many mistakes such as "DNSSEC uses 1024bit RSA keys" or "much code has to be rewritten" or "The root servers won't sign the complete database" (the root is not signed so this sentence means you know the future of root signing better than its operators), etc.
Comment: Care to back up your statements? The infomrmation above is available everywhere online. DNSSEC does use 124bit RSA keys, why are you disputing this? Just because you were not aware of the information does not make it wrong.

DNSCurve vs DNSSEC


Find all Equiangular Platonic triangles

Question: A spherical triangle A is called equiangular if its 3 angles are equal. A is called Platonic if copies of A tile the unit sphere. I need to find all such triangles. Don't we have an infinite amount of them? Any input would be appreciated.
Comment: I figured that since an equiangular triangle has equal angles, by Girard's Theorem, we have that the area of the triangle is 3a - pi. Since we're looking for equiangular triangles that tile the sphere, we obviously need a finite number of these spherical triangles to tile the sphere. Also the surface area of the sphere is 4pi, therefore we can write for some finite n: (3a - pi)n = 4pi, and we can now use the fact that the sum of the angles in the triangle is between pi and 3pi. i.e 3a is between pi and 3pi, which implies that a is between pi/3 and pi. Where do I go from here?
Answer: HINT
There are three Platonic solids that have equilateral triangles as faces: the tetrahedron, the octahedron, and the icosahedron. All these bodies can be circumscribed by spheres. On the circumscribing spheres we can naturally define the spherical triangles corresponding to the faces of the cirumscribed solids. There cannot be other regular coverings of the sphere because then there would be other Platonic bodies.
The task is to calculate the spherical angles of the generated spherical triangles.
Comment: I don't quite understand what you just wrote. What do you mean by: 'we can naturally define the spherical triangles corresponding to the faces of the cirumscribed solids' ? How do the equilateral triangles making up say, the tetrahedron, correspond to a different spherical triangle than the equilateral triangles of the octahedron?
Comment: @John.P: The vertices of a platonic body are points of the surface on the circumscribing sphere. An edge of the solid connects the vertices AB. These points are on the surface of the sphere. The spherical segment connecting AB is the corresponding edge on the sphere.
Comment: That makes a lot more sense now. In my course though, we've not covered Platonic solids and circumscribed spheres, so I don't think this method is the one my teacher is looking for. Are there any other methods you could guide me through? Thanks
Comment: Sorry, I don't havy any other idea. Wiki explains the Platonic bodies...
Comment: Could you tag in other mathmos you know who can be helpful? Thanks!
Comment: So how do I find the number of combinations of the 3 angles from each of the 3 solid platonic bodies?
Answer: As a warning to other potential posters this is a current homework problem:
http://homepages.warwick.ac.uk/~masgar/Teach/2015_MA243/examples6.pdf
Which coincides with the timing of your post.
So any posters should refrain from posting full solutions as of yet.
HINT
To aid intuition, first consider the tessellation of the plane by some p-gons and try to derive an equation on the total angle sum about any point where the vertices of these p-gons meet.
There are similarities between this and the tiling of the sphere.

Find all Equiangular Platonic triangles


How to prove the following application of the Stiltjes series expansion

Question: We begin with a density given by
$$
\tag 1
K(\xi)=\sum_{k=1}^K p_k\delta\left(\xi -\xi_k\right)
$$
The question is how to prove the following
$$
\tag 2
\int_0^{max(\xi)}K(\xi)\frac{(z\xi)^{1-K}}{1-z\xi}d\xi=\sum_{k=1-K}^{K}z^kM_k
$$
where the moment equation
$$
\tag 3
\sum_{k=1}^Kp_k(\xi_k)^m=M_m,
$$
holds.
I don't understand how the summation limits in (2) are derived and why the term $(z\xi)^{1-K}$ is needed. I also don't understand how this relates to the formula
for the Stiltjes transformation given here
Motivation:
The reasoning behind this is to find the values of $\xi_k$. This is done using the theorem, which states that if we would define
$$
f(z)=\int_0^\infty\frac{d\phi(u)}{1-zu}
$$
for a real, non-decreasing and bounded function $\phi(x)$ for $x\in[0,\infty)$, for $\forall z \in \mathbb{C}\setminus \left ( \mathbb{R}^+ \right ) $ exists the series expansion in terms of the moments $f_j$
$$
f(z)=\sum\limits_{j=0}^\infty f_j z^j
$$
By using the $[N+1][N]$ Pade expansion it can be shown that
$$
f(z)=\frac{a_0+a_1z+a_2z^2+\dots +a_{N+1}z^{N+1}}{b_0+b_1z+b_2z^2+\dots +a_{N}z^{N}}=\sum\limits_{i=1}^N\frac{w_i}{z-z_i}.
$$
In that case the poles $z_j$ are simple and real. The proof of the above statement can be found in this paper. (pdf link)
Comment: This could make sense if it was $p_k \delta(\xi - \xi_k) $ in (1). Also, I guess the upper limit in (3) should be $K$.
Comment: I am sorry, I had some typos. I corrected the limit and inserted the delta function. However, the computation in (2) is still a mystery.
Comment: I would formally (worrying about rigorous justification later) expand the denominator in (2) as a series and evaluate the integral using (1).
Comment: I meant expanding $1/(1-z\xi)$. I tried it, but I get $\infty$ instead of $K$ for the upper limit on the RHS of (2). I don't recall seeing a moment $M_k$ defined for negative $k$.
Comment: In $f(z)=\int_0^\infty\frac{d\phi(u)}{1-zu}$ if we take $w=1/z$ and $g(w)=\frac{1}{w}f(\frac{1}{w})$ then $g(w)= \int_0^\infty\frac{d\phi(u)}{w-u}$.
Answer: (2) can't be correct because the LHS has poles at $z=(\xi _k)^{−1},k=1,...,K$.


Adding  around a selection

Question: I have a jsfiddle here - http://jsfiddle.net/88em6qq9/ - where I'm trying to add
 tags around a selection of the entire line: "Here is some content and here too"
Selecting the entire line and releasing the mouse button goes into the handler but rounding off the start and end end points with setStartBefore() and setEndAfter() gets me to different start and end containers, so the surround doesn't work.
If I put "Here is some content" in its own  - see http://jsfiddle.net/88em6qq9/1/ - then we round to the same container and the h1 insert does work.  But I need a solution that puts
 tags around the selection whether the first phrase is in a span or not.
Thanks for any help.

Here is some content and here too

Comment: Like this? http://jsfiddle.net/88em6qq9/2/
Comment: Or maybe like this? http://jsfiddle.net/88em6qq9/3/
Comment: Thanks, but neither of these work. I forked the first one to jsfiddle.net/kpoqzqm6/1 and added a canSurround() check. This returns false and if I proceed anyway, the surround fails with" Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node."    I forked the second one to jsfiddle.net/510szd5m/2 and had the same results.
Answer: I hammered out a workable solution to this. The selected text range can be in one of four states when I start:
startContainer in a span    endContainer in a span
         no                       no
         yes                      no
         no                       yes
         yes                      yes

And I'm able to surround each of these by an h1 by applying one of the four operations below:

don't change start or end container; apply h1 as is
set end to after focusNode parent
set start to before anchorNode parent
set end to after focusNode parent and set start to before anchorNode parent

So I go down through these four operations, applying each one to my range,  and after each I see if canSurround() returns true. When it does I stop and do the surround.
The code is:
case "RTE_h1_icon" :
                newNode = document.createElement("h1");
                var sel = rangy.getSelection();
                anchorParent = sel.anchorNode.parentNode;
                focusParent = sel.focusNode.parentNode;
                range = sel.getRangeAt(0);

                if(range.canSurroundContents()) {  // no modification
                    range.surroundContents(newNode);
                    break;
                }
                range1 = range;
                range1.setEndAfter(focusParent);  // adjust end
                if(range1.canSurroundContents()) {
                    range1.surroundContents(newNode);
                    break;
                }

                range2 = range;
                range2.setStartBefore(anchorParent);  // adjust start
                if(range2.canSurroundContents()) {
                    range2.surroundContents(newNode);
                    break;
                }

                range3 = range;
                range3.setStartBefore(anchorParent);  // adjust start
                range3.setEndAfter(focusParent);      // and end
                if(range3.canSurroundContents()) {
                    range3.surroundContents(newNode);
                    break;
                }
                break;

If anyone has a better solution or sees problems with what I'm doing I'd be glad to hear from you.
Thanks

Adding  around a selection


In the Benfica vs Man Utd match, why did the referee point to his watch after the goal?

Question: In the Champions League match between Benfica and Manchester United that happened on Oct 18, 2017, Rashford took a freekick, the Benfica goalkeeper misjudged the angle and trajectory of the freekick and carried the ball inside the goal. The referee was standing very far away, but even then he knew the ball had crossed and I think he said so by pointing to his watch. Why did he do that? Does the ball have some sort of GPS tracker that relays to the watch? Can someone explain this?
Answer: The UEFA Champion's League uses goal-line technology.
This is an automated system which detects the moment the ball has crossed the goal-line under the crossbar. It sends a signal to the referee via a wrist-mounted alarm unit to show a goal has been scored. This reduces the reliance on precise visual judgements from bad angles.
The referee indicated that the GLT unit had already signalled a goal.
Answer: The watch is the part of Goal Line Technology system,
Under IFAB LAW 1 - THE FIELD OF PLAY,

GOAL LINE TECHNOLOGY (GLT)
  The indication of whether a goal has been scored must be immediate and automatically confirmed within one second by the GLT system only to the match officials (via the referee's watch, by vibration and visual signal).

(my emphasis)
While the technology employed is Hawk-Eye based provided by Hawk-Eye Innovations Limited, to know how it works watch this video.

More information: fraunhofer.de, football-technology.fifa


After "?" redirect, the url is cut, why?

Question: I am using the Anonymous Redirect module to redirect example.com to example.com/login.
But when I refer a link like
example.com/525?some=node/227 and log in, the url will be cut to example.com/525
I don't know why the url is cut after "?" or "&".
Any solutions for this one?
Comment: i think you need to use l() function.
Answer: Even though I haven't ever used the Anonymous Redirect module, I wouldn't be surprised if your "issue" is caused by the fact that this module does not support what you're trying to do.
However, as a possible alternative (as per your "Any solutions for this one?"), you may want to use the Rules module to perform the redirect you want to do. For an example of how to do so, refer to my answer to "How to redirect an anonymous user to the login form after a 403 error?" (the "option 2" part of it. Not sure what exact "Rules event" would fit in your case, but it'll be probably something related to a specific "path" in your site.
Not sure if it would fit your needs here also, but maybe you want to add the "Rules URL argument" module also to this. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.


Alterando valor de objeto inserido em uma array

Question: Dê uma olhada neste exemplo: https://jsfiddle.net/b4w6jqgf/1/
Nele tenho duas arrays:
<code>__options e __defaultOptions;
</code>
Ao iniciar dou push em __options inserindo o objeto __defaultOptions.
Posteriormente efetuo a alteração do valor do objeto na posição 0, setando no campo "maxsize" o valor 1500.
Acontece que o valor é atribuído também em todas as outras posições da array.
Imagino que esteja apenas referenciando o objeto __defaultOptions nas posições do array, sendo o mesmo objeto em todas as posições, assim quando efetuo a alteração do valor em uma das posições, todos tem seu valor alterado.
Como posso contornar esta questão?
Há algum meio de importar os dados de um objeto em si, e não referenciar o objeto?
Answer: Bastou utilizar JSON.parse(JSON.stringify()) para criar uma cópia do objeto.
Demo da correção: https://jsfiddle.net/b4w6jqgf/2/


Order of using technologies during Cricket's review

Question: In cricket, during wicket review by third-umpire in Ashes 2013, the following technologies are used:
<code>1.Hot Spot
2.Hawk eye prediction
3.Snicko Meter
</code>
Is there any order in using these systems. I mean, as far as I have seen, umpires are analysing only hotspot at first, hawkeye in second and snicko in third. It may be either LBW review or catch review, this order is being used. Is there any reason for using them in order?
Comment: Snickometer was not used as part of the DRS in the 2013 Ashes. Umpires would use the sound feed to try and discern whether there was any noise that indicated an edge, but this was not fed into Snickometer (although, for purely interest's sake, later replays on the TV broadcast were able to apply Snickometer for extra analysis).
Comment: Don't forget old-fashioned video. They always/usually start with that, I believe. (First the bowler's front foot, ...)
Answer: Although i cant cite an official view on this but i think the order of using different technologies in DRS is based on logic of eliminating the options.
DRS is mostly used in 3 situations, "caught behind wicket", "caught by close-in fielders" & "LBW".
In the first two situations above, there is no need of hawk-eye. So the sequence will/should be
1)Check for No ball
2)A slow motion close-in camera replay(If the edge is clearly visible via an actual match feed than the hotspot is just an additional closing confirmation. If not, then hotspot is the crucial confirmation)
3)Sound feed from the stump mic(Again because real feed confirmation is better than a processed technological one. If the edge is clear & distinct then hotspot will seal the deal)
4)Hotspot
Note that as yet, snickometer has not been incorporated in DRS
In case of LBW, the sequence will/should be
1)Check for No ball
2)A slow-mo close-in camera replay(To check for an inside edge before hitting the pad. If clearly visible, then the next hotspot will confirm it & hence no need of hawk-eye)
3)Hotspot(If the inside edge is visible, hotspot will be the closing confirmation. If not then hotspot evidence will be the crucial confirmation required for Not Out)
4)Hawkeye(If there is "absolutely" no clear evidence of an inside edge, Hawkeye evidence becomes crucial for decision making. In case of an "inconclusive" inside edge, a Hawkeye showing ball going wide of the stumps or not hitting in line will make hotsopt irrelevant)
In case of LBW, hawkeye is checked after hotspot because the trajectory estimate of the ball depends on where it hits first. So, in case of inside edge, it will take the hit on the bat & estimate the trajectory, which if it hits the stump, gives the impression of OUT


How can I create a button with scaling text

Question: I have a TableLayout with cells, populated like this:
    TableLayout tableLayout = (TableLayout) getActivity().findViewById(R.id.button_table);

    for (int y = 0; y < 4; y++) {
        TableRow row = new TableRow(getActivity());
        row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

        for (int x = 0; x < 3; x++) {
            Button button = new Button(getActivity());
            button.setText("Button");
            button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mainPresenter.processAction(((Button)v).getText().toString());
                }
            });
            buttons.add(button);
            row.addView(button);
        }

        tableLayout.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
    }

This works nicely to start with, however sometimes the buttons have their text set to something that is too large for the allocated width. This results in the button expanding to accommodate the text.
I would like it to work the other way around - the buttons maintain their assigned width, and instead the font that is used shrinks to make sure that the text fits into the button. How can I do this?
Answer: when you add the button into a table row, instead of using buttons.add(button);, use buttons.add(button, new TableRow.LayoutParams(100, 100)); which would make the button be 100x100 large.
Comment: I don't want fixed size buttons - I just want the text displayed in them to fit to available size.


Combining token based authentication with Windows Authentication

Question: We currently have an internal API that uses Windows Authentication. I've been charged with looking into making this API public, and one of the requirements is that it should be possible to login without a domain user. Domain users should still be able to login, and should be considered super admins (access everything).
It is also clear that before long, we will need role or claim based authorization. As a prototype, I have implemented a system using ASP.NET Identity. Using JWT tokens and Claims based authorization.
But how do I ensure that users authenticated with Windows Authentication can skip the token step and simply use the API directly?
Answer: Found a solution where I add custom AuthorizationFilterAttributes to my endpoints. In the attribute, I check for the Principal type:
<code>    public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        if (actionContext.RequestContext.Principal is WindowsPrincipal)
        {
            return Task.FromResult<object>(null);
        }
        //Custom logic here
        [...]
    }
</code>


Whether an ordered field $K$ equipped with the Nested Interval Property or The Cauchy Complete Property is an archimedean ordered field

Question: The Nested Interval Property

For all sequences $\{a_n\},\{b_n\}\in K^\mathbb N$ satisfied that for every element $\varepsilon\in K_{>0}$ , there exists an $N\in\mathbb N$ such shat $|a_n-b_n|<\varepsilon$ for all $n>N$ and$$a_0\le a_1<\cdots\le a_n<\cdots\le b_n\le \cdots\le b_1\le b_0$$then there is $c\in K$ such that $$\bigcap_n[a_n,b_n]=\{c\}$$

The Cauchy Complete Property

For all $\{a_n\}\in K^\mathbb N$ satisfied forall $\varepsilon\in K_{>0}$, there is a $N\in \mathbb N$ such that $|a_n-a_m|<\varepsilon$ for all $n,m>N$ , then there is a $c\in K$ such that for all $\varepsilon\in K_{>0}$  there is a $N\in \mathbb N$ such that $|a_n-c|<\varepsilon$ for all $n>N$

The Archimedean Property

For all $x\in K$ and $y\in K_{>0}$ , there is $n\in\mathbb N$ such that $n\cdot y>x$ .

$n\cdot y$ is $$\underbrace{y+y+\cdots+y}_{n \ \text{times}}$$

I know an archimedean ordered field equipped with the Nested Interval Property or the Cauchy Complete Property is isomorphic to $\mathbb R$ and I'm wandering whether it can be proved except the Archimedean Property.
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Answer: No, the Archimedian property is necessary.  The ease of constructing a counterexample depends on your mathematical background.
Before I begin: (Cauchy) completeness is easily shown to be equivalent to the Nested Interval Property.  I will refer to the two interchangeably as completeness.
At the level of intuition, the problem is that the decimal expansion of a real number is "only" as long as $\mathbb{N}$.  There are analogues with longer "decimal sequences"Fn. 1, called the surreal numbers.  Wikipedia's (linked) construction is quite good, and no more complicated than Rudin's construction of $\mathbb{R}$ in Principles of Mathematical Analysis.
The Archimedian property encodes the length of the decimals when it restricts $n\in\mathbb{N}$.  Your definition of completenessFn. 2 does not; it depends on $\epsilon\in K^+$, which may be too small for decimals.  It admits more examples than the Archimedian property: the simplest is the Levi-Civita field; the most complex (IMHO) is the aforementioned surreals.
If you've seen some mathematical logic, then the nonstandard reals ${}^*\mathbb{R}$ are a slick counterexample.   That ${}^*\mathbb{R}$ is non-Archimedean is well-known: for any nonprincipal ultrafilter $\mathcal{U}$ and any $r\in\mathbb{R}$, $$(0,1,2,3,\dots)/\mathcal{U}>(r,r,r,\dots)/\mathcal{U}$$  But Cauchy Completeness is easily formalizable in first-order logic with quantification over $\mathbb{N}$, and so holds in ${}^*\mathbb{R}$ by the transfer principle.  (The transfer principle shows completeness for sequences indexed by ${}^*\mathbb{N}$, but this implies standard completeness a fortiori.)

Fn. 1 Technically, Dedekind cuts.
Fn. 2 There are other definitions of completeness that "bake in" the reals; these are equivalent to Archimediacy.


Xeon E5 V3 - 2S vs. 4S CPUs - L3 Cache Size Impact on Performance

Question: I've tried searching to answer this question, but I've found it difficult to get concrete information, so thought I'd ask here. Sorry for the complex title, but the essence of my question is this: in the Xeon E5 V3 family of CPUs, the 4S SKUs often have more L3 cache than the 1S/2S SKUs; does this provide a material benefit when using 4S SKUs in single/dual CPU configuration?
For instance, consider the following 2 broadly similar chips: E5-2620 v3 and E5-4655 v3. They're both 6 core/12 thread, both have 3.2GHz max turbo clocks, identical L1 cache (6x32 KB 8-way set associative instruction/data), identical L2 cache (6x256 KB 8-way set associative), but the E5-4655 v3 has a higher base clock (2.9GHz vs 2.4GHz) and double the L3 cache (30 MB 20-way set associative shared cache vs 15 MB 20-way set associative shared cache). Excepting the base clock difference, in varied workloads (including Windows/Linux/FreeBSD virtualisation, video transcoding, databases, archive compression/extraction etc), would it be reasonable to see a difference between these CPUs in a single/dual CPU configuration due to the L3 cache difference?
I ask because I've currently got a Dell R730 server with two E5-4655 v3 CPUs, and I'm considering a CPU upgrade in the not too distant future to a single CPU (I don't really need the PCIe lanes or extra memory capacity offered by the 2nd CPU and I'd like to cut power consumption and potential performance penalties inherent in a 2S system). Prices for used 2S CPUs are typically quite a bit lower than those for 4S CPUs with similar specs (core/thread count, base/boost clocks), but I wonder what impact halving the L3 cache would have. Keep in mind that if I did consolidate 2 CPUs into 1, I wouldn't be buying the E5-2620 v3 mentioned above (that was just for illustrative purposes); I'd be getting a >= 12 core part (as yet undecided).
I understand this question may not be simple to provide a concrete answer to, but would appreciate any input or relevant benchmark data. Thanks.
Answer:
I understand this question may not be simple to provide a concrete
  answer to, but would appreciate any input or relevant benchmark data.

Depends, especially since you described a varied and diverse workload. No way to know specifics short of you testing your workload. Benchmarks can define relative performance of one thing, but performance is more complex than that.
In general, of course newer microarchitecture, more cores, higher clocks, and more cache are better. But you have further constraints such as power and cost.
The Haswells you mention are several generations old now. Often that old isn't worth the power consumption, and raises concerns about the length of support left. Try one generation behind state of the art if you are looking for used or discounted.
Four socket capable system just for one socket and its cache seems dubious so long as Intel maintains a highly segmented product line with premium features.  Not the most perverse incentive on CPU economics, might make sense. But its rather contorted just because more cache looks tempting, need some data to support a decision like that.
Also consider if you are willing to evaluate other vendors. AMD EPYC has a simple one socket story. For example, the 16 core EPYC 7302P has 128 MB L3, same as the 2 socket capable EPYC 7302. Not the used Xeon you asked for, but it may provide price competition. AMD definitely wants to sell single socket systems.
Comment: Yeah, I wish I could afford to move to an EPYC platform, but this is just for homelab use, so I can't justify that at the moment. Thanks for your response though.
Answer: The premise of the question - that Xeon E5 4xxx always have more L3 cache than Xeon E5 2xxx - is not universally true. Take, as example, the Xeon 2690v3: it has 30 MB L3 cache, albeit being a 2S processor.
That said, the impact of halving the L3 cache on a Broadwell-based CPU is going to be totally dependent of the workload your application is putting on the processor: transcoding or other FPU heavy tasks will be almost unaffected, while virtualization and databases can show a 5-15% hit (at same clock/cores).
However, the key reason why 4S processors often have more L3 cache per core is that they use more complex NUMA layout, where the added cache means lower latency accessing main memory. Moreover, 4S systems can use a significant portion of the LLC (L3, in this case) for directory/snoop/coherency, "wasting" more cache than a 2S system (but this is strongly CPU and system architecture dependent).
For a future update with used parts, simply buy what will provide you the best band for the buck. If going for a large L3 CPU is expensive, simply avoid it (maybe investing in more clock/cores).
Comment: Yeah, the E5-2690 v3 is a good counterpoint. I've been considering it, but it's still a bit out of my price range for the moment (this is just for my homelab, so I don't have a real budget, as such). I don't really know much about the "directory/snoop/coherency" issues you mentioned, so I'll have to go and do some more research on those topics on my own. Thanks for the pointers.


Picking the top 10 answers from a survey

Question: I ran a survey on a population of advisors in all the different recruitment centers of in a country. I had 1410 text written entries (not multiple choice)
I took a sample of 284 to see what are the top 10 mistakes done by job seekers during interview.
My goal is to infer my result to the population of all advisors (which am defining as the total of 1410 entries). That is, what are the top 10 mistakes done my job seekers during interviews?
Now that I have the proportions of my 284 samples. I am not sure if I need to test first for the normality of my sample or determine another sample and perform an ANOVA test?
I am simply not sure how to proceed given my stated objective.
Thanks for the help
Answer: There's no ANOVA to do here - ANOVA relates a dependent variable to one or more independent variables. You haven't got that.  There's also no need for normality.
You have a multinomial distribution. But, you don't want to infer the proportions (which is tricky enough; see this paper) you want to see something about the top 10 in your population, based on the top 10 in your sample.
I doubt there is an analytic solution to this; I think you should try resampling of some sort. That is, simulate a population of 1410 responses with as many different answers as you got. Then repeatedly sample 284 and see how often the top 10 from the 284 match the top 10 from the 1410.


Ler uma Procedure de SGBD em ADVPL

Question: É possível ler uma Procedure de SGBD em ADVPL (linguagem da TOTVS) tratando o retorno de um Cursor ?
Existe algum objeto ?
O banco em questão é Oracle.
create or replace PACKAGE abc IS
   TYPE abcCursor IS REF CURSOR;
END;

create or replace PROCEDURE x (p1 IN VARCHAR2,
                               pCursor IN OUT abc.abcCursor)
   IS
BEGIN
  IF PCURSOR%ISOPEN THEN
     CLOSE PCURSOR;
  END IF;
    SELECT * from tabela where chave=p1;
END;

No caso chamar a SP x do advpl e ter o Cursor retornado.
Answer: No AdvPL existem três formas de executar um Statement em um SGDB através do DBAccess:

TCSPEXEC() -- Para executar stored procedures com um ou mais
parametros de entrada e/ou saída (O Retorno é uma lista dos
parametros definidos na Procedure como IN/OUT ou apenas OUT)
TCSQLEXEC() -- Para executar statements de DDL ou DML (Sem retorno de
dados, apenas Sucesso ou Falha)
TCGENQRY() -- Para executar um SELECT no SGDB (Uma Query, cujo
retorno seja ou possa ser tratado como um result-set.

A única função que tornaria visível ao AdvPL um result-set seria a TCGenQry(), usada em conjunto com a função DbUseArea() ou mesmo o comando USE ... Porém o DBAccess somente permite abrir um cursor usando a TCGenQry() s a instrução SQL seja iniciada com um SELECT. Una instrução SQL iniciada com "EXECUTE" ,"CALL" ou afins, se executada pela TCGenQry(), resulta no erro de execução "Invalid Select / Query Statement".
Já a função TCSqlExec() permite a execução de instruções SQL como INSERT, UPDATE, CALL, EXECUTE e afins, porém se a execução gerar um result set, ele não é recuperado no AdvPL.
Se, ao invés de criar uma Stored Procedure, você criar uma Table Function, será possível recuperar o retorno pelo AdvPL usando TCGenQry(). Para isso, veja o seguinte tópico: Procedure Oracle retornar linhas da consulta
Uma vez usando a alternativa acima, o cursor aberto no AdvPL não possui nenhuma diferença em relação a um result-set obtido com um "Select". Para maiores informações sobre como abrir um result-set em AdvPL, consulte a documentação da função TCGenQry.
Um cursor no AdvPL através do DBAccess usando a função TCGenQry() é sempre aberto como um cursor Read-Only e Forward-Only (somente leitura e leitura sequencial) endereçado através do ALIAS usado na abertura como parâmetro para a função DbUseaArea(). As colunas da linha atual de retorno são acessadas usando a sintaxe ALIAS->COLUNA. Para verificar se o cursor chegou ao final, use a função EOF(), e para buscar o próximo resultado do cursor, use a função DBSKIP() -- equivale a um Fetch no cursor.
Referências:

http://tdn.totvs.com/display/tec/TCGenQry
http://tdn.totvs.com/display/tec/TCSPExec
http://tdn.totvs.com/display/tec/TCSQLExec
http://tdn.totvs.com/display/tec/DBUseArea
http://tdn.totvs.com/display/tec/Comando+USE
http://tdn.totvs.com/display/tec/Comando+TCQUERY
Comment: E a manipulação do result set é equivalente ao retorno do cursor? Em nenhum momento de sua resposta eu vi você tratando disso em específico.
Comment: Valeu , vou testar.

Ler uma Procedure de SGBD em ADVPL


How do I build a graphical needle gauge UI widget in Android?

Question: I need a graphical needle gauge (like a speedometer etc) for my app but such a UI widget is not part of the SDK so I probably have to create it myself.
My idea is to have the background with the tickmarks and coloured fields (green, yellow, red) as one bitmap and the needle as another bitmap drawn on top of the background, but rotated in the appropriate angle.
In my book, Professional Android 2 Application Development, there is a somewhat similar example with a compass rose, although that one is drawn using line graphics, not pre-fabricated images like I will have to use to get the desired look.
However, in the compass example the whole canvas is rotated before drawing the tick marks. I cannot use this approach as it will also rotate the gauge background. So I need to somehow rotate the needle image (which should be transparent) before superimposing it. But I don't know how to do accomplish this.
Can anyone lead me in the right direction on how to proceed with the needle gauge? Also, if there is a better way to build the meter than sketched above, please let me know.
Answer: You can divide your guage into different layers. One for background, one for tick marks. Layer for tick marks can be rotated to draw marks and when turned back and combined with 'background' layer.
You can see the following example with layer technique described above: http://mindtherobot.com/blog/534/android-ui-making-an-analog-rotary-knob/
P.S. This is not my blog, i've just found this technique there.
Comment: Thank you so much for that link!!!

The same guy has this tutorial also which is exactly what I need: http://mindtherobot.com/blog/272/android-custom-ui-making-a-vintage-thermometer/

Since my phone has no temperature sensor, I needed to set the temperature manually in the code; apart from that it works right away.

Now I can model my meter after this. Fantastic :-)


R/mgcv: How do you interpret the 'fixed effects' for multivariate te() tensor products in the 'lme' part of a gamm model in R?

Question: When fitting a 'gamm' model in the R package mgcv, and using a te() tensor product of three variables, the lme part of the model reports seven fixed effects, from 'Fx1' to 'Fx7', with coefficients and standard errors.
How should one interpret those coefficients?
example:
library(mgcv)
dat <- gamSim(1, n = 200, scale = 2)
b <- gamm(y ~ te(x0, x1, x2), data = dat)
summary(b$lme)

produces:
...
                      Value Std.Error  DF  t-value p-value
X(Intercept)       7.967688  0.151562 192 52.57042  0.0000
Xte(x0,x1,x2)Fx1 -11.272537  3.361371 192 -3.35355  0.0010
Xte(x0,x1,x2)Fx2  -5.423052  4.190418 192 -1.29416  0.1972
Xte(x0,x1,x2)Fx3  -0.203082  3.594615 192 -0.05650  0.9550
Xte(x0,x1,x2)Fx4  -6.921183  2.853750 192 -2.42529  0.0162
Xte(x0,x1,x2)Fx5  14.069427  3.367979 192  4.17741  0.0000
Xte(x0,x1,x2)Fx6 -16.363401  3.427253 192 -4.77449  0.0000
Xte(x0,x1,x2)Fx7  -8.381191  2.955847 192 -2.83546  0.0051

I suppose that:

Xte(x0,x1,x2)Fx1 is the slope of the first linear basis function, in x0
Xte(x0,x1,x2)Fx2 is the slope of the second linear basis function, in x1
Xte(x0,x1,x2)Fx3 is the slope of the third linear basis function, in x2
Xte(x0,x1,x2)Fx4 is the slope of the fourth linear basis function, in x0:x1
Xte(x0,x1,x2)Fx5 is the slope of the fifth linear basis function, in x0:x2
Xte(x0,x1,x2)Fx6 is the slope of the sixth linear basis function, in x1:x2
Xte(x0,x1,x2)Fx7 is the slope of the seventh linear basis function, in x0:x1:x2

Is this correct?
Thanks!
Answer: Yes, these fixed effect terms relate to the unpenalized functions in the basis (i.e. those functions in the null space). Note that what is in the null space entirely depends on the order of derivative-based penalty used; the default is m = 2 so only linear/planar functions are unpenalised, but if you change this — or alter whether the function's basis even has a null space (via m = c(2, 0) say) — you'll get different basis functions in the null space and hence fewer/additional functions depending on settings.
There isn't a simple interpretation for these basis functions; that they're displayed in the fixed effects when you fit the model via lme() or (g)lmer() is just a side effect of the way the model has to be represented when using mixed effects software. If you were to refit the model using random effect smooth terms with gam() you wouldn't see this decomposition of penalized and unpenalized basis functions. You would see just the fitted smooths and you would just plot the resulting estimated function.
Comment: Thank you very much for your response Gavin. I have another doubt derived from your answer: Does the p-value of a basis function indicate whether a factor has a significant effect on the response variable? If we fit the model `gamm(y ~ s(x0) + s(x1), data = dat)` and `Xs(x0)Fx1` has a p-value of 0.36, can we say that the factor `x0` is not related to `y` and therefore should be removed from the model? Thank you again
Comment: No, you can't interpret it that way, Look at the model you fitted; it is basically two functions $f_1(x_0)$ and $f_2(x_1)$. You should do inference on those *functions*, not the individual basis functions that happen to be used to represent $f_1$ and $f_2$ in the model. In the same way that if you fitted `lm(y ~ poly(x0, 4))` you wouldn't remove the terms associated with $x_0^3$ just because it had a large p-value. You would be interested in the fit of the 4-th order polynomial over a 3-rd order one, say via a LRT.


What's the deal with VARs?

Question: I'm new to econometrics/statistics. Why are Vector Autoregressive (VAR) equations considered a separate class of models in textbooks, apart from ARs? Isn't it true that you can estimate the equations one by one and arrive at the same estimates compared to estimating the equations simultaneously? Why even call them VARs instead of saying "we have multiple AR models"?
Answer: First of all, multiple AR would normally mean that only own lags are included as regressors in each equation. Meanwhile, lags of other endogenous variables are included in addition to own lags in a VAR.
Regarding estimation: technically, you may indeed estimate VAR using equation-by-equation OLS. However, it need not always be the efficient way to do it. Generally, a feasible GLS estimation is the efficient one.
One notable exception where feasible GLS does not improve on equation-by-equation OLS is when the set of regressors (the right hand side variables) are the same in each equation in the system. Another exception is when the error terms are uncorrelated across equations.
Most of the textbooks covering VAR models consider these issues and provide a more detailed discussion then here.
Answer: They are vector autoregressions because the residual covariance matrix and the coefficient covariance matrix can have (but does not always have) relationships among residuals/coefficients of different equations. Actually, this is something you can input into your prior, or parameterize your likelihood function to take these cross-equation relations into account.

What's the deal with VARs?


Unity C# ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

Question: I'm creating a game that is like snake. In my code below, each segment of the snake's body is an instance of the Character class. When I try to add a new character, I get the error:
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

Other resources online have proposed that there's a List that is empty that I'm trying to reference. But I don't see any evidence of that case in my code.
Perhaps someone smarter than myself can find what I've done wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/*
 * This class controls the entire snake. The snake has a list
 * of segments that are each a character. We can move along the snake
 * by moving the characters bottom up, so that the character replaces
 * the position of the character before him.
 */

public class PlayerController : MonoBehaviour {

//how many units will he move per 'frame'
public float moveUnits = 1;
//how often he will move (every quarter second)
public float moveTimer = 0.25f;
private float timeSinceLastMoved;
public KeyCode dir = KeyCode.RightArrow;
//locations of boundaries
public float topBoundary = 4.5f;
public float bottomBoundary = -4.5f;
public float leftBoundary = -8.5f;
public float rightBoundary = 8.5f;
//Holds all characters for the snake body
public List<Character> chars = new List<Character>();

// Use this for initialization
void Start () {
    timeSinceLastMoved = Time.time;
    getFirstCharacter ();

}

// Update is called once per frame
void Update () {
    getInput ();

    if (timeSinceLastMoved + moveTimer < Time.time) {
        move ();
        timeSinceLastMoved = Time.time;
    }

}

void getInput() {

    //if i press right go right, but i can't be going left when i want to go right
    if (Input.GetKeyDown (KeyCode.RightArrow) && dir != KeyCode.LeftArrow) {
        dir = KeyCode.RightArrow;
    } else if (Input.GetKeyDown (KeyCode.LeftArrow) && dir != KeyCode.RightArrow) {
        dir = KeyCode.LeftArrow;
    } else if (Input.GetKeyDown (KeyCode.UpArrow) && dir != KeyCode.DownArrow) {
        dir = KeyCode.UpArrow;
    } else if (Input.GetKeyDown (KeyCode.DownArrow) && dir != KeyCode.UpArrow) {
        dir = KeyCode.DownArrow;
    }

    //for testing character addition
    else if (Input.GetKey (KeyCode.A)) {
        addCharacter ();
    }

}

void move() {

    float x = 0;
    float y = 0;

    if (chars.Count != 0) {

        //moves the transform in the appropriate directions
        switch (dir) {
        case KeyCode.RightArrow:
            x = transform.position.x + moveUnits;
            y = transform.position.y;
            break;
        case KeyCode.LeftArrow:
            x = transform.position.x - moveUnits;
            y = transform.position.y;
            break;
        case KeyCode.UpArrow:
            x = transform.position.x;
            y = transform.position.y + moveUnits;
            break;
        case KeyCode.DownArrow:
            x = transform.position.x;
            y = transform.position.y - moveUnits;
            break;
        default:
            break;
        }
        //prevents him from moving outside the set boundaries
        x = Mathf.Clamp (x, leftBoundary, rightBoundary);
        y = Mathf.Clamp (y, bottomBoundary, topBoundary);
        Vector2 pos = new Vector2 (x, y);
        //this moves the whole snake
        transform.position = pos;
        //this moves the first snake segment
        chars[0].transform.position = pos;

        //for all characters(aka snake segments)
        //take the position of the segment before you
        for (int i = chars.Count - 1; i > 0; i++) {
            chars [i].transform.position = chars [i - 1].transform.position;
        }
    }

}

void addCharacter() {
    //the position of the last segment
    Vector2 prevCharPos = chars[chars.Count-1].transform.position;
    Vector2 pos;
    float x = 0;
    float y = 0;
    switch (dir) {
    case KeyCode.RightArrow:
        x = prevCharPos.x - moveUnits;
        y = prevCharPos.y;
        break;
    case KeyCode.LeftArrow:
        x = prevCharPos.x + moveUnits;
        y = prevCharPos.y;;
        break;
    case KeyCode.UpArrow:
        x = prevCharPos.x;
        y = prevCharPos.y + moveUnits;
        break;
    case KeyCode.DownArrow:
        x = prevCharPos.x;
        y = prevCharPos.y - moveUnits;
        break;
    default:
        break;
    }
    pos = new Vector2 (x, y);
    //make a new character at the position behind the last segment
    Character newChar = Instantiate (chars[chars.Count - 1], pos, Quaternion.identity, this.transform);
    //add him to the list
    chars.Add (newChar);
}

void getFirstCharacter() {
    //find the character that already exists and add him to the list
    GameObject firstChar = GameObject.Find ("Character");
    if (firstChar != null) {
        chars.Add(firstChar.GetComponent<Character>());
    }
}

}
Comment: Hope that it is not your first post, and you know how to ask a question. then why this much of unnecessary lines of codes?
Comment: Just my intuition - check this line if you are playing with for loop correctly?

for (int i = chars.Count - 1; i > 0; i++) {
            chars [i].transform.position = chars [i - 1].transform.position;
Comment: What line you get that exception? Debugging to that point me help you to understand the cause of problem!
Comment: Can you tell us which line you are getting the error?
Comment: Looks like error is at line `Character newChar = Instantiate (chars[chars.Count - 1], pos, Quaternion.identity, this.transform);` in `addCharacter`method. `chars[chars.Count -1]` will throw exception if `char.Count` is zero.
Answer: Change your FOR loop condition. Theoretically, it will throw out of range exception.
for (int i = chars.Count - 1; i > 0; i++)
   chars [i].transform.position = chars [i - 1].transform.position;
I believe your intent should be
for (int i = chars.Count - 1; i > 0; i--)
Answer: Just put you for loop inside an if check
            if(chars.Count>0){
            //for all characters(aka snake segments)
                    //take the position of the segment before you
                    for (int i = chars.Count - 1; i > 0; i++) {
                        chars [i].transform.position = chars [i - 1].transform.position;
                    }
            }
            else{
               Debug.Log("Warning:: chars Count is less than 1");
}

Answer: According to MSDN documentation ArgumentOutOfRangeException is :

The exception that is thrown when the value of an argument is outside
  the allowable range of values as defined by the invoked method

Which means, the exception will raise when you tried to access an item from a collection based on its index value but actually that index is not within the range of indices. most of the cases collections follows 0 based indexing so if your specific value is below 0 or it is greater than the number of elements in the collection will lead to this exception while accessing.
When we goes through the given snippet, we can see that you have used chars [i - 1] in different places, obviously this will cause Exception when value of i is 0.
In short we can say that, Let chars be a collection and you are accessing the items based on index, it is important to check chars.Count > 0 if you are accessing a previous item  using i-1 and also the loop limit should be less than chars.Count.
This may be a generalized answer, but hope that it helps you to understand the reason for this error and how to solve them


When does IIS log a request?

Question: This sounds silly, but when do they log requests? I have a web application, and about 500 HTTP proxies that will load up that application. But problem is sometimes (and this morning a lot), the proxy (using php sockets) believes it connected and the response that came back was blank.
BUT IIS has no log of this request.
When does IIS log a request? Could it be rejecting the connection, and not even processing the request?
Answer: IIS logs requests after they have completed.  W3WP.exe logs to memory after the response has been sent to the client.  Then, at regular intervals (usually less than 10 seconds) W3Wp.exe writes to the IIS log file specified in the Website configuration.  You may have to wait several seconds before requests are visible in the IIS log file.  I believe that HTTP.sys is written to in realtime.  If you don't see your requests in the IIS log file, check that you are indeed visiting the website you think you are.  You can also check the most recent \%systemroot%\System32\LogFiles\HTTPERR log file for your request... if IIS can't handle your request, HTTP.sys will log why IIS could not accept the request.  Hope this helps.
-Chris
Comment: Kenny, the log includes the time taken to execute the request... therefore, the request must be complete before that information is available for logging.
Comment: Do you have any sources for your claim that requests are logged after they've completed? I'm not disputing the claim so much as curious about the context or background about this behavior.
Comment: That helped me, we could not find request in IIS logs, but we found canceled request their. Thx a lot.

When does IIS log a request?


docker container: can't access dotnet web api container from another container

Question: I have created dotnet core web API which runs in a docker container.
when I try to call the API from my browser (Chrom) I got the result, but when I try to call the API from an angular app which is also running in a docker container I got a connection_faild error.
the docker file for the web API :
FROM microsoft/dotnet:2.2-sdk
COPY /pub/ /root/
WORKDIR /root/
ENV ASPNETCORE_URLS="http://*:5000"
EXPOSE 5000
ENTRYPOINT ["dotnet", "Backend-lite.dll"]

to run the container:
docker run -p 5000:5000 netcore-rest

docker file for the angular app:
FROM node:8.11.2-alpine as node
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx:1.13.12-alpine
COPY --from=node /usr/src/app/dist/myapp /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/conf.d/default.confs

to run the angular container:
docker run -t -p 80:80 angular

I'm using this connection string to connect to the API from the angular app
const BASE_URL = 'http://localhost:5000/api/';

I have also tried to create a network between the two containers but it didn't work.
docker network create --gateway 172.16.1.1 --subnet 172.16.1.0/24
app_subnet

then I ran the api container:
docker run --name server --ip 172.16.1.2 -p 5000:5000 --network
app_subnet dotnet

the angular container :
docker run --name app --ip 172.16.1.3 -p 4200:80 --network app_subnet
angular

and I changed the connection string in the angular app to match the container's IP
const BASE_URL = 'http://172.16.1.2:5000/api/';

I'm new to docker so can someone help me find the problem.
Answer: Try 'http://host.docker.internal:5000/api/'
Localhost would be the loopback of the container but you want the host PC's port 5000
Answer: The best suggestion would be to use docker-compose as you are using two separate services. https://docs.docker.com/compose/gettingstarted/
In your angular container then you can use the service name instead of IP Address or localhost.
For your reference example
https://github.com/DanWahlin/Angular-Docker-Microservices/blob/master/docker-compose.yml
Comment: thank you, I did use docker-compose like in the example, but it didnt work!
Comment: Could you please share you docker-compose file


Wireless Accessory Configuration (WAC) in iOS integrate and how to use

Question: how to add the Wireless Accessory Configuration (WAC)into the app and use the features. I am using this for the first time. Also tried find few tutorials for the same in google but was not successful. I need to know how to integrate that in my app and use the files of the same.
Thanks in advance.
Comment: If you are succeed to integrate WAC.please share
Comment: Can you share some code please.
Comment: @shasha  HI, Are you done with integrating?
Answer: to integrate WAC to your you need go through libraries in following link:
// take a look at eawifiunconfiguredaccessorybrowser , this class helps you to handle WAC, this would suffice your need.
https://developer.apple.com/reference/externalaccessory/eawifiunconfiguredaccessorybrowser?language=objc
i will brief you about adding WAC feature your app.
step1
enable WAC capabilities in app target ,as shown in picture below :
enabling WAC in capabilities section of App target
step2
make use of eawifiunconfiguredaccessorybrowser methods :
*startSearchingForUnconfiguredAccessoriesMatchingPredicate --> helps to search for run configured accessories
*configureAccessory:withConfigurationUIOnViewController: --> does configuration by presenting system based screen.
it will work similar to WAC done through iOS setting app.
Comment: @n devaraj Hi, Can we also control video processor through wifi?
Comment: @AnuragSharma if you plan to communication with Process with MFI certificate you can refer to  link below https://developer.apple.com/documentation/externalaccessory/easession?language=objc
Comment: @n devaraj Thank you for your suggestion, Actually, I am connecting using NSStream now. As my hardware has IP and port number.


C# Multi threading- Move objects between threads

Question: i am working with a winforms control that is both a GUI element and also does some internal processing that has not been exposed to the developer. When this component is instantiated it may take between 5 and 15 seconds to become ready so what i want to do is put it on another thread and when its done bring it back to the gui thread and place it on my form. The problem is that this will (and has) cause a cross thread exception.
Normally when i work with worker threads its just with simple data objects i can push back when processing is complete and then use with controls already on the main thread but ive never needed to move an entire control in this fashion.
Does anyone know if this is possible and if so how? If not how does one deal with a problem like this where there is the potential to lock the main gui?
Comment: Can the initialization work be spun off into its own thread, apart from the control itself?
Comment: Hi Robert unfortunately not no.
Comment: How about breaking of the initialization to a "ControlContext", initialize the Context in a thread and posting it back to the control, in effect setting Control.Properties from Context.Properties?
Comment: Hi Patrick unfortunately the initialization is tightly coupled with the control.
Comment: (You could probably solve this with some reflection and _really nasty_ unsafe code, but I would weep every time I looked at it and I sure as hell wouldn't want anyone to credit that code back to me.)
Answer: You don't need to lock the GUI, you just need to call invoke:

Controls in Windows Forms are bound to
  a specific thread and are not thread
  safe. Therefore, if you are calling a
  control's method from a different
  thread, you must use one of the
  control's invoke methods to marshal
  the call to the proper thread. This
  property can be used to determine if
  you must call an invoke method, which
  can be useful if you do not know what
  thread owns a control. ref

Here is how it looks in code:
public delegate void ComponentReadyDelegate(YourComponent component);
public void LoadComponent(YourComponent component)
{
    if (this.InvokeRequired)
    {
        ComponentReadyDelegate e = new ComponentReadyDelegate(LoadComponent);
        this.BeginInvoke(e, new object[]{component});
    }
    else
    {
        // The component is used by a UI control
        component.DoSomething();
        component.GetSomething();
    }
}

// From the other thread just initialize the component
// and call the LoadComponent method on the GUI.
component.Initialize(); // 5-15 seconds
yourForm.LoadComponent(component);

Normally calling the LoadComponent from another thread will cause a cross-thread exception, but with the above implementation the method will be invoked on the GUI thread.
InvokeRequired tells you if:

the caller must call an invoke method
  when making method calls to the
  control because the caller is on a
  different thread than the one the
  control was created on.
  ref

Update:
So if I understand you correctly the control object is created on a thread other than the GUI thread, therefore even if you were able to pass it to the GUI thread you still won't be able to use it without causing a cross-thread exception. The solution would be to create the object on the GUI thread, but initialize it on a separate thread:
public partial class MyForm : Form
{
    public delegate void ComponentReadyDelegate(YourComponent component);
    private YourComponent  _component;
    public MyForm()
    {
        InitializeComponent();
        // The componet is created on the same thread as the GUI
        _component = new YourComponent();

        ThreadPool.QueueUserWorkItem(o =>
        {
            // The initialization takes 5-10 seconds
            // so just initialize the component in separate thread
            _component.Initialize();

            LoadComponent(_component);
        });
    }

    public void LoadComponent(YourComponent component)
    {
        if (this.InvokeRequired)
        {
            ComponentReadyDelegate e = new ComponentReadyDelegate(LoadComponent);
            this.BeginInvoke(e, new object[]{component});
        }
        else
        {
            // The component is used by a UI control
            component.DoSomething();
            component.GetSomething();
        }
    }
}

Comment: @Grant, create the object on the GUI thread and initialize it on the worker thread (since you said the initialization takes 5-10 seconds). I've updated my answer with that in mind.
Comment: @Grant If you initialize the component via BeginInvoke, then it will cause the initialization to occur on the UI thread since it was created on the UI thread... I just realized this problem. Trying to think of a workaround. It's a catchy question.
Comment: Doesn't this suffer from the same problem that the O.P. wanted to avoid? Namely, he wants to initialise his control in the background so it doesn't block the GUI thread as it takes 15 seconds to initialize. If Invoke is used to marshall execution back to the GUI thread, will that not still block the GUI thread?
Comment: @Tim, I assume that the component will already be initialized in a separate thread when the OP calls yourForm.LoadComponent. The GUI will not be burdened with the initialization.
Comment: hi, im not sure if ive made myself clear. using delegates and background workers isnt working as all they are doing is passing back a reference to my object. The object is still on the worker thread and the gui thread cant make use of it.
Comment: Thanks Lirik your suggestion seems to work. The only thing I've noticed is that even though its on a separate thread and its initialized via the begin invoke - its still behaving as though its all on the one thread again (blocks the UI for 10+ seconds). Maybe because the object is on the main thread invoking to it blocks it just the same as if there was no worker thread at all. does that make sense?
Comment: Yeah i know. one of the more challenging multi threading issues i've had to deal with..
Comment: @Grant, can you briefly tell us what does the initialization of the component entail? Can you put any of the initialization parts on a separate thread?
Comment: Not really sure TBH. Its a closed component. It goes off and does some data fetching and processing from a remote location. So theres TCP activity and number crunching, database etc. Have been over the component using redgate reflector and cant see any public methods or ways to separate it out.
Comment: @Grant, I don't know if I can be of any further help here... let's see if anybody else can come up with a better solution.
Answer: Without knowing too much about the object. To avoid cross thread exceptions, you can make the initial thread invoke a call (Even if you are calling from a thread).
Copied and pasted from one of my own applications :
 private delegate void UpdateStatusBoxDel(string status);

    private void UpdateStatusBox(string status)
    {
        listBoxStats.Items.Add(status);
        listBoxStats.SelectedIndex = listBoxStats.Items.Count - 1;
        labelSuccessful.Text = SuccessfulSubmits.ToString();
        labelFailed.Text = FailedSubmits.ToString();
    }

    private void UpdateStatusBoxAsync(string status)
    {
        if(!areWeStopping)
            this.BeginInvoke(new UpdateStatusBoxDel(UpdateStatusBox), status);
    }

So essentially the threaded task will call the "Async" method. Which will then tell the main form to begininvoke (Actually async itself).
I believe there is probably a shorter way to do all of this, without the need for creating delegates and two different methods. But this way is just ingrained into me. And it's what the Microsoft books teach to you do :p
Answer: The BackgroundWorker class is designed for exactly this situation. It will manage the thread for you, and let you start the thread, as well as cancel the thread. The thread can send events back to the GUI thread for status updates, or completion. The event handlers for these status and completion events are in the main GUI thread, and can update your WinForm controls. And the WinForm doesn't get locked. It's everything you need. (And works equally well in WPF and Silverlight, too.)
Comment: hi, im not sure if ive made myself clear. using delegates and background workers isnt working as all they are doing is passing back a reference to my object. The object is still on the worker thread and the gui thread cant make use of it.
Comment: The backgroundworker object can send progress messages to the GUI thread, and can include an object in the message. That will make the object available to the GUI thread.
Answer: The control must be created and modified from the UI thread, there's no way around that.
In order to keep the UI responsive while doing long-running initialization, keep the process on a background thread and invoke any control access.  The UI should remain responsive, but if it doesn't, you can add some wait time to the background thread.  This is an example, using .Net 4 parallel tools: http://www.lovethedot.net/2009/01/parallel-programming-in-net-40-and_30.html
If interaction with the specific control being initialized can't be allowed until initialization finishes, then hide or disable it until complete.
Comment: Hi Ragocrazy, Im not following. If the control is created and modified on the UI thread (main thread) - how can i keep the process on a background thread??
Comment: Try to divide your work into processing that doesn't directy affect the UI and the UI updates, then use BeginInvoke (or Invoke) for the UI updates.  This way all the processing that can is done on the background thread and you only marshal to the UI thread when necessary.

So, for insance, adding items to a listbox -- all the retrieval from a database, formating of text, etc, can be done on the background thread and then only the Add() has to use BeginInvoke.  The rest of the UI will still be responsive to the user (and the listbox, too, if you make it visible).


geometry theorems on triangles

Question: Having _________ in common is NOT proof that 2 triangles are congruent
a) 2 angles and the included side
b) two sides and the included angle
c) 2 angles and one excluded side
d) 3 sides
e) none of the above
Based from my geometry book, I think the answer is e. Is this correct?
Comment: You are going to have to be much more specific. Theorems about what? What about the angles and sides?
Comment: Side angle side (SAS, AAS, SSS, etc)
Comment: These are theorems on geometry and this is a multiple choice question so I am to select one of the following choices above
Comment: Yes, but what is the question...?
Comment: Think carefully about c...
Answer: Part c is the correct choice. Two triangles might have two angles equal (which means all angles are equal, that is, the triangles are similar) and two sides equal, without being equal themselves.
For instance, you may have $ABC\cong A'B'C'$ (meaning the angle $A$ is equal to the angle $A'$, etc...) and $AB=B'C'$. If you had $AB=A'B'$, then yes, the triangles would be equal; now however they need not be.
The word excluded is also key here. There are two excluded sides, so we can't tell which matches to which...

geometry theorems on triangles


Executing command line app

Question: I am trying to execute JAD decompiler on class file from code:
Process p = Runtime.getRuntime().exec("c:\\1\\jad.exe c:\\1\\EIn.class");
//All paths are correct, "c:\\1\\jad.exe c:\\1\\EIn.class" wotks when I run it in cmd

When I debug i don't get any errors, debugger moves to the next line...
if I put:
int res = p.waitFor();

It just hangs.
Update:
BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String str = null;
while ((str = in.readLine()) != null) { //Stucks here
}

Comment: See http://stackoverflow.com/questions/12433888/use-java-to-start-a-windows-exe/12433899#12433899
Comment: what should i see there?
Comment: I don't understand you. what /k argument?
Comment: Use the cmd to launch it. The '/k' arg causes to wait in the cmd.
Answer: Is the jad decompiler waiting on input from you via stdin?
To see the errors that you are getting, consume the getOutputStream and getErrorStream to see what the decompiler is writing out.
You can use the ProcessBuilder class to make redirecting streams a little more pleasant.
Comment: with file ProcessBuilder it also gets stuck
Answer: public static void main(String[] args) throws Exception {

    String[] cmd = { "c:\\1\\jad.exe", "-c:\\1\\EIn.class" };
    Process p = Runtime.getRuntime().exec(cmd);
    p.waitFor();
}

Answer: This is a TRAP in Java ,please just have a look at this page,you will get more than you wanna!

Executing command line app


Dúvida para trazer dados do mysql

Question: Estou com a seguinte dúvida. Considere que tenho os seguintes dados de vendas:
Dois Estados ex: São Paulo (Atibaia, São Paulo e Campinas) e Paraná (Londrina, Curitiba, Cascavel).
| cidade    | estado | vendas |
|-----------|--------|--------|
| Cascavel  | PR     | 10     |
| Curitiba  | PR     | 8      |
| Londrina  | PR     | 3      |
| Campinas  | SP     | 3      |
| São Paulo | SP     | 5      |
| Atibaia   | SP     | 3      |

Preciso trazer as cidades dos seus respectivos Estados que possui o maior número de vendas.
Fiz esse comando: para fazer um count na cidade aí traz a soma, porém preciso separar agora as cidades. nesse caso teria que trazer São Paulo e Cascavel.
 select
  count(d_clientes.cidade_nome), f_pedidos.cliente_sk, d_clientes.cliente_sk, d_clientes.cidade_nome, d_clientes.estado_nome, d_clientes.estado_sigla
 from
 f_pedidos
 inner join d_clientes on f_pedidos.cliente_sk = d_clientes.cliente_sk
group by d_clientes.cidade_nome

Comment: lol n entendi nada o enunciado , edita ai rsss - tipo posta sua estrutura do db e exatamente como vc quer ordenar.
Comment: acho que dá pra usar o MAX do SQL
Comment: @JasarOrion ele entende bem de SQL, top
Answer: Podemos quebrar esse problema em duas partes. Primeiro precisamos contar a quantidade de vendas por cidade e estado:
SELECT cidade, estado, count(*) FROM vendas
GROUP BY cidade, estado
ORDER BY estado, count(*) DESC;

Com isso temos o resumo já ordenado.
| cidade    | estado | count(*) |
|-----------|--------|----------|
| Cascavel  | PR     | 10       |
| Curitiba  | PR     | 8        |
| Londrina  | PR     | 3        |
| São Paulo | SP     | 5        |
| Campinas  | SP     | 3        |
| Atibaia   | SP     | 3        |

E como encontrar a cidade que mais vendeu por estado?
Para isso precisamos incluir um ranking das cidades que mais venderam por estado, algo assim:
| cidade    | estado | count(*) | ranking
|-----------|--------|----------|---------
| Cascavel  | PR     | 10       | 1
| Curitiba  | PR     | 8        | 2
| Londrina  | PR     | 3        | 3
| São Paulo | SP     | 5        | 1
| Campinas  | SP     | 3        | 2
| Atibaia   | SP     | 3        | 3

Isso pode ser feito de forma bem simples com uma window function. Colocando isso numa subquery, o trabalho final seria fazer um filtro onde o ranking é igual a 1:
SELECT * FROM (
    SELECT cidade, estado, count(*),
      row_number() over (partition by estado order by count(*) DESC) as rank
    FROM vendas
    GROUP BY cidade, estado
    ORDER BY estado, count(*) DESC;
) AS sub
WHERE rank = 1;

Porém, o MySQL não suporta window functions :(
Para chegarmos ao mesmo resultado, é preciso algumas adaptações na parte referente ao ranking:
-- Não esqueça de definir as variáveis! Elas são importantes
SET @currcount = NULL, @currvalue = NULL;
SELECT cidade, estado, qtd_vendida FROM (
  SELECT *,
      @currcount := IF(@currvalue = estado, @currcount + 1, 1) AS rank,
      @currvalue := estado AS bla
  FROM (
    SELECT cidade, estado, count(*) as qtd_vendida
    FROM vendas
    GROUP BY cidade, estado
    ORDER BY estado, count(*) DESC
  ) AS vendas
) AS ranking
WHERE rank = 1

Veja funcionando no SQL Fiddle.
Referências:

http://tapoueh.org/blog/2013/08/20-Window-Functions
https://blog.jooq.org/2013/11/03/probably-the-coolest-sql-feature-window-functions/
https://stackoverflow.com/a/30269273/2099835

Dúvida para trazer dados do mysql