What is the advantage of async over BeginXXX/EndXXX?

Question: When looking for an elegant way to asynchronously receive a stream of datagrams from a UDP socket, I came across this question: How to use asynchronous Receive for UdpClient in a loop?
The advantages of the first answer I understand, as they use the familiar BeginReceive/EndReceive methods. This solution is nice in that there are no threads hanging around being blocked.
The second answer, however gives two different Task-ish solutions, one using ReceiveAsync and the other using the synchronous Receive method. I'm wondering, in this case, what the advantage is. As I understand it, even in the ReceiveAsync case, there's still a (threadpool?) thread waiting around for things to happen.
Is there an advantage in using Async methods in this case? If not, is there a way to implement this type of pattern using Async methods without the overhead of a thread, task, or other blocking object?
Comment: `As I understand it, even in the ReceiveAsync case, there's still a (threadpool?) thread waiting around for things to happen.` The whole point of async is that that is not true.  Read http://blog.slaks.net/2014-12-23/parallelism-async-threading-explained/
Comment: @SLaks See the linked post; it is in fact unnecessarly allocating a thread pool thread to do some work, although not quite as much as the OP thinks.
Comment: You are getting a rosy picture from that 2nd answer.  He intentionally doesn't do anything with the data that's received and does not deal with any errors.  Once you flesh that in you'll definitely see the difference.  Those details get pretty nasty in a hurry with APM.
Comment: @Servy: That's a good point; his `Task.Run()` call is completely useless.
Comment: In particular, the `*Async()` methods are just friendlier wrappers around the `Begin*()` methods.
Answer: First of all, in a naturally asynchronous API there are no blocked threads in both the async-await (TAP) version and Begin/End(APM) (There Is No Thread).
In this specific case however, the linked answer does waste a ThreadPool thread unnecessarily and this should be avoided.
The ReceiveAsync case offloads the synchronous part of the operation (until await ReceiveAsync) to a ThreadPool thread. This is useful if you have a substantive CPU-bound operation to perform and you want to free up the calling thread. This doesn't seem to be case as there's nothing to do other than create the client.
You can simply remove the Task.Run and have an async method:
async Task ListenAsync(int port, CancellationToken token)
{
    using (var client = new UdpClient(port))
    {
        while (true)
        {
            var result = await client.ReceiveAsync().WithCancellation(token).ConfigureAwait(false);
            // process result.Buffer
        }
    }
}

Comment: Yes, in a naturally asynchronous API there is no thread, but in the example that the question specifically  mentions it is not a proper implementation, it *does* unnecessarily create thread pool thread, the use of `FromAsync` isn't necessary, as there is already a `Task` returning async method, and your comments on the TPL being preferable as a paradigm are rather offtopic in the face of the question, which is asking about properties of a specific implementation *using that paradigm*.
Comment: @Servy The OP asked (specifically in the title) about advantages of TAP over APM and different TAP versions. This answer cover the general case and the specific case.
Comment: So you read the title and none of the body of the question?  The body of the quesiton makes it very clear that it's not asking about the difference between different approaches to asynchronous methods.
Comment: @Servy I've read **both**. And answered **both**. Which is crucial since this post would be the end result of future Google searches. And *"even in the `ReceiveAsync` case, there's still a (threadpool?) thread waiting around for things to happen."* makes that a lot less clear than you make it seem.
Comment: So it's important to ask a question that the OP isn't actually asking, because future readers might make the same mistake that you did and  believe that the OP is asking something completely different?  If someone finds a question that seems similar but is in fact asking about something different than what they're asking about, then they can't really expect to get the answer to their question.  You cannot answer everything about everything in the event that someone wanting to know something else just happens to find the question.
Comment: @Servy I don't think the OP is really **only** concerned about that specific issue when the title is irrelevant and they mention waiting `ThreadPool` threads. If you're so sure about that then I suggest you edit these issue out of the question. I'm not **that** sure and so instead of assuming one way or another I gave the exact literal answer and the more general scope in which it stands.
Comment: If the OP had no idea that a properly asynchronous implementation wouldn't involve thread pool threads waiting on the operations then why would be asking if the example that he saw actually needs to create a thread pool thread and asks if it is indeed causing a thread pool thread to wait for the operation?  If he didn't know that async IO didn't need to involve thread pool threads waiting, he wouldn't have asked the question he did in the first place.  You're also burying the actual answer to the question (which you edited in later) inside a bunch of content that he already knows.
Comment: @Servy The OP may know what's a proper asynchronous implementation but it seems they are asking whether `async-await` is indeed that proper implementation (as opposed to `BeginX/EndX` which they know as a proper implementation).
Comment: No, he's asking if this particularly TPL implementation is implemented correctly, and if not, how *should* this operation be properly implemented in the TPL.  He's given no reason to believe that he doesn't understand that the TPL vs. other asynchronous operations are all capable of solving various problem, it's purely a matter of how easy/hard it is to do.
Comment: @Servy And again, I think that both the title and quote are reasons enough to doubt that.
Comment: The title gives reason to doubt that, the body of the post leaves little doubt.  The quote is very much the reason that makes most of your answer irrelevant.  The quote indicates that he knows a properly implemented asynchronous solution shouldn't involve tying up a thread pool thread, but the linked post does in fact appear to be doing that (it isn't, but it isn't immediately obvious that that's the case without a through understanding of how `Task.Run` works).  That he's bringing up the concern is exactly why you can know that he is aware of most of what you've said here.
Comment: @Servy is correct; What I'm asking here is, "if the linked example is correct, what's the point of XXXAsync?". The secondary question would be, "if the linked example is incorrect (as it appears to be), what is the correct implementation?"
Comment: @Mark great. So by explaining the point of `XAsync` I show that the linked example is incorrect. And since it's incorrect I added a correct implementation. Is that too much?
Comment: @i3arnon Your answer is great as far as the question goes, but your implementation doesn't solve the problem in the linked question, which is, "how do I do this in a loop?". Your implementation only receives a single datagram. Either way, you get credit for this one.
Comment: @Mark true. I've added a `while` and `CancellationToken` (you should also take a look at this if you actually plan on using it: [Async network operations never finish](http://stackoverflow.com/q/21468137/885318))
Comment: @i3arnon once you put the `while` loop in there, I think you've fallen into the same trap? I.E. you're just holding a thread around which continually awaits something. I think you need a .ContinueWith() in there instead.
Comment: @Mark Then @Servy wasn't right. You're not holding any threads. You use the calling thread until you reach the `await` the first time. When it completes you get another thread from the `ThreadPool` that executes the contents of the `while` loop until it reaches `await`. The thread is then freed while you asynchronously wait for the receive operation to complete and so forth and so forth. You're never holding a thread while you wait. You only get a thread when the task completes.
Comment: @Mark Logically `ContinueWith` and `await` are not that different.
Answer: Well, it's not allocating a thread pool thread to sit around and wait for the async operation to finish.  Rather, it's allocating a thread pool thread to start the asynchronous operation, instead of starting it in the current thread.
There really isn't any reason to do this, at least unless the act of starting the asynchronous operation takes a long time, and it really shouldn't if it has been written correctly.
Can you implement the same thing without starting the async operation in a thread pool thread, sure, just remove the code to start it in a thread pool thread.


Was von Neumann right that 'with four parameters you can fit an elephant'?

Question: I was looking into free parameters and found this previous nice answer to
What is a "free parameter" in a computational model?
Is it possible to actually demonstrate that with x free parameters, any function can be approximated?
For example, in $A=aB^2+bB+c$, could a,b,c (free parameters) allow me to turn this into whatever shape I want? Or are there limits to this?
Answer: (1) Any function can be modelled by itself, using no free parameter: $f(x)=f_1(x)$, where $f_1(x):=f(x)$.
(2) For any model, with an arbitrary but finite number of degrees of freedom, $a_1 f_1(x)+a_2 f_2(x)+\dots$, there always exists a function that is very far away from being able to be modelled with that model. (This can be given a precise mathematical formulation. For your quadratic model, for example, you'll not be able to model a function with both a maximum and a minimum using that model)
What von Neumann meant was along the lines of statement (1): Since there are infinitely many ways to choose a model (the model itself, i.e. the functions $f_i$, not the parameters of a fixed model) it's not a great feat to find good fits to data even with small models. Even though standard models might not contain the function $f$ that you are trying to model, if you look through enough models with 4 degrees of freedom, you'll find an exotic one that models your data very closely just by coincidence.
Answer: No, a fixed number of parameters for a fixed parametrisation is not enough to approximate any general function $f$.
If you are interested only in a particular class of functions, and the model is true, then yes, you can approximate all of them with a fixed number of arguments. For instance, if the functions $f$ that you want to approximate happen to be all real valued with real argument and linear, then you only need 2 parameters to approximate any such function, since $f(x) = a x + b$ by assumption. But as soon as the assumption is false, 2 parameters won't be enough.
More generally, a model is a simplifying assumption about the form of $f$. For instance, one can choose the model to be a finite subspace of a function space which is dense in a space where you assume $f$ to live in
E.g. if you assume $f$ to be continuous, by Stone-Weierstrass you know that for every $\epsilon > 0$ there is some polynomial $p$ of unknown order $n=n(f, \epsilon)$ uniformly approximating it within distance $\epsilon$. So in principle you need only $n+1$ parameters to get $\epsilon$ close to a fixed $f$, but you don't know $n$ since it will change for each $f$. So you can try with a polynomial space of fixed high order, knowing that your approximation will almost certainly be off, unless the $f$ generating the data happens to be a polynomial of degree less or equal to the degree you fixed.
Another example of a model is a truncated Fourier series. Under mild assumptions on $f$, Fourier series are good approximators. The more parameters (coefficients of the series) that you add, the closer your approximation will be to the true function, but this proximity depends on the regularity of $f$, about which you don't know anything a priori. So again, you fix a space with say 50 coefficients and there will always be an integrable function which cannot be well approximated with that number. For instance there will be issues like the Gibb's phenomenon if $f$ has any jumps.
Neural networks are another family of good approximators ("good" meaning with few parameters) for certain very general classes, but it can be proven that they can also be very bad, requiring an exponentially large number of parameters to approximate some functions.
If you consider fixing the number of parameters and swapping the model, then you can improve the fit, i.e. reduce the distance between the best approximation in your space and $f$. And this leads to the assertion: there will always be some space where just a few parameters are enough to fit your data (we are assuming no noise).
Comment: Misread the question! A fixed number of parameters cannot approximate any function, of course


a theorem about regularization of function

Question: Theorem:
Let $u(x)$ is locally integrable function on $R^n$,
 $\phi= e^{\frac{1}{|x|^2-1}}, when |x|<1;\phi= 0, when |x|\geq 1  $
$\alpha(x)=\frac{1}{C}\phi$
where $C=\int_{R^n}\phi(x)dx$
and $\alpha_{\epsilon}(x)=\frac{1}{{\epsilon}^n}\alpha(\frac{x}{\epsilon})$
then $u_\epsilon(x)=\int_{R^n}u(x-y)a_\epsilon(y)dy$ is a $C^\infty$ function.
The proof is so brief:
$a_\epsilon$ is a infinite continues differentiable function, so use the interchangeabilty of $\frac{d}{dx}$ and $\int$, we can have $u_\epsilon(x)=\int_{R^n}u(x-y)a_\epsilon(y)dy$ is a $C^\infty$ function.
I'm still don't know how to proof it.
can you give me a step-by-step proof? thanks a lot!
Comment: It is a convolution product.
Comment: And you need more hypothesis on $a_\epsilon$ for $u_\epsilon$ to be defined. Is $a_\epsilon$ a compactly supported function ?
Comment: Sorry I forgot that, I've added those definitions in.
Comment: yes, according to definition of $a_\epsilon(x)$, it's support is $\{x: |x|<\epsilon\}$
Answer: Let $\epsilon >0$, we will try to prove that
$(u * a_\epsilon)'(x)=u * a_\epsilon'(x).$
To begin, let $h>0$ :
$$\frac{u * a_\epsilon(x+h)-u * a_\epsilon(x)}h=\frac 1 h \int_{R^n}u(y)a_\epsilon(x+h-y)dy-\frac 1 h \int_{R^n}u(y)a_\epsilon(x-y)dy$$
By linearity of the integral :
$$\frac{u * a_\epsilon(x+h)-u * a_\epsilon(x)}h=\int_{\mathbb{R}^n}u(y) \frac 1 h\left[ a_\epsilon(x+h)- a_\epsilon(x) \right] dy.$$
Hence :
$$\lim _{ h \to 0 } \frac{u * a_\epsilon(x+h)-u * a_\epsilon(x)}h = \lim _{ h \to 0 } \int_{\mathbb{R}^n}u(y) \frac 1 h\left[ a_\epsilon(x+h-y)- a_\epsilon(x-y) \right] dy.$$
Let $x \in \mathbb{R}^n$, then : $\forall 0<h<1, \frac 1 h\left[ a_\epsilon(x+h-y)- a_\epsilon(x-y) \right]$ is compactly supported in some $K_{x,\epsilon}$. Hence :
$$\lim _{ h \to 0 } \int_{\mathbb{R}^n}u(y) \frac 1 h\left[ a_\epsilon(x+h-y)- a_\epsilon(x-y) \right]dy= \lim _{ h \to 0 } \int_{K_{x,\epsilon}}u(y) \frac 1 h\left[ a_\epsilon(x+h-y)- a_\epsilon(x-y) \right]dy.$$
Now, we have, by some famous inequality, since $a_\epsilon \in C^1$ and has its support in $K_{x,\epsilon}$ being compact :
$$\left| a_\epsilon(x+h-y)- a_\epsilon(x-y) \right| \le \| a_\epsilon'\|_\infty h.$$
In other words :
$$\left|u(y) \frac 1 h\left[ a_\epsilon(x+h-y)- a_\epsilon(x-y) \right] \right| \le \| a_\epsilon'\|_\infty\left|u(y)\right|.$$
Since $u$ is locally integrable : $\| a_\epsilon'\|_\infty\left|u(y)\right| \in L^1(K_{x,\epsilon})$, then we can, by dominated convergence theorem, exchange $\lim$ and $\int$ :
$$\lim _{ h \to 0 } \frac{u * a_\epsilon(x+h)-u * a_\epsilon(x)}h =  \int_{\mathbb{R}^n}u(y) \lim _{ h \to 0 } \frac 1 h\left[ a_\epsilon(x+h-y)- a_\epsilon(x-y) \right] dy=\int_{\mathbb{R}^n}u(y) a_\epsilon'(x-y) dy.$$
The right term exists and is well defined, then, if $a_\epsilon \in C^1$  :
$$(u * a_\epsilon)'(x)=u * a_\epsilon'(x).$$
Since $a_\epsilon \in C^\infty$, we have, by induction, for all $n \in \mathbb{N}$ :
$$(u * a_\epsilon)^{(n)}(x)=u * a_\epsilon^{(n)}(x).$$
Since $x$ is arbitrary, $u * a_\epsilon \in C^\infty$.
Comment: Thank you!  I think the second formula can be deleted. Am I right ?
Comment: They all seem important to me to make the path clear.
Comment: It seems haven't been used in the following path..
Comment: It seems haven't been used in the following path..
Comment: Then may be I do not understand which formula you are talking about.
Comment: I've mentioned about $

u∗a_\epsilon(x+h)−u∗a_\epsilon(x)h=\int_{R^n}{u(y)\frac{1}{h}[a_\epsilon(x+h)−a_\epsilon(x)]}dy.
$  Thanks !:)
Comment: May be the step was obvious, but I think it helps understanding the whole process.
Comment: understand! thank you for your reply :)


Get author id in field template - or make an edit button on a node's teaser

Question:
I am using Display Suite to display Teasers of a custom content type Project in a View.
I want to show link on each Teaser to edit that node if the logged in user is the author of the node.
Our requirements do not allow us to use Contextual Links with the little hover gear.

Things I have tried:

I was also able to make a Display Suite field for [node:author:uid] and display that field in the Teaser.
I was able to create a Display Suite field to hold the link and display it in the Teaser.
I was able to create a custom field template for that Project Edit Button field I just made and display it in the Teaser. field--field-project-edit-button.html.twig.
This is where I hoped to wrap the content of that field (the link) in a conditional statement.

However

In the past I have been able to access fields in a different field's template using this technique. {{ element['#object'].field_name.value }}
I was able to do this with a Display Suite field for [node:nid] and then do {{ element['#object'].nid.value }} (where nid is the machine name of my [node:nid] Display Suite field) in the Project Button field template above.
It also works to use it in a conditional statement like {% if element['#object'].nid.value == 6 %}.
But this same technique is not working with {{ element['#object'].aid.value }} (where aid is the machine name of my Display Suite 'Author ID' field). It just comes back empty.

So
What is different about my [node:author:uid] and [node:nid] fields?
Why am I seeing the actual Author ID field properly but not {{ element['#object'].aid.value }} in the edit link's field template?
How do I make this silly button? I am completely open to other ways of doing this as long as it meets my requirements at the top of this post.
FULL SOLUTION, thanks to No Sssweat below
Display Suite token field:
 Edit [node:title]

In the .theme file under mytheme_preprocess_field
/* Make the current user id available in field templates */
$vars['uid'] = \Drupal::currentUser()->id();

In that custom field template:
{% if element['#object'].getOwner.uid.value == uid %}
  {% for item in items %}
    {{ item.content }}
  {% endfor %}
{% endif %}

Comment: `where aid is the machine name of my Display Suite 'Author ID' field`. Did you manually create this Author ID field? perhaps the machine name is actually `field_aid`.
Answer: Assuming in your use case an Author is a user on your site, I believe you will be able to access to Author's ID using
{{ element['#object'].getOwner.uid.value }}
No need to create a custom field to hold the author's value.
Comment: Thank you! Going to put my snippets in the main question.
Answer: First, this should be the simplest way for getting the the author's id in a twig template.
{{ node.getOwnerId }}

Second, I would use the path() function and the entity.user.canonical route with the user id to create the link to the user's page. This won't break if you choose to alias the user pages.

   {{ author_pic }}


Trying to access node content with PHP

Question: I have the following code to load a different node into my homepage:
<?php $node = node_load(2); ?>

      <button class="close" data-dismiss="modal">×</button>

<?php echo $node->title; ?>

      <?php render( $node->content ); ?>

      Close

The title displays, but the content doesn't. I get the error Notice: Undefined property: stdClass::$content in include()
Based on what I read here I feel this should work. What do I need to do to make the node content display? (it's just a basic page w/ title and body)
Answer: The node's content isn't built when you load the node, you need to invoke it manually with node_build_content():
$node = node_load(2);
node_build_content($node, $view_mode);

// You now have access to $node->content

Comment: What Clive said.
Comment: render( $node_content ) isn't doing anything. I guess I will have to find which section or the array I need
Comment: @Damon It should be `print render($node->content)`, the node is an object once it's loaded
Comment: ah I was assuming the echo/print was included with the render. beautiful!

Trying to access node content with PHP


How do I PXE boot multiple Windows 7 desktops off the same image?

Question: Some years ago at my university, I recall that the labs there booted Windows NT over the network.
There was a shared drive for your own stuff and other than that any changes you did to the running OS were reset when you restarted the machine.
Now I'd like to be able to do the same thing with Windows 7.
I have found some how to's for this using iSCSI, but I don't want an iSCSI disk for every single PC, I want one image for multiple PC's. I've also found PXE Boot setup files for installing Windows locally, but that's not what I want either.
How would I go about setting up what I had at university but with Windows 7 as a OS to netboot?
i.e. How do I netboot Windows 7 images? I do not want to netboot a Windows 7 installer to a PC to install Windows locally, I want to run a Windows 7 image from memory/network.
Comment: "with a Windows7 image on it". How do you generate pxe bootable images? I presume these have to run like a livecd.
Comment: @HopelessN00b I think Matt is asking about *how* to build/configure custom WIMs to boot via PXE.  Perhaps info about PXE booting multi-gig WIMs would also be helpful?
Comment: Absolutely.  They will be multi-gig.  On Linux I can use nfsroot which means for large images they don't all have to be in memory. What option is there for windows? minimal windows and software installed on SMB share?
Comment: What about virtual desktops?  Run multiple instances of windows on a central server and then clients can access them with a wide variety of clients.
Comment: Citrix Provision server had this feature. I could boot an entire 30 station lab (All the same hardware) with out having an local harddrive installed. It did a PXE Boot and booted from an disk image. Users then logged in and saved data to a network drive. It was very fast and not hard to setup. But alas it was too expensive and so I am back to the old method of booting from a local harddrive. I also would like to accomplish this.
Comment: @Chris S - what about CUDA?  according to this, no because it's still an emulation layer.  http://stackoverflow.com/questions/2260931/cuda-program-on-vmware
Comment: You'd set up a server with a Windows7 image on it, set your clients to PXE boot and... well, what's the real question or issue here?
Comment: @Matt You're looking to netboot into a Window7 image, not "deploy"/install a Windows7 image to clients, right?
Comment: That's exactly what I'm asking.  I'll update the question with that stated.
Comment: The problem with virtual desktops is that you don't get access to the graphics hardware. Also, have you ever tried to watch a video over terminal server? it's generally unwatchable.  So while I think VD is a good solution in some instances... it's not for mine.
Comment: @Matt, Not only does Hyper-V and ESX have remote hardware video acceleration these days, but Terminal Server 6.0+ with MSTSC 7.0+ plays 1080i over GbE fairly well.
Comment: Remote desktop is not a practical solution when you want access to cuda for your local graphics hardware.  What if you have 50 PC's needing it?  Sharing one or two GPU's in a server isn't going to cut the mustard sorry.
Answer: To answer my own question.  It is possible using iPXE and iSCSI or AoE.  The idea is to either replace the network card option ROM with iPXE or to chainload ipxe and then do a sanboot.
iSCSI is the easier of the two san protocols because you can actually install Windows 7 directly to an iSCSI target.  This is because iSCSI support is built into windows 7 while AoE is not.
See: archive.org mirror of windowsdiskless.wordpress.com
Or: archive.org mirror of windowsdisklessaoe.wordpress.com
Noting of course that although iSCSI supports multiple machines accessing the same target with NTFS.  Corruption will occur.  Either a Copy on Write mechanism at the back end needs to be employed, or create a base image (template) and copy that to a newly exported target.
I ended up patching the open source iscsi target from freebsd and adding copy on write.  So I could use the same LUN but the writes were directed elsewhere.  I was able to direct them to local RAM or to another file on the server. I'm not using this anymore though, it was a proof of concept.
Comment: Doing this with block-level storage will lead to NTFS corruption. In your question you state that you want *multiple* computers to be able to boot the same installation. Mounting and sharing the same NTFS volume across multiple clients will cause corruption, file lock issues, etc. Have you actually tried this?
Comment: I'm aware of that issue.  You can do this with a copy on write mechanism at the back end or copy the base image as a template to a new copy and export that.
Answer: The scenario you describe essentially amounts to the use of each workstation as a thin client to access a centrally located desktop environment. It would be highly impractical for Windows 7 to boot from PXE even if it could be done.
Whenever PXE is used to boot, it downloads the entirety of the boot image to the client system, which would mean several GB of transfer at each boot.
Ideally, this scenario is accomplished by keeping the desktop environments on the network in the central location. In a Virtual Desktop Infrastructure (VDI) environment, this is accomplished using virtualization to allow separate virtual desktop environments to reside together on hardware, the virtual environments are provided to the clients through a manager. In a session based environment, each user's desktop environment launches natively on the server and is brokered to the clients through a technology like Remote Desktop Services.
In both instances, the workstation must still run an operating system; however it is typically a very lightweight operating system providing a basic interface for the hardware and a client for redirection to the server hosting the desktop environments. For customers with Software Assurance, Microsoft provides Windows Thin PC as a lightweight operating system designed to connect through Remote Desktop Services to a Windows Server. Additional features supported like RemoteFX support for enhanced graphics, DirectAccess VPN connectivity, and BitLocker encryption help to provide the optimum thin client operating system for repurposing desktop hardware.
If the above sounds like the right route for you, you can find more information, guides for IT professionals, access to trials and betas, and much more in the Desktop Virtualization Center of the Springboard Site on TechNet.
Answer: It's not possible to boot Windows 7 over PXE or anything similar to that. Windows PE (Pre-Installation Environment; which is licensed only for maintenance and installation purposes and has nothing like a normal Windows Desktop) can be PXE booted. Certain other versions of Windows that you're not interested in can also be PXE booted, but nothing like a Desktop OS.
Most Enterprise-grade iSCSI targets can do thin provisioning, where they use the same base image for all systems and only the differences take up extra space. Also, Windows doesn't support single instance boot (yet; it's something MS has been kicking around internally for a while now). So each computer does need to see different storage, they can't yet share.
Comment: The Etherboot CoW stuff looks interesting, but a kitten dies every time a SysAdmin deploys AoE =[
Comment: AoE has nothing but MAC filtering for security. The whole RFC is 7 pages long. iSCSI has CHAP password authentication, standard firewall rules, IPSec, *and* MAC Filtering. iSCSI is slower than AoE, unless you have iSOE NICs (iSCSI Offload Engine Network Interface Cards), which accelerate iSCSI similar to TOE (TCP Offload Engine). Regardless, AoE can't be routed over the Internet, so hacking it is pretty tough; iSCSI best practices are to vLAN the SAN traffic; hacking any form of SAN is oddly rare.
Comment: @Matt That's the problem with questions like that, it used to be an emulation layer in ESX (and several other visualization platforms). That's not the case now however, and there are virtualization extensions for the PCI Express bus itself to make passthrough easier, with less overheard, and with more features (this only applier to fairly recent hardware, look for PCIe-IOV and PCIe-ATS). For ESX [VMware KB 1010789](http://kb.vmware.com/kb/1010789) has instructions for setting up the passthrough. KVM & Xen works (note: may not work with just any hardware). Hyper-V doesn't (thanks MS)
Comment: After some more research I found ccboot. And then I found AoE and vblade and this link looks promising. http://www.etherboot.org/wiki/appnotes/cow
Comment: It should have better performance than iSCSI though.  AoE isn't exactly that secure.  If an iSCSI target were to be compromised surely iSCSI is not any more secure as AoE.  Once you break into the target you're in.  A hacker could just delete the filesystem if they have enough permissions.
Comment: Thanks that's really interesting.  The other problem with AoE is that it would appear it is not very friendly to other network traffic.  Which may cause some problems if there is a lot of AoE traffic on the network.
Answer: not possible to use same image, but you can use the deduplicated filesystem to use a lot of cloned images and safe disk space, i think the result will be the same.
Try to use my distro with SDFS, OpenDHCP for simple configuration and AoE to boot diskless Windows...
http://windowsdisklessaoe.wordpress.com
and the preview release of distro here:
http://susestudio.com/a/UZQFsW/windows-diskless-with-aoe
Answer: xMy solution for identical problem:
Hardware: Igel Thin Client (winNET p680, 1.5 Ghz, 1 GB CF, 1 GBit NIC in pci)
does a IPXE-Boot to iSCSI-disk with Windows 7 ThinPC (ISCSI is located on nas4free)
The Steps are:

Format USB / CF with FAT32 with freeware USBFormat
Install grub4dos on USB / CF and copy files "grldr" an "menu.lst" from grub4dos
directory to USB / CF
with editor change menu.lst
default 0
title Windows ThinPC
kernel /ipxe.lkrn
build with "rom-o-matic.eu" ipxe.lkrn and save it after download on USB /CF
choose advanced and linux kernel
Attention 1: only mark option for booting iSCSI, rest unchanged
Attention 2: Embedded script is (change ip an iqn !):
"#!ipxe
dhcp net0
sanboot iscsi:192.168.???.???::::iqn.2007-09.jp.ne.peach.istgt:disk?
set keep-san 1"
With Virtualbox I installed a Windows 7 TC VM. The disk has to be VHD with fixed size (
7 GB and later expanded on LUN to 25 GB).
Then I "restored" with winimage 9.0 the VHD to iSCSI from my Windows machine.

Remark for owners of Igel:
The Igel TC has now dual monitor in Windows 7 (driver from Top4download 22.00.01u). For Audio use Vinyl Deck. The Igel performs like a desktop. The processor isn't lame.

The Solution from windowsdiskless isn't smart and simple and did not work for me.
Comment: I ended up modifying the source code to a popular iSCSI client and adding in a new backend with copy on write.  Writes went to temporary storage or ram if you choose.


How do I add a SwitchBar in my app?

Question: I'm trying to use a SwitchBar from the Android Settings app in my app but after adding it to my activity and adding in all the required parts to get it to compile, I get this compilation error: Error inflating class com.android.settings.widget.SwitchBar.
Here are the changes I made to get it to compile:
Added this to my attrs.xml
<attr name="switchBarTheme" format="reference" />
<attr name="switchBarMarginStart" format="dimension" />
<attr name="switchBarMarginEnd" format="dimension" />

Added this to my dimens.xml

<dimen name="switchbar_margin_start">16dp</dimen>
<dimen name="switchbar_margin_end">16dp</dimen>

Added this to my styles.xml

Added this to my Activity.xml
<com.android.settings.widget.SwitchBar
    android:id="@+id/switch_bar"
    android:layout_height="?android:attr/actionBarSize"
    android:layout_width="match_parent"
    android:background="@drawable/switchbar_background"
    android:theme="?attr/switchBarTheme"
    />

If this isn't a good way of adding a SwitchBar, how can I exactly replicate the SwitchBar in my app?
Answer: Your attributes already defined in SwitchBar.java in settings.This file involve marginend and other properities.And also switch_bar id.Please check this java file and later you can use in this file keys and attributes or you can define different name from there.

How do I add a SwitchBar in my app?


Is it possible to set multiple decorators for a single node?

Question: Something like
<button decorator='initbutton:p1, p2; tooltip:Text' />

I have found a decorator helper plugin for combining decorators:
http://martypdx.github.io/ractive-decorators-helpers/
Is it the best option right now?
Answer: Ractive doesn't natively support multiple decorators, at least not yet. The decorator helper plugin that you found is the best option right now.
Someone opened an issue on GitHub to request this feature if you want to chime in.
Answer: Use ractive-multi-decorator.
First install it:
npm install ractive-multi-decorator --save

Then add it to ractive:
var ractive = new Ractive({
    ...
    decorators: {
        multi: require('ractive-multi-decorator')
    },
    ...
});

Then use it:

Credits go to akhouzy and martypdx.
Comment: Also tested this https://github.com/ractivejs/ractive/issues/399#issuecomment-128687437 — works fine for me
Comment: Thanks!
Will try to use it first and then will change the accepted answer.


Expected value of an exponential martingale

Question:
Consider the symmetric random walk $(S_n)_{n \ge 0}$ on $\mathbb{Z}$. For real $u \ne 0$ consider the exponential martingale $Z_n = e^{uS_n}cosh(u)^{-n}$ of the symmetric random walk $(S_n)_{n \ge 0}$ on $Z$.
Show that the martingale $Z$ is not $L^p$-bounded for any $p > 1$ by computing $\mathbb{E}[Z_n^p]$.

I do not see how to start with this. I guess that we should use the optional stopping theorem, which yields
$$\mathbb{E}[Z_n^p] = \mathbb{E}[Z_0^p] = \int_{- \infty}^{\infty} u \cdot e^{uS_0p}cosh(u)^{-0 \cdot p} du.$$
However,  I do not see how to go on from here.
Answer: The step $\mathbb{E}[Z_n^p] = \mathbb{E}[Z_0^p] $ is not valid: it is true that $(Z_n)$ is a martingale, but $(Z_n^p)$ is not a martingale.
It is possible to compute $\mathbb E\left[Z_n^p\right]$ explicitely by using independence of the increment of the random walk, denoted $X_j$, namely, $\mathbb E\left[e^{upS_n}\right]=\prod_{j=1}^n\mathbb E\left[e^{upX_j}\right]=\left(\cosh(pu)\right)^n$, where the last equality follows from the fact that $\mathbb P(X_i=1)=\mathbb P(X_i=-1)=1/2$. You will get that $\mathbb E\left[Z_n^p\right]=a^n$ for some $a$ that you will have to show that it is greater than one, by strict convexity of $t\mapsto t^p$.
Comment: $X_i$ is $+1$ with probability one half and $-1$ with probability one half. So the expectation $E[e^{upX_i}]$ is...
Comment: Thanks for your answer, but I do not get why $\prod_{j=1}^n\mathbb E\left[e^{upX_i}\right]=\left(\cosh(pu)\right)^n$. Could you please explain this?
Comment: Sorry, but I still do not see it. I get that $\mathbb{E}[X_i] = 0$, but why should this imply that $\mathbb{E}[e^{upX_i}] = \cosh(pu)$, shouldn't it be $\mathbb{E}[e^{upX_i}] = 1$?
Comment: The random variable $e^{upX_i}$ takes the value $e^{up}$ with probability $1/2$ and $e^{-up}$ with probability $1/2$.


firefox - how to clear http / https cache?

Question: I've recently completely switched to Firefox Developer Edition but I have a problem I've not been able to handle yet on FF.
I'm a web developer so it happened to me to have several subdomains which corresponds to a test env of a live website.
exemple : http://local.example.com is my local for https://www.example.com
As it's a common problem to have modules licensed for a domain and its subdomains, I have to process this way to have a correct development environment (with the same modules than the live env).
My problem is the following : if I go to https://www.example.com Firefox will remember that it accessed it in https and will force my local to https://local.example.com instead of http://local.example.com (and of course the https on my local is not configured)
Cleaning the browser cache does not help (it solved the problem on chrome).
Changing the ttl of the dns to 0 in Firefox config did not help.
Restarting the browser does not help neither.
In the developer panel settings, i checked "disable http cache when dev tools is open", it did not worked.
At the moment, I have to work on my local in a private window, which is not very practical.
Does anybody knows how I can flush this cache in Firefox ?
Even better : is there a way to disable this cache ? As I'm using the developer edition, that would be awesome to be able to disable it at least on this version.
Thanks!
Answer: Since the root domain seems to affect the other domains, it may seem you are using HSTS to make sure all requests are https.
You have 3 solutions to fix this:
Exclude subdomains on the main HTST header
The simplest solution for you and all other developers working on your site may be removing the includeSubDomains on the HTST header on your main domain. (But beware that this decreases security if you actually use other subdomains)
Use a private window
HTST domains are not shared by to a private window for privacy reasons
Get an free SSL certificate for local.example.com
Temporary redirect the global local.example.com domain to your computer, and use letsencrypt to get a certificate for your pc
Comment: According to the following resource: https://support.mozilla.org/nl/questions/919498#answer-311682 you can right click in the history menu on the site, and then forget this site, and if you then open it in a new tab, it should work. But I don't use Firefox on the PC I'm on at the moment, so I couldn't verify the answer
Comment: OK thanks for your answer. I understand that if I want to do it permanently, there's no other way than what you described. But what if I just want to flush the "domain cache" which contains which protocol my browser have to use for a domain and its subdomain ?
Comment: Thank you for your complete answer. I'll continue to use private browsing for now and when I'll have some extra time, I'll proabbly generate certificates with lets encrypt. Have a nice day!


Bivariate normal distributed vector $X (X,Y)$. Show distribution of $(X-Y, X+Y)$.

Question: I have a a bivariate normally distributed random vector $X = (X,Y)$ and with Expected Value $(X)= (\mu(x),\mu(y))$, and Covariance Matrix $2\times 2$. (not independent)
Now I want to show which distribution $(X-Y, X+Y)$ has.
I first took the bivariate normal density function and simply replaced $X$ by $X-Y$ and $Y$ by $X+Y$ but I don't quite know how to continue .
Comment: The notation $X=(X,Y)$ seems troublesome. I recommend editing your question and using a different symbol (there are two $X$s).
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: That is actually what I wanted to do, it is the same X and Y. However, I do agree I should change variables while calculating
Comment: The expected value(s) should be easy enough
Answer: The mean vector is easy:  $E(X\pm Y) = E(X) \pm E(Y)$ so
$$
\left< (X-Y,X+Y) \right> = (\mu(x)-\mu(y),\mu(x)+\mu(y)) = (<X>-<Y>, <X>+<Y>) $$
As to the covariance matrix:
$$<(X-Y)^2> - (<X-Y>)^2 = \\<X^2> + <Y^2> - 2<XY> - (<X>)^2 - (<Y>)^2 + 2<X><Y> =\\
[ <X^2> - (<X>)^2] + [ <Y^2> - (<Y>)^2] -2[<XY>-<X><Y>]
$$
and each expression in square brackets is recognized as an entry in the covariance matrix for $X,Y$.  Similarly for each of the other three elements in the covariance matrix of $X-Y, X+Y$.
$$<(X+Y)^2> - (<X+Y>)^2 =\\ <X^2> + <Y^2> + 2<XY> - (<X>)^2 - (<Y>)^2 - 2<X><Y> =\\
\sigma_x^2 + \sigma_y^2 -2\sigma_{xy}
$$
and
$$<(X-Y) (X+Y)>  - <X-Y><X+Y>  =\\ <X^2> - <Y^2> - (<X> - <Y>) (<X> + <Y>)
\\=
[<X^2>-(<X>)^2  ] - [<Y^2>-(<Y>)^2  ] = \sigma_x^2 - \sigma_y^2
$$


Tentar verificar se um dia está inserido num intervalo entre duas datas

Question: Boas, tenho uma função que me guarda numa array os dias entre duas datas.
De seguida, quero verificar se um dado dia pertence ao intervalo e crio um foreach que me percorre o array com as datas todas e, no caso de a data estar inserida, ele dá um echo de '1'.
A questão é que ele nunca me retorna 1 mesmo quando a data corresponde a um valor do array.
O meu código é o seguinte:
$data_inicial = new DateTime(implode('-', array_reverse(explode('/', '10/05/2010'))));
$data_final = new DateTime(implode('-', array_reverse(explode('/', '07/06/2010'))));

while ($data_inicial <= $data_final) {
    $datasint[] = $data_inicial->format('d/m/Y') . '
' . PHP_EOL;
    $data_inicial->add(DateInterval::createFromDateString('1 days'));
}

foreach ($datasint as $key => $value) {
    if ($value == '25/05/2010') {
        echo '1';
    }
}

Alguem consegue perceber onde está o erro? Se quiserem copiem o código e tentem por vocês mesmos!
Comment: Você está concatenando `` nas datas, então dentro do `foreach` os valores são `10/05/2010`, `11/05/2010`, `25/05/2010` etc.
Comment: muito obrigado!
Comment: Se for só para verificar, você não precisa criar um array com todos os dias, basta verificar se a data em questão é maior que a data inicial e menor que a data final.
Answer: Como o hkotsubo disse, você está concatenando
 em cada valor do array. E no momento de realizar a comparação com a string acontece da seguinte forma:
foreach ($datasint as $key => $value) {
    if ('25/05/2010
' == '25/05/2010') {
        echo '1';
    }
}

Basta apenas remover a concatenação.
while( $data_inicial <= $data_final ) {
    $datasint[]= $data_inicial->format( 'd/m/Y' );
    $data_inicial->add(DateInterval::createFromDateString( '1 days' ));
}

Méritos da resposta ao hkotsubo, respondi aqui para facilitar na busca da resposta.


why is the most common note length in music the quarter note?

Question: I am new to learning piano and most of the notes I see in scores are in the length of a quarter note, and the time signatures I see are in 4/4.  My question is if the quarter note is used so often, wouldn't it make more sense to call it the whole note and have the lengths of other notes relative to that?
I say this because, for instance, if there is a watch on my table and I wouldn't say there is a quarter of a watch on my table, that would just be unnecessarily complicated and silly.
Now let's bring the logic back to music.  When you are first taught to read notation, you are told to play quarter notes.  So the fundamental unit of counting is in quarters.  How strange is that?
Comment: The *most common* duration is not the *longest common* duration. Therefore using it as the basis of notation would lead to lots of unreadable multi-tied notes.
Comment: In addition to the given answer's: there might be an observational bias here - you are looking at music sheets for beginners at the moment which are meant to be simple in some ways for teaching purposes. Looking at more advanced music scores, you'll find pieces in other time signatures and another distribution of note length. Search the web for images of some well known pieces, like Mozart's Turkish March (Rondo "alla turca") to get an idea... - Though I'm really curious now, whether anyone had done note length and time signature statistics across a wide variety of pieces already :)
Answer: Go back in history, and you'll discover the breve. The word means short, but it's actually worth eight crotchets (quarter notes).
Most music has a pulse to it - the part that one taps one's foot to, the heartbeat. The most common note to write for this amount of time has become the crotchet. In the most common time signature - 4/4 - that means there are four of them per bar. So, to put it into your way of thinking, one watch equals one bar.
That then makes it simple to divide up - or extend. These days one note in one bar of 4/4 is called a semibreve - all four beats - a whole note, taking up a whole bar. That bar could have two minims (half notes), or eight quavers (eighth notes). It all works smoothly.
By the time we get to sixteenth notes (semis), we see dots with stems that have two tails. Using your idea would add another tail, and start to get unwieldy. And since minims and semibreves work well, they would then be redundant. If it ain't broke...
Answer: In a measure of 4/4 time there are four beats. A whole note in that same measure calls for a count of four beats. A half note calls for a count of two beats, half the number of beats called for in a whole note. A quarter note calls for one beat, 1/4 the number of beats that are called for in a whole note. If a quarter note were to be renamed a whole note, we would have to find another name for the note that represents 4 beats and 2 beats wouldn't we.
Answer: The whole note is officially a "semi-breve", half of a short note.  It was a unit melodies were written in, and then people found that for shorter notes, they needed subdivisions, and they used stems, filled in noteheads and started adding flags in order to manage successively smaller subdivisions.
Then at some point of time, musicians figured out that those further means of indicating subdivisions were actually faster to grasp and easier to read than the old divisions were and stuff tended to be written in shorter durations.
Triplet passages in older baroque times were written in 3/1 and were performed fast.  In newer notation of the same music, this tends to have moved to 3/4 instead.  It is hard to quantify, but those differences in notation tend to feel different also, making it somewhat more natural for me to sing from scores using the old durations.  How much of a duration change makes the music feel "most natural" to modern performers may differ according to the musician.
But while usage of note lengths changed, the names stayed mostly the same after the initial transition from latin names (1 = semibreve, 2 = breve, 4 = longa) to fractions of a "whole" note (semibreve).


File sent from react not showing up in backend response body

Question: I'm trying to get a file from the user in my react application and then send that file to my back end and upload it to s3 bucket. I am successfully able to choose a file and it even shows up in the console. But when I send it to the back end, it just shows empty braces.
Here's the code to update the state:
handleInputChange = (event) => {
        this.setState({
            ...this.state,
            file: event.target.files[0]
        })
    }

This is the code to send the file
  submit = () => {
        console.log(this.state.file)
        axios.post(process.env.REACT_APP_SERVER + '/uploadThumbnail', { file: this.state.file, status: true})
            .then(response => {
                console.log(response)
            })
    }

Now, I can see the file in console. But in backend, it shows
REQUEST BODY: {file:{}, status: false}

Anyone knows how to solve this issue?
Answer: It's not right to send the file as a json.
I guess you are using nodejs backend and maybe using multer for file upload?
To send a file object via api, you have to send it as a form data.
const data = new FormData();
data.append('file', this.state.file);
data.append('status', true);
axios.post(process.env.REACT_APP_SERVER + '/uploadThumbnail', data, {
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})
.then(response => {
    console.log(response)
})


Android studio does not want to connect to ios simulator

Question: I just installed flutter on my mac and xcode etc, I am trying to run the flutter demo app on my simulator and it keeps telling showing me no device connected regardless of the fact that my simulator is online and running, I can't seem to figure out what the problem is, if I can get help to solve this I will be very grateful.
Flutter Doctor
[✓] Flutter (Channel stable, v1.17.1, on Mac OS X 10.13.6 17G66, locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    ✗ Android licenses not accepted.  To resolve this, run: flutter doctor
      --android-licenses
[!] Xcode - develop for iOS and macOS (Xcode 10.0)
    ✗ Flutter requires a minimum Xcode version of 11.0.0.
      Download the latest version or update via the Mac App Store.
[✓] Android Studio (version 3.6)
[!] Connected device
    ! No devices available
.....
thanks guys
Comment: Does this answer your question? [Flutter : Not Connecting to IOS Simulator in Android Studio](https://stackoverflow.com/questions/50318475/flutter-not-connecting-to-ios-simulator-in-android-studio)
Answer: You need Xcode version 11.0.0 at a minimum. Try updating it from the AppStore, it should work after that. Xcode is required to build and sign iOS Apps, so if you do not have a valid version, Flutter can't build to those devices.
From your error message: "[!] Xcode - develop for iOS and macOS (Xcode 10.0) ✗ Flutter requires a minimum Xcode version of 11.0.0."
Comment: without xcode 11.0 i can't run flutter on my simulator? what if i am on a macOS high sierra and I can't run the latest macOS catalina?
Comment: @Octagod Yes, and you will not be able to build to a real device. Android should work fine though.
Comment: is there any way around this?
Comment: @Octagod Maybe you could try downgrading Flutter to an older version that works with Xcode 10.0. Obviously thats not a great solution but I don't know of any others.
Comment: Ok, i will try that
Comment: @Octagod Good luck, feel free to accept the answer if you feel like it helped.


Condição senão no javascript

Question: Alguém saberia me explicar como coloco uma condição no script abaixo pra falar que tudo que for diferente dessas opções deve me retornar o valor 'Central'?
function run(cidadeFilial) {
cidadeFilial = cidadeFilial.toUpperCase();
if(cidadeFilial == 'SAO PAULO'){return 'Filial01';}
else if(cidadeFilial == 'RIO DE JANEIRO'){return 'Filial02';}
else if(cidadeFilial == 'CURITIBA'){return 'Filial03';}
else if(cidadeFilial == 'FLORIANOPOLIS'){return 'Filial03';}
else if(cidadeFilial == 'SANTOS'){return 'Filial04';}
else if(cidadeFilial == 'GUARUJA'){return 'Filial05';}
else if(cidadeFilial == 'BELO HORIZONTE'){return 'Filial05';}

Comment: Acredito que tenha um erro no seu código de implementação: Santos e Guarujá provavelmente deveriam ter a mesma filial, e não Guarujá e Belo Horizonte, certo? :)
Comment: Alguma das respostas resolveu seu problema? Se a dúvida estiver solucionada, considere aceitar uma resposta. Veja mais detalhes em [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/a/1079/100416)
Answer: Além do if..else e do switch, que já foram apresentados, você também pode utilizar object e fazer a verificação das keys. Caso uma chave exista, retorna a filial atrelada a ela; caso contrário, retorna a filial central.
A vantagem é que você terá um código limpo e com performance semelhante à utilização do if..else
Código comentado:

function cidadeFilial(cidadeFilial) {
  /* Cadastra as cidade com suas respectivas filiais */
  const filiais = {
    'SAO PAULO': 'Filial01',
    'RIO DE JANEIRO': 'Filial02',
    'CURITIBA': 'Filial03',
    'FLORIANOPOLIS': 'Filial03',
    'SANTOS': 'Filial04',
    'GUARUJA': 'Filial05',
    'BELO HORIZONTE': 'Filial05'
  }

  /**
   * Utiliza o operador "null coalescing" para verificar se
   * determinada cidade foi cadastrada no objeto
   * Se não existe (se o resultado `filiais[cidadeFilial]`)
   * for nulo, ele irá retornar a filial 'Central'; caso contrário,
   * retorna o valor da filial cadastrada.
   *
   * Código equivalente: `return (filiais[cidadeFilial]) ? filiais[cidadeFilial] : 'Central'`
   *
   * OU
   *
   * if (filiais[cidadeFilial]) return filiais[cidadeFilial]
   * else return 'Central'
   */
  return filiais[cidadeFilial] ?? 'Central'
}

console.log( cidadeFilial('GUARUJA') )

Performance
Num teste de performance, obtive os seguintes resultados:

If..else x 852,585,637 ops/sec ±0.28% (67 runs sampled)
Object x 855,238,844 ops/sec ±0.25% (67 runs sampled)
Answer: Você pode resolver isso colocando um else ao final do seu codigo. Isso faria o seguinte algoritmo:
Se a cidade for SAO PAULO
    Filial01
Se a cidade for RIO DE JANEIRO
    Filial02
...
Se não for nenhuma delas
    Central

function run(cidadeFilial) {
  cidadeFilial = cidadeFilial.toUpperCase();
  if (cidadeFilial == 'SAO PAULO') {
    return 'Filial01';
  } else if (cidadeFilial == 'RIO DE JANEIRO') {
    return 'Filial02';
  } else if (cidadeFilial == 'CURITIBA') {
    return 'Filial03';
  } else if (cidadeFilial == 'FLORIANOPOLIS') {
    return 'Filial03';
  } else if (cidadeFilial == 'SANTOS') {
    return 'Filial04';
  } else if (cidadeFilial == 'GUARUJA') {
    return 'Filial05';
  } else if (cidadeFilial == 'BELO HORIZONTE') {
    return 'Filial05';
  } else {
    return 'Central';
  }
}

console.log(run('FLORIANOPOLIS'));
console.log(run('teste'));

E é possível reduzir o número de ifs utilizando um "se A ou B". Veja exemplo abaixo:
if (cidadeFilial == 'CURITIBA' || cidadeFilial == 'FLORIANOPOLIS') {
    return 'Filial03';
}

Resolvendo com switch
Ao invés de usar vários if else, o recomendado pra esse tipo de caso é o switch, pois facilita a leitura do código e a escrita também. Se você não sabe como o switch funciona, dê uma lida nessa pergunta, que apesar de ser em outra linguagem, o conceito é o mesmo: Como funciona o switch por baixo dos panos?
O algoritmo será o mesmo que o citado no começo da resposta, pois o default cumpre o papel de senão enquanto os cases cumprem o papel de if (cidadeFilial == 'CIDADE'), e você também pode agrupar as cidades que possuem a mesma filial para executar o mesmo código, veja:

function run(cidadeFilial) {
  cidadeFilial = cidadeFilial.toUpperCase();
  switch (cidadeFilial) {
    case 'SAO PAULO':
      return 'Filial01';
    case 'RIO DE JANEIRO':
      return 'Filial02';
    case 'CURITIBA':
    case 'FLORIANOPOLIS':
      return 'Filial03';
    case 'SANTOS':
      return 'Filial04';
    case 'GUARUJA':
    case 'BELO HORIZONTE':
      return 'Filial05';
    default:
      return 'Central';
  }
}

console.log(run('FLORIANOPOLIS'));
console.log(run('teste'));

No caso das cidades com a mesma filial, aqui simplesmente é feito um "se" com duas condições:
Se a cidade for CURITIBA ou FLORIANOPOLIS
    Filial03

Condição senão no javascript


$\sum_{n=1}^\infty a_n<\infty$ if and only if $\sum_{n=1}^\infty \frac{a_n}{1+a_n}<\infty$

Question: For $a_n$ positive sequence.
I think I can prove one direction, but not both.
Comment: @YoavR. In this case $a_n=-2$ would form a counterexample. I believe you intend the numbers to be positive as well.
Comment: $\Rightarrow$ seems pretty obvious, just use the comparison test.  So I assume it's $\Leftarrow$ you're having trouble with?
Comment: Which direction?
Comment: Any assumptions on $a_n$? (are they complex numbers, real numbers, positive numbers?)
Comment: Which direction you proved? How?
Comment: @Wojowu real numbers
Comment: $ \sum_{n=1}^\infty a_n<\infty \implies \sum_{n=1}^\infty \frac{a_n}{1+a_n} <\infty$ - this is pretty straight forward as $a_n > \frac{a_n}{1+a_n}$
Comment: @Wojowu - as you can see - $a_n$ positive sequence - as I already said
Answer: Since $\frac{a_n}{1+a_n}<a_n$, thus $\sum_{n=1}^\infty a_n<\infty$ implies $\sum_{n=1}^\infty \frac{a_n}{1+a_n}<\infty$. On the other hand, let $\sum_{n=1}^\infty \frac{a_n}{1+a_n}<\infty$. Then $\lim_{n\to\infty}\frac{a_n}{1+a_n}=0$ and hence $\lim_{n\to\infty}a_n=0$. So there is $N>0$ such that $a_n<1$ when $n\ge N$. From this, we have
$$ \frac{1}{2}a_n\le\frac{a_n}{1+a_n}, \text{ for }n\ge N $$
which implies  $\sum_{n=1}^\infty a_n<\infty$.
Comment: Can't figure out this thing you wrote: "Then $\lim_{n\to\infty}\frac{a_n}{1+a_n}=0$ and hence $\lim_{n\to\infty}a_n=0$"
Comment: @YoavR., you can prove this fact that $\lim_{n\to\infty}\frac{a_n}{1+a_n}=0$ implies $\lim_{n\to\infty}a_n=0$.
Comment: can you show me a proof(or even intuition)?
Comment: @YoavR., ok. Clearly if $\lim_{n\to\infty}\frac{a_n}{1+a_n}=0$, then $\{a_n\}$ is bounded, say, $a_n\le M$ for all $n\ge 1$. Thus $\frac{1}{1+M}a_n\le\frac{a_n}{1+a_n}$. Thus $\lim_{n\to\infty}\frac{a_n}{1+a_n}=0$ implies $\lim_{n\to\infty}a_n=0$


UIView embedded only in UINavigationController and UITabBarController, why?

Question: In iOS, why can a UIView (and others) be only embedded in a UINavigationController or UITabBarController? What's special about these two classes?
Edit: oops, wanted to ask 'UIViewController' instead of UIView.
Answer: No, its not true. UIView is embedded with UIViewController. This class provides life cycle for UIView. It takes responsibility from initializing the view to deallocating the view.
UINavigationController and UITabBarController are just derived from UIViewController. They provide extra functionality for building hierarchy and switching between hierarchy respectively.
Answer: UIView can be embedded in any ViewController or its subclass. UINavigationController and UITabbarController are nothing but subclasses of UIViewController.
Answer: I think the embedding you're referring to is the embed in menu item which only allows for UITabBarController and UINavigationController. This means that XCode will take your UIViewController subclass and embed it in one of these two controllers. They are special because they are controllers of other controllers (collections of UIViewControllers). Xcode is simply taking some of the pain out of building a view controller and then adding it to a navigation controller or a tab bar. You can easily embed it in one of these with one click and no code. Much easier than in past versions of XCode.
Answer: If you're talking about "embed" as in Interface Builder, yes, as of iOS 5, Interface Builder only gracefully designs user interfaces for three view controller containers, UINavigationController, UITabbarController, and UISplitViewController. These are the three container controllers that come out of the box. You can, though, do your own view controller containment. See Session 102 in WWDC 2011 for information on view controller containment. Also refer to the section on view controller containment in the UIViewController Class Reference.


What Phaser is used at the beginning of "Rooster" by Alice in Chains?

Question: I built a CE2 chorus clone that sounds fantastic and should work for Rooster.  But I believe the Alice in Chains guitarist (was it Cantrell or Layne playing?) is also using a phaser, which I don't yet own... much of the high shimmer of the chorus is missing, but there's a nice "middle" warble going on with the chorus too.  I read somewhere it was a chorus and phaser combo.
So which phasers have a frequency response/range like that?  Would just an ordinary Phase 90 do it? Or would I need something with less depth like the Phase-45, or more control like a Phase 100, or maybe some other phaser (Ibanez, Ross, Boss, etc.)?
If it's not a phaser and there's some other known way of getting that sound, I'm open to ideas... I can get pretty close with the CE2 and cutting as many "highs" as possible, but there's still a missing warble.
Thanks!
Answer: It's really tough to tell the difference between phase/univibe/chorus/vibrato when they are low in the mix--as most of those effects overlap or sound very similar. The thing about phasers is the more stages you have the more versatile the sound. Most analog phasers have anywhere from two to twelve stages (incrementing by two for each tier)--and it sounds like it could be a basic 4 or 8 stage phaser. The important thing to listen for when attempting to identify a phaser is for the telltale "notch" in between phase tiers. I can't really hear it clearly on the live or album versions of the song I have, so it may be something else.
Knowing Jerry Cantrell if he used a phaser he likely used a standard MXR Phase 90 for this, but there's also the option that he used a Dunlop Rotovibe, since that has been seen on his recent pedalboard. I also hear a little telltale warble in there in addition to the vibe effect--which further convinces me that it is likely the Rotovibe or a combination between a phaser/vibe and a chorus unit.
In any event, you can emulate the sound with a Phaser, a chorus, or a vibrato with the right settings. It won't be perfect, but most people won't even notice.
Comment: I saw the vid with the Rotovibe, though as I recall they talked about it being specific to a certain song, and it wasn't Rooster.  I've heard a few live recordings and it sound like they might use some different gear than when they recorded it.  But thank you for the info about phaser stages - I will look more into this, as I'm looking at getting/building a phaser soon.
Answer: I thought I read in a guitar magazine that it was a flanger, which sounded right to me. I covered the song in a band several years ago, and I used the flange effect on my GT-6, and it sounded right. I know sometimes it's not the easiest thing to distinguish a light phase effect from flange, though, and even if Jerry did use a flanger on the recording, you can probably get a very close approximation with a phaser if that's what you have. Like @Jduv said, a lot of people won't even notice the difference.
Comment: Pretty certain it was a flanger - think I read the same magazine article as you @Andy. Will try and hunt down the article.
Answer: The closest I've come to the Rooster clean tone is with using a CE-1 Anolog Chorus from my POD HD500, a EHX Deluxe Electric Mistress Flanger, and a dual amp setup with one of the amps being a Yamaha RA-200 rotating speaker. The chorus and flanger are blended on two paths of my signal (lets call them 'A' & 'B') Then those two signals run through a VOX AC30 preamp sim and split out to the power amps of a 50W EL34 tube amp and the Yamaha RA-200.  The Yamaha and Electric Mistress help add those tough to distinguish modulation qualities that probably come from Jerry's mix of chorus/flange/phase/vibe.
Answer: I was Dave Jerden's tech for a decade but did start a little after Dirt...however, the sound was Dave's Taylor into a ce-1, small stone, and flanger (prob his Boss)...the amp was a vox superbeatle...hope this helps :)
Answer: Got a DOD 747 flanger the other day. We used my housemate's lovely new pink strat and played on it for hours and got a pretty decent rooster tone


What are the technical differences between freestyle and butterfly swimming?

Question: Freestyle times (46.91 WR for 100m) tend to be faster than butterfly (49.82 WR for 100m) times. However, the "peak speed" for butterfly is faster than freestyle(1). Would this have to do with an aerodynamic or technical effect?
What are the technical differences between freestyle and butterfly?
Answer: Without elaborating on the technical differences, because I'm probably not qualified to give a full answer in that respect, I'll answer the first part.
The reason butterfly has a higher peak speed is that you are pulling with both arms at once. When pulling with both arms, you're going faster than the one arm pull of freestyle. When recovering both arms, you are slower than the average freestyle speed in which you're pretty much always moving an arm or staying long in the water.
This pdf states:

The large power impulse generated by the simultaneous double-arm
  pulling pattern  yields great propulsive potential; however, during
  the arm recovery phase there  is no propulsion generated. This creates
  a minor 'dead space' in the stroke.

This ppt states:

...since speed drops significantly during the recovery phase, it is
  overall slightly  slower than the freestyle.

I'm not entirely sure why the tradeoff ends up being slower. I know if you run into a wind for distance x and then with the wind for the same distance, it's slower than running with no wind, and that can be proven with simple math. Maybe that is the situation. You're pulling twice as hard and then getting no pull. And you can't be as long in the water all the time during butterfly, which is a big reason for speed. All the elite swimmers are pretty tall with large wingspans.
Comment: Any chance you're be interested in digging further into this when you get some time? Some references would be awesome to make this answer stand out even more
Comment: Yeah sure. I'll do a little research when I get off work.
Comment: @waxeagle No time for research on the last paragraph or to add technical differences, but I'll try to do that this weekend.
Comment: Good answer. I would suspect the tradeoff has to do with the variation of speed (perhaps butterfly undulates in terms of speed...and freestyle is more consistent).
Comment: Speaking from experience, one other limiting factor not mentioned here is that the fly technique is more physically intensive due to the shoulder strength/mobility to bring both arms over the surface simultaneously. It's a lot harder than the equivalent frontcrawl motion, therefore prone to cause greater overall fatigue. I don't have any scientific evidence to back this up though, aside from 25+ years of competitive swimming experience: ask any swimmer and they'll tell you fly is harder than frontcrawl.


Gaussian Mixture, sampling and interpretation

Question: I came across the following which I have troubles understanding and would appreciate your help.
Suppose we want to fit a Gaussian mixture model (GMM) to a $t$-dstribution with some degrees of freedom. Let the GMM have $K$ components. Using the $EM$-algorithm we found $K$ means $\mu_k$ and variances $\sigma^2_k$ of the Gaussians as well as $K$ mixing coefficients $\pi_k$.
In order to sample from the GMM we use an ancestral sampling scheme with one exception (steps 4 and 5). That is, for one sample, we have to

generate $U$ following a standard uniform distribution.
compute $k=\sum_{j=1}^K I_{\{g_j>U\}} + 1$, with $g_j=\sum_{i=1}^j\pi_i$, $j=1,...,K$.
Given $k$ choose $\mu_k$ and $\sigma^2_k$.
Sample $v_t$, $t=1,...,L$, each following to $N(\mu_k, \sigma^2_k)$.
Compute $V=\sum_{t=1}^Lv_t$

Note that in step 4 we sample from the same Gaussian $L$ samples which are summed in 5.
Now the claim is that $V/\sqrt{L}$ is GMM-distributed, where the scaling comes from the sum of $L$ Gaussians. In this particular case approximately $t$-distributed. Is this true? I find it odd but cannot grasp why. Thanks for help.
Answer: Given that you are taking the sum of $L$ Gaussian $\mathcal{N}(\mu_k,\sigma^2_k)$ variates, the sum $V$ is also Gaussian $\mathcal{N}(L\mu_k,L^2\sigma^2_k)$. Hence your outcome $V/\sqrt{L}$ is still one from a Gaussian mixture
$$\sum_{k=1}^K \pi_k \mathcal{N}(\sqrt{L}\mu_k,L\sigma^2_k)$$
I must add that I see little motivation for considering this simulation and average.
Answer: Thanks for the answer, I appreciate it very much. I agree with your comment regarding the motivation.
Regarding your answer: Isn't the variance of the variance of $V$ equal to $\sum_{k=1}^K \omega_k \left(\sigma_k^2+L(\mu_k-\mu_g)^2\right)$?, with, $\mu_g=\sum_k\omega_k\mu_k$?
Here is how I derived it, with $v_{t,k}$ denoting the random variables form the $K$ components:
$$\sum_k\omega_k E\left(\frac{\sum_t v_{t,k}}{\sqrt{L}}-\sqrt{L}\mu_g\right)^2\\
= \frac{1}{L}\sum_k\omega_kE\left(\sum_t v_{t,k}-L\mu_k+L\mu_k-L\mu_g \right)^2\\
=\frac{1}{L}\sum_k\omega_k\left(E\left(\sum_t (v_{t,k}-\mu_k)\right)^2+2E\left(\sum_tv_{t,k}-L\mu_k\right)\left(L\mu_k-L\mu\right)+L^2\left(\mu_k-\mu_g\right)^2\right)\\
=\frac{1}{L}\sum_k\omega_k\left(L\sigma_k^2+L^2(\mu_k-\mu_g)^2\right)\\
=\sum_k\omega_k\left(\sigma_k^2+L(\mu_k-\mu_g)^2\right)
$$
The middel term in the longest line vanishes. Where is the mistake? Thanks.


The set of natural number functions is uncountable

Question: I thought the set of natural number functions would be of the same cardinality as the countably infinite product of $\mathbb{N}$, which is countable.
Each natural number function can be identified with an infinite-tuple of $\mathbb{N}$ by letting the $i$th entry be the image of the number $i$ under the function.
Comment: What is the question?
Comment: [One](http://math.stackexchange.com/questions/129851/). [Two](http://math.stackexchange.com/questions/304314/). [Three](http://math.stackexchange.com/questions/629268/). [Four](http://math.stackexchange.com/questions/86650/). [Five](http://math.stackexchange.com/questions/461054/). [Six](http://math.stackexchange.com/questions/300444/). And there are definitely more.
Comment: Ergo the "argument" that the product of countably many countable sets is countable is at best fishy, no? Actually this argument is wrong and you are probably mixing it up with the fact that the *union* of countably many countable sets is countable
Comment: I'm wondering where I went wrong in my thoughts on this problem, since I would say the set of functions is countable, but I know that it's actually uncountable.
Answer: Cantors diagonalisation method: If it is countable then it is $F=\{f_1,f_2,\ldots\}$. But the function $g(i):=f_i(i)+1$ is not in $F$. A contradiction to the initial assumption.
Proof:
For every  $i $ we have
$$g(i)=f_i (i)+1 \implies g (i)\ne f_i (i) \implies g \ne f_i $$
and so $g \notin F$.
Comment: @Jason I added a proof. This is similar to Cantor's diagonalisation proof.
Comment: Why isn't it in $F$?
Comment: @miracle173 Thank you very much for this answer. How do you then prove that $card(F)=card(R)$, where R is real numbers.
Answer: Every real number in $(0,1)$ has either one or two decimal representations. (Some have two, like $0.1000\ldots$ which is equal to $0.0999\ldots$.) But any way, each real number in $(0,1)$ gives at least one decimal representation. And that decimal representation can be viewed as a function from $\mathbb{N}$ to $\mathbb{N}$ by taking the $n$th digit after the decimal. (Actually, it's more restrictive: from $\mathbb{N}$ to $\{0,1,2,3,4,5,6,7,8,9\}$.)
For example, $0.72465\ldots$ can be used to define a function $$\begin{align}1&\mapsto7\\ 2&\mapsto2\\ 3&\mapsto4\\ 4&\mapsto6\\ 5&\mapsto5\\ \vdots&\phantom{\mapsto{}}\vdots\end{align}$$
So the set of functions from $\mathbb{N}$ to $\mathbb{N}$ contains a subset that is as large as the real interval $(0,1)$. (And seemingly even stronger, so does the set of functions from $\mathbb{N}$ to $\{0,1,2,3,4,5,6,7,8,9\}$. And seemingly even stronger still, if we used binary instead of decimal, so does the set of functions from $\mathbb{N}$ to $\{0,1\}$.)
Answer: The cardinality of the natural number functions is $\mathbb{N}^{\mathbb{N}} \geq 2^{\mathbb{N}}$ and $2^{\mathbb{N}}$ is uncountable
Comment: $\geq$ actually (and indeed $=$, I believe).
Comment: @Eric Stucky: thanks
Answer: The countably infinite product of $\mathbb{N}$ is not countable, I believe, by Cantor's diagonal argument.
Comment: Countable *union* of countable sets is countable. Perhaps that is what you had in mind.
Comment: I thought it's the case that a countable product of countable sets is countable.
Comment: Andre, yeah that must be the source of the confusion. Thank you!
Comment: I have a question. Is the union of the set of natural number functions countable?
Comment: @valentino That is actually the same thing as the countably infinite product of $\mathbb{N}$. Both can be abbreviated $\mathbb{N}^\mathbb{N}$. This is the same as how $\mathbb{R}^3$ can be seen as the space of functions from $\{1,2,3\} \to \mathbb{R}$
Comment: I'm sorry! That was somewhat vague I meant the set of functions $\{f\mid f:\mathbb{N}\to\mathbb{N}\}$ is the union of this set countable?
Comment: @valentino That's what I mean as well. :) So no, by the diagonalization argument.
Answer: Let's consider the following set: $F = \{ f:D \in 2^\mathbb{N} \rightarrow \mathbb{N} \ | \ f(x) = x \}$;
Notice how there is a function $f$ for each possible set of natural numbers residing inside $2^\mathbb{N}$, which will allow us to draw the following conclusion: $|F| = |2^\mathbb{N}|$.
Now, observe how $F$ is a much smaller set than $\mathbb{N}^\mathbb{N}$(because it contains only functions of the form $f(x)=x$), but even so, it's uncountable. Therefore $\mathbb{N}^\mathbb{N}$ is evidently uncountable since it's a superset of $F$.
$F \subseteq \mathbb{N}^\mathbb{N}, |F| = |2^\mathbb{N}| \implies |\mathbb{N}^\mathbb{N}|=|2^\mathbb{N}|  \ \ \ \square $
Comment: I'd like to understand what's wrong behind this reasoning.


Quando uso uma classe "Endpoint" para publicar um Web Service, aonde o WSDL é criado?

Question: Por exemplo, eu tenho 3 classes no meu Web Service:
1 - Uma SEI (a interface do Web Service):
package calc;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style = Style.RPC)
public interface CalculatorServer {
    @WebMethod float sum(float num1, float num2);
    @WebMethod float subtraction(float num1, float num2);
    @WebMethod float multiplication(float num1, float num2);
    @WebMethod float division(float num1, float num2);
}

2 - Uma SIB (a implementação da Interface):
package calc;

import java.util.Date;
import javax.jws.WebService;

@WebService(endpointInterface = "calc.CalculatorServer")
public class CalculatorServerImpl implements CalculadoraServer {

    public float sum(float num1, float num2) {
        return num1 + num2;
    }

    public float subtraction(float num1, float num2) {
        return num1 - num2;
    }

...

}

3 - E a classe responsável por publicá-la:
package calc;

import javax.xml.ws.Endpoint;

public class CalculadoraServerPublisher {

    public static void main(String[] args)
    {
        Endpoint.publish("http://127.0.0.1:9876/calc",
        new CalculadoraServerImpl());
    }
}

Se eu rodar a terceira classe e acessar o endereço:
http://127.0.0.1:9876/calc?wsdl

Eu verei o WSDL do meu Web Service. Daí vem a pergunta: se eu posso acessá-lo, ele está fisicamente alocado em algum lugar do meu computador, mas...AONDE? Eu tentei usar todas as ferramentas de busca do Windows que eu conheço (eu uso o Windows 8.1) e nenhuma delas conseguiu encontrar. Aonde ele está, afinal?
Answer:
Daí vem a pergunta: se eu posso acessá-lo, ele está fisicamente alocado em algum lugar do meu computador, mas...AONDE?

Não é verdade que se você está acessando algum recurso ele necessariamente precisa ser físico e estar em algum lugar do computador. O caso apresentado por você é um destes cenários, já que o WSDL é armazendo em memória (não o WSDL exatamente, mas o que o forma).
Com JAX-RS, se não informarmos a localização do WSDL ele é gerado automaticamente. Na especificação do JAX-WS (considerando a 2.2), temos o seguinte em 5.2.2 Publicação:

The WSDL contract for an endpoint is created dynamically based on the annotations on the implementor
  class, the Binding in use and the set of metadata documents specified on the endpoint (see 5.2.4)

Ou seja, o WSDL é criado dinamicamente e é criado o metadado dos endpoints baseado nas anotações. No entanto na especificação não há nada que fale COMO estes artefatos devem ser armazenados.
Cada implementação da especificação armazena o WSDL de uma forma, então para saber detalhes de ONDE é armazenado, é necessário ver como cada implementação realiza esta tarefa, mas como já se tem os metadados é comum que ele esteja em memória em algum objeto e é serializado sempre que as URL terminadas em ?wsdl ou ?WSDL é chamada.
Você pode olhar com detalhes a especificação do JAX-WS disponível em https://jax-ws.java.net/, os tópicos 5.2.4 e 5.2.5 possuem informações relevantes, além da documentação de implementações do JAX-WS que atendem à estes pontos da especificação, como por exemplo olhar as classes dos pacotes com.sun.xml.internal.ws.transport e com.sun.xml.internal.ws.wsdl, do JDK, para ver como as referências são armazenadas para serialização.


Limit Migrate explode process plugin to 1 takes whole string

Question: I have a csv places column with values like that:
Madrid|Spain
Barcelona|Spain

I want to migrate this places to a custom taxonomy and 3 terms (Madrid, Spain, Barcelona) get generated doing it like that:
  field_taxonomy_places:
    -
      plugin: explode
      source: places
      delimiter: '|'
    -
      plugin: entity_generate

But actually I only want to create cities (Madrid, Barcelona), but not countries. So I try to take the first value till the delimiter like that:
field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 1
      delimiter: '|'
    -
      plugin: entity_generate

The problem is that now 2 terms get generated (Madrid|Spain, Barcelona|Spain).
Answer: Just found the solution after rereading the PHP explode docs:

If limit is set and positive, the returned array will contain a
  maximum of limit elements with the last element containing the rest of
  string.

So setting the limit to 1 has the effect that the returned array element contains the rest of the string, which in my case is the whole string. So setting the limit to 2 fixes the problem and gives back the first part of the string:
field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 2
      delimiter: '|'
    -
      plugin: entity_generate


Hashing a 5 digit passcode for a mobile app with bcrypt

Question: Our application stores normal passwords in hashed format using bcrypt, with a cost (number of rounds) of 15. Checking the validity of a password takes little over 1 second on our production servers, which is acceptable for a once-per-session action.
We're now in the process of developing and securing our app. We will give the user the opportunity to setup a 5 digit passcode, after having logged in with their usual credentials (login and password) for the first time.
Would it be reasonable to use a lower bcrypt cost (i.e. 13) to hash these passcodes?
My considerations:

A lower cost allows quicker access, which is vital for our app users.
A lower cost doesn't impose a big security risk, as the passcodes alone are useless (they are device-bound).
It's still strong compared to many alternative hashing mechanisms.
Comment: Where are you storing this PIN - server-side? Also, how are you identifying the device. I see you've already accepted an answer - are you still looking for help?
Comment: Tips are always welcome. I opened up another question about identifying the device here: http://security.stackexchange.com/questions/105653/implement-a-passcode-to-authenticate-app-users  Yes, the code is stored serverside.
Comment: It's already implemented by the way. The device registers itself on the server with a string consisting of time, device id and a random string. The app stores that id in local storage, and the server hashes it with bcrypt and stores it in the database. Passcode gets registered on the server once, gets hashed as well and is not stored by the app obviously.
Answer:
Would it be reasonable to use a lower bcrypt cost (i.e. 13) to hash these passcodes?

In a nutshell, yes. Or scrap bcrypt completely (see below).
I think there's some confusion here about key stretching and KDFs (i.e. bcrypt), and how they relate to offline and online attacks.
Algorithms such as bcrypt are there to prevent the password from being known if somebody extracts the hashes from your server and proceeds to run an offline brute force or password guessing attack against them.
Bcrypt isn't there to prevent password guessing attacks against your application when running. Here you can use server-side application logic in order to detect a brute force against the same account, and then rate limit that attempt. For example, purposefully delaying the response once a certain number of incorrect guesses have been made in a certain time period against the same username.

The device registers itself on the server with a string consisting of time, device id and a random string.

Assuming the device id is a 128 bit UUID, you already have an identifier with 128 bits which is actually uncrackable if properly random. However, GUIDs are designed to be unique, not random and as you mention in your other question, anyone knowing this value is already halfway there to cracking your authentication.
I would scrap this and simply generate a random 128 bit string to use as an "installation ID" using a cryptographically secure pseudo random number generator (CSPRNG). As this is already strong, there is no need to salt it or run it through a a password stretching algorithm, or key derivation function such as bcrypt. SHA-256 hashing on the server side stored version would be adequate.
A 5 digit passcode can be represented using 17 bits. A bcrypt cost of 13 would effectively give this passcode the strength of 30 bits. This is well below the NIST recommendation of 80 bits.
However, let's have a think about what this means. Bcrypt is there to protect server side hashes from being guessed using a word list (or in this case a number list ranging from 00000 to 99999). If your 128 bit installation ID is stored hashed on the server and an attacker manages to gain access to your user table, even if they do crack the 5 digit passcode stored in bcrypt, they cannot then log in as the user as they do not know how the SHA-256 hash was generated - they do not have the installation ID. It would be completely unfeasible to run through every possible 128 bit value and find out if it hashed to the stored value. Rainbow tables would be far too big to store too with 2128 combinations.
To make things simpler I would be tempted to scrap bcrypt for the passcode codes and simply store SHA-256(passcode + 128 bit random installation ID) on the server. The passcode can act as a salt for the "installation ID" so a user changing their passcode will generate a completely different hash that is stored server-side.
Note that the above is assuming that there is a one-to-one relationship between device and account. If multiple accounts are used per device, then you should add an additional salt per account (say 64 bit) - otherwise two users that have chosen the same passcode will have the same server-side hashed value. There is also an additional security risk in that the "installation ID" is now known by another user, as well as all the additional risks that come with sharing a client device with other users (e.g. physical security aspects or malware risks).
Answer: There's not much interest in hashing a 5-digit passcode alone, as it can easily brute-forced (there are only 100000 possible values).  I'd try to see if there is a way to store the passcode hashed together with the user password.
Comment: Then it would take over a second to calculate the validity of the passcode, which is way too long. Would it be stronger if I would add, say, the login and/or id to the passcode?
Comment: Yes, but make sure you're not leaking information.  By the way, how come is 1 sec too long?  An user would hardly notice it after the time spent entering the passcode.
Comment: That 1 second is apart from other processes such as loading the page the user actually requested. That feels quite lengthy. I'll think about adding the login to the mix, although that would only suffice if the attacker doesn't know the login (or doesn't know that we use the login in the mix). Then again: the risks are minimal, as the digits themselves are useless without the user's device.
Comment: You can reduce the *perceived* waiting time by showing a message or a quick progress bar to the user.
Comment: 1 sec is too long. Could you give me some info about the setup. Do you have a web app or native or (hybrid)? So, the client authenticate the user on the device (offline) after the user creates his/her own passcode (i.e. 5 digit). Are you considering account recovery procedure just in case user losses their passcode?


What are the effects of the "access commerce administration pages" permission

Question: The SA-CONTRIB-2020-020 security patch was titled "Further restrict anonymous user access to anonymous orders."
Unfortunately it seems to have broken some sites I work on.  We are now seeing access denied errors on admin/commerce/orders/xxx for "semi-trusted" users who have permission "Default: Update orders".  For these sites the security patch was a non-back-compatible change and I have raised an issue for that.
The solution that worked for me is to grant the semi-trusted users the "access commerce administration pages" permission.
However I am nervous because this permission doesn't seem to have clear documentation.  I don't wish for these "semi-trusted" users to suddenly gain extra access that they should not have such as to edit products.
Please can anyone confirm the effects of this permission?  Does it do nothing alone and only work if other permissions are added?
Comment: I'm voting to close this question because it's a bug report that must be reported to the issue queue on drupal.org to be fixed.
Comment: OK I have raised an issue.  The remaining question still seems valid - "please can anyone confirm the effects of this permission".
Comment: You might consider rephrasing the question title, this maybe helps to get to the point more quickly.
Comment: Agreed, please move this to the issue queue, though I'm not even sure it's a bug so much as a feature or documentation request? Re: clearer communication, it's pretty common practice _not_ to be overly specific in SA's to protect users while their upgrades are pending.
Comment: That's fine I'm very happy to raise an issue thanks for the guidance on the appropriate approach.
Answer:
Does it do nothing alone and only work if other permissions are added?

Currently, yes (although that could theoretically change in the future).
The permission is added to all HTML admin routes for the order entity type (add/edit/etc), and for admin overview pages, which essentially list sub-pages that the user has access to.
If the user doesn't have access to those sub-pages, all provided by separate permissions, they won't see the links, and won't be able to visit them. Similarly, if they don't have the correct entity access permission, they won't be able to perform the respective operation on the entity.


Como verifico se um $_FILE foi definido?

Question: tudo certo?
Estou tentando executar essa código:
<code>if(empty($_FILES['imagem']['name'])){
    $upload = new Upload();
    $novoNome = $upload->efetuarUpload($_FILES["imagem"]);
    $pontoTrocaAlterado->setImagem($novoNome);
}
</code>
Eu preciso que apenas quando o usuário fizer upload do arquivo, ele executar a função efetuar Upload e setar o novo nome da imagem. No entanto fazendo os testes, mesmo quando o usuário não faz upload do arquivo, o nome é alterado.
Já usei diversas funções como:
in_array
array_key_exists
Mas não tive sucesso, alguém poderia me ajudar?
Comment: O nome de qual arquivo é alterado quando não é feito o upload?
Comment: Campo imagem, no banco de dados
Comment: isset() não resolve o seu caso?
Comment: Aliás, não faltou um `!` antes do `empty`, para entrar no `if` somente quando o valor não é vazio?
Comment: Consegui resolver, como era um caso de alteração do arquivo eu fiz o seguinte:

 `if(!empty($_FILES['imagem']['name'])){
        $upload = new Upload();
        $novoNome = $upload->efetuarUpload($_FILES["imagem"]);
        $pontoTrocaAlterado->setImagem($novoNome);
    }else{
        $pontoTrocaAlterado->setImagem($imagem);
    }`.

@AndersonCarlosWoss eu segui sua sugestão de acrescentar **!** , mas observei q mesmo eu não definindo o nome ele não gravava no banco, pois o banco não aceita nulo, então gravei o nome antigo do arquivo.
Answer: Consegui resolver, como era um caso de alteração do arquivo eu fiz o seguinte:
<code>    if(!empty($_FILES['imagem']['name'])){
    $upload = new Upload();
    $novoNome = $upload->efetuarUpload($_FILES["imagem"]);
    $bannerAlterado->setImagem($novoNome);
}else{
    $bannerAlterado->setImagem($imagem);
}
</code>
eu segui a sugestão do @AndersonCarlosWoss de acrescentar ! , mas observei q mesmo eu não definindo o nome ele não gravava no banco, pois o banco não aceita nulo, então gravei o nome antigo do arquivo.


Generating these p-values in R

Question: I need to compare two categorical tests as follows:

A size $\alpha$ Pearson's test rejects $H_0$ if $Q(x) = {(x_1 - np_{01})^2 \over np_{01}(1 - p_{01})} > F_1^{-1}(1 - \alpha)$
A size $\alpha$ binomial ML test. Rejects $H_0$ if $T(x) = {(x_1 - np_{01})^2 \over n(x_1/n)(1 - x_1/n)} > F_1^{-1}(1-  \alpha)$

Fix $n = 500$ and $p_0 = (0.4, 0.6)$. Generate an $x$ from
Multinomial$(n, p_0)$ (it suffices to get $x_1$ from  Binomial$(n, p_{01})$ and set $x_2 =(n -x1)$. Calculate the two p-values for this data under the two kinds of
tests. Now repeat this 100 times. Make a plot of these 100 pairs of p-
values and compare them with the 45 degree line. Are the two types of tests
behaving similarly for this simulation setting?

Using the following code, I am getting nonsensical answers. I'm not quite sure how I should plot these p-values either? Should I plot them $(p_B, p_M)$ as a pair?
# Lab 10
n = 500
p0 = c(0.4, 0.6)
x.1 = rbinom(1, n, p0[1])
x.2 = n - x.1
x = c(x.1, x.2)
Xtest = chisq.test(x, p = p0)
print(Xtest)
# Chi-squared test for given probabilities

# data:  x
# X-squared = 0.0083, df = 1, p-value = 0.9273

## 100 times for X test
n = 500
p0 = c(0.4, 0.6)
x.1 = rbinom(100, n, p0[1])
x.2 = n - x.1
data = c(x.1, x.2)
x.mat = matrix(data, ncol = 2)
pvals.Q = 0
Q.x = 0
for (i in 1:length(x.1)){
Q.x[i] = (x.1[i] - n*p0[1])^2/(n*p0[1]*p0[2])
pvals.Q = 1 - pgamma(Q.x, 1/2, 1/2)
}
# for (i in 1:length(x.1)){
    # x = c(x.mat[i, 1], x.mat[i, 2])
    # pvals.Q[i] = chisq.test(x, p = p0)$p.value
# }

## Binomial Test
n = 500

x.1 = rbinom(100, n, p0[1])
x.2 = n - x.1
x = c(x.1, x.2)
p0 = c(0.4, 0.6)
T.x = 0
for (i in 1:length(x.1)){
    T.x[i] = (x.1[i] - n*p0[1])^2/(x.1[i] * (1 - x.1[i]/n))
}
pvals.ML = 1 - pgamma(T.x, 1/2, 1/2)

plot(pvals.Q, pvals.ML, ann = FALSE, type = "p")

Answer: You need to first "set.seed" this will make sure that you are comparing the same datasets. As you have it coded you are comparing different random draws to each other. The rest of your code looks fine, though is often redundant (more typing than necessary!).
set.seed(123)

You can also get a straight line on your plot by using
abline(0,1)

Generating these p-values in R


How to write a method in ruby that takes hash-style, square bracketed arguments, like mymethod[arg]?

Question: I want to write a method in ruby to replace a current method that simply returns a hash.
So currently we have this
def some_stats
  {
    :foo => "bar",
    :zoo => "zar"
  }
end

which can be called like this:
some_stats[:foo]

I want to replace this with a method that is called with :foo, which does some more complicated things that just building a hash.  However, I'd like it to be called in the same way, with the square bracket notation.  EG
#this is a bit pseudo-cody but hopefully you get the idea.
def some_stats[](key)
  if key.to_s =~ /something/
    #do something
    return something
  else
    #do something else
    return something_else
  end
end

This would still be called like some_stats[:foo]
I can't work out the syntax for defining the method name:  the above, def some_stats[](key) doesn't work.  I feel like this should be possible though.
Answer: You're quite close. object[sth] is just a syntax sugar for object.[](sth). So to do what you need you have to define some_stats method that returns the object which defines [] method:
class Stats
  def [](key)
    if key.to_s =~ /something/
     #do something
     return something
  else
    #do something else
    return something_else
  end
end

def some_stats
  Stats.new
end

some_stats[:something_new] #=> something
some_stats[:not_new] #=> something_else

Answer: Your original method is not called with square brackets; it is called without any argument, but returns an object (in your case a Hash), which has method :[] defined and hence understands square brackets. Your method call is equivalent to
(some_stats())[:foo]

or, more explicitly, to
x = some_stats()
x[:foo]

Therefore you need - inside your method return an instance of some class which offers the [] method. Say you have written a class named MyClass which has a [] defined. You could then write a function
def some_stats
  if _your condition goes here_
    { ... } # Return your Hash
  else
    Myclass.new
  end
end

This would be used as
some_stats[:whatever]

However, to be really useful, your condition would make use of a parameter to the method, i.e.
def some_stats(param)
  if param < 4000
    { ... } # Return your Hash
  else
    Myclass.new
  end
end

And you would invoke it by
some_stats(4711)[:whatever]

Comment: `some_stats` could also return a lambda if there is a little bit of processing that needs to be done but not enough for a whole class.


How to avoid appending incremental number to filename

Question: I don't want Drupal to add incremental numbers to my file names to make them unique. I want to always have files stored with the same name they had when I uploaded them.
If the file with given name already exist, "Replace already existing file?" prompt should appear instead of default behaviour.
Comment: Hello and welcome. It seems English is not your first language. It is not my first language, either ;) So to be sure: You want to have "Replace file?" dialog instead of default behaviour: number appended to filename to make it unique? And you want to always have files stored with the same name they had when you uploaded them?
Comment: Yes you are absolutely clear with the requirement Mołot
Comment: I edited it for you, hope it will attract more attention (and answers) now. As we can see with NWOM's answer, your question was easy to misunderstood, but I think we have it figured out. Good luck!
Answer: The Upload File Replace module should do the trick:

Module Page Description
This is a small utility module that automatically stops Drupal from
  renaming new files upload via filefield CCK. When 2 files with the
  same name exist, the older files will be renamed.

Edit: Sorry, I missed the part where you are expecting a prompt. According to the comment below, it is not possible.
Comment: There are two issues with it: 1) it does not provide a dialog, it overwrites silently, and 2) 7.x-1.0-beta1 worked very, very unstable for me (messing managed files table et cetera). Can't tell about dev from 2013-Oct-19 - maybe it's better now?
Comment: @NWOM Files are still getting renamed after using this utility,I think i am missing something please suggest?


Angular Typescript Create a File object from assets img directory

Question: I'm trying to implement a custom image selection. I want to propose several image in a modal and when a user click on one element, put it in a File object in my ts (like a file picker). I don't want to use a filepicker to restrict image choice.
I load my images like this from assets directory :
    <ng-container *ngFor="let item of [].constructor(12); let i = index">

      </ng-container>

I want to create a new File object in my .ts with the src of the selected image to send it to server.
ex :
const file = new File(.......)

Can I do this ?
Thanks for your help !
Answer: You could create your own function and put it in a service:
async convertRelativeUriToFile(filePath: string, fileName: string, mimeType: any) {
    mimeType = mimeType || `image/${filePath.split(".")[filePath.split(".").length - 1]}`;
    const imageUrl = await fetch(filePath);
    const buffer = await imageUrl.arrayBuffer();
    return new File([buffer], fileName, { type: mimeType });
}

const file = await this.convertRelativeUriToFile(<YOUR_FILE_URL>, <YOUR_FILE_NAME>, <YOUR_MIME_TYPE>)


how many overthrow can be done?

Question: how many overthrow can be done? If a fielding team do overthrow 2-3 times and the batsman take many runs in that, do the umpire interfere and declare ball dead so that no extra overthrow can be done in that particular ball.
Answer: There is (quite correctly) nothing in the Laws of Cricket which would mean that the umpires would declare the ball dead. If a team is stupid enough to keep throwing the ball hard at the stumps after they've missed three times already, then they deserve to have the batsmen keep racking up the runs. They can always just walk the ball to the wicket.

how many overthrow can be done?