How to make inverted rounded corners and "bend" content to follow curved container

Question: The carousel is designed with a rounded bottom, and the captions should follow that... I'm lost on how to achieve this.
The curved bottom comes from this code on my carousel:
.round-carousel {
    height: 600px;
    border-bottom-left-radius: 80% 20%;
    border-bottom-right-radius: 80% 20%;
    overflow-y: hidden;
    width: 105%;
    left: -3%;
}

The thing I have so far... I'm lost on how to make the div curved. Maybe it's late at night and my brain is not functioning..
.carousel-indicators {
    height: 80px;
    background: rgba(0,0,0,0.5);
    width: 100%;
    margin: auto;
}

.carousel-indicators li {
    font-size: 0.9rem;
    height: 40px;
    text-indent: inherit;
    background: none;
    display: flex;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    -webkit-justify-content: flex-end;
    -moz-justify-content: flex-end;
    -ms-flex-pack: end;
    width: 12%;
    line-height: 1.3rem;
    position: relative;
    margin: 0 15px;
    flex-direction: column;
    -webkit-flex-direction: column;
-ms-flex-direction: column;
-moz-flex-direction: column;
    text-align: center;
}

.carousel-indicators li:after{
    height: 8px;
    width: 8px;
    border-radius: 100%;
    content: " ";
    background: #fff;
    position: absolute;
    left: 50%;
    bottom: -20px;
}

.carousel-indicators li.active{
color: #72c267;
}

.carousel-indicators li.active:after{
height: 10px;
width: 10px;
background: #72c267;
box-shadow: 0 0 0 2px #72c267;
border: 2px solid rgba(0, 0, 0, 0.6);
}

EDIT: Adding HTML
Using bootstrap on wordpress, so this has some variables on php as well:

                            <?php  $number = 0;
        foreach(Home::getRepeatable(get_the_ID(),'carrousel_slide') ?? [] as $key =>
                            $value): ?>
                            <li class="<?= $key === 0 ? 'active' : '' ?>" data-target="#carouselExampleSlidesOnly" data-slide-to="<?php echo $number++; ?>"><?php echo $value['ss_slide_title'];?>

                            <?php endforeach; ?>

                        <?php foreach(Home::getRepeatable(get_the_ID(),'carrousel_slide') ?? [] as $key =>
                        $value):?>
                        <div class="carousel-item <?= $key === 0 ? 'active' : '' ?>">

<?php echo $value['ss_slide_desc']; ?>

                                <a class="btn btn-primary btn-md" href="<?=  $value['ss_slide_link']; ?>"><?php echo $value['ss_slide_button_text']; ?>

                            <img class="img-fluid d-block w-100" src="<?= wp_get_attachment_url($value['ss_slide_image']); ?>" alt="First slide" />

                        <?php endforeach ?>

Comment: I'd look into `motion-path` in CSS ([example](https://css-irl.info/positioning-text-along-a-path-with-css/)) or `textPath` in SVG ([example](https://css-tricks.com/snippets/svg/curved-text-along-path/)).
Comment: Some HTML would be useful...
Comment: You should look after your question from time to time and react on the comments. Otherwise your bounty is wasted...
Comment: I'm sorry, got caught and was not able to come back. But you're right. I'm adding HTML now
Comment: @JeremyCaney I really like the idea of the textPath in SVG. Seems to be the most acurate to follow the right angles. But I dont't understand how to "draw" the SVG. Any advice? I've updated my question with HTML in case you can take a look..
Answer: You should post also complete code, it is not always enough with CSS. (Enlico already commented this to you).
Anyway, a posible solution would be this, moving the elements in a vertical amount to make them rotate:

.container {
    width: 100%;
    position: relative;
    top: 200px;
}

.element {
    position: absolute;
    background-color: tomato;
    left: 50%;
    transform: translateY(-400px) rotate(var(--angle)) translateY(400px) rotate(calc(-1 * var(--angle)));
}

.element:nth-child(1) {
    --angle: 50deg;
}

.element:nth-child(2) {
    --angle: 30deg;
}

.element:nth-child(3) {
    --angle: 10deg;
}

.element:nth-child(4) {
    --angle: -10deg;
}

.element:nth-child(5) {
    --angle: -30deg;
}

.element:nth-child(6) {
    --angle: -50deg;
}

item 1

item 2

item 3

item 4

item 5

item 6

Comment: Sorry! Edited my question to include HTML. I' playing around with your code, but it seems that the background overlay is missing. But it's a great start for me! Thank you!!
Comment: I focused my answer on the issue of the question (bending the content). I left apart other details of your code. Anyway, happy that it helped you
Answer: This might get you in the right direction. I made this in CSS but I would suggest you to use svg if you want the output same as that of the image you mentioned in the question.

var slide_btn = document.getElementsByClassName('slide_btn');
var carousel = document.getElementsByClassName('carousel')[0];
var carousel_after = document.getElementsByClassName('carousel_after')[0];
slide_btn[0].onclick = function() {
  carousel.style.backgroundImage = "url('https://media.architecturaldigest.com/photos/5d49d4d911d3930008a81c6c/master/pass/GettyImages-872448084.jpg')";
  carousel_after.style.backgroundImage = "url('https://media.architecturaldigest.com/photos/5d49d4d911d3930008a81c6c/master/pass/GettyImages-872448084.jpg')";
}
* {
  margin: 0px;
  padding: 0px;
  font-family: 'arial';
}

body {
  background: #161616;
}

.container {
  position: relative;
  height: 80vh;
  width: 100%;
  display: flex;
  background: #161616;
  overflow: hidden;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.carousel {
  position: absolute;
  top: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  height: 80vh;
  width: 130%;
  background-image: url("https://www.build-review.com/wp-content/uploads/2020/01/model-architecture.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 2;
  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
  transition: 0.4s;
}

.carousel_after {
  position: absolute;
  top: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  height: 60vh;
  width: 130%;
  background-image: url("https://www.build-review.com/wp-content/uploads/2020/01/model-architecture.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 5;
  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
  transition: 0.4s;
}

.slider_pane {
  position: absolute;
  bottom: 0;
  padding-top: 50vh;
  background: rgba(0, 0, 0, 0.6);
  height: 30vh;
  display: flex;
  width: 130%;
  align-items: center;
  justify-content: center;
  z-index: 4;
  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
}

.slider_pane p {
  display: flex;
  padding: 30px;
  margin-top: 50px;
}

.slider_pane a {
  display: inline-block;
  text-decoration: none;
  color: white;
  width: 160px;
  transition: 0.2s;
  font-size: 1.5rem;
  margin: 0px 2rem;
  text-align: center;
  transform-origin: 50% 50%;
}

.slider_pane a:hover {
  color: #00FF7F;
}

.slider_pane a:nth-child(1) {
  transform-origin: 100% 0%;
  transform: rotateZ(10deg);
}

.slider_pane a:nth-child(2) {
  transform-origin: 0% 0%;
  transform: rotateZ(5deg)translateY(5px);
}

.slider_pane a:nth-child(3) {
  transform-origin: 0% 0%;
  transform: rotateZ(0deg)translateY(25px);
}

.slider_pane a:nth-child(4) {
  transform-origin: 100% 0%;
  transform: rotateZ(-4deg)translateY(15px);
}

.slider_pane a:nth-child(5) {
  transform-origin: 0% 0%;
  transform: rotateZ(-6deg)translateY(10px);
}

.slider_pane a:nth-child(6) {
  transform-origin: 0% 0%;
  transform: rotateZ(-10deg)translateY(-15px);
}

@media only screen and (max-width: 1121px) {
  .carousel,
  .carousel_after {
    background-size: 1457.3px auto;
  }
}

      Collaborative Science
      Traditional Research
      Pandemic Preparedness
      Global Reach
      Educational Mission
      Physician Scientists


Tossing a ring over pegs: Snaring exactly one peg?

Question: Let there be a point peg at every $\mathbb{Z}^2$
lattice point. Let a ring be a radius $r$ circle.

Q1. Which value of $r$ maximizes the chance that a
randomly placed ring will enclose exactly one peg?

Small $r$ may capture no pegs; large $r$ may capture
more than one peg.
I know this is elementary, but I am not seeing an easy
route to calculate $r$. My real question is this generalization:

Q2. Which value of $r$ maximizes the chance that a
randomly placed $(d{-}1)$ sphere in $\mathbb{R}^d$ will enclose exactly one lattice
point of $\mathbb{Z}^d$?

Questions inspired by "ring toss":

(Image from gameplanent.)

Added. Following @GussB's suggestion, I compute
$r=0.541$:

Comment: For $d = 2$, the situation is relatively simple, since we want the radius to be such that the portion of the arc within the square which is outside the other circles to be equal to $45$ degrees, or $\pi/4$.  Then the radius is $\frac{\sec \pi/8}{2} \approx 0.54120$.  I don't think this can generalize easily to higher dimensions.
Answer: In order to evaluate the probability for a fixed $r$, you can draw a circle of radius $r$ around each lattice point. The proportion of $\mathbb{R}^2$ that is in precisely one circle is the probability you are looking for.
Note that it suffices to compute this proportion inside the square (0,0), (0,1), (1,1), (1,0) due to the fact that the pattern is repeated. Moreover for optimal $r$, we must have $0 < r < \frac12\sqrt{2}$, so that each point of the square is in either 0, 1 or 2 circles.
In this square, there are four quarters of a circle, with a combined area of $\pi r^2$. From that we have to subtract the overlapping area twice. Let $A_1(r)$ denote the intersection area of two circles of radius $r$ whose centers are at distance $1$ of each other, which can be computed exactly. Then the probability you are looking for is $$\pi r^2 - 4 A_1(r),$$ which should then be maximized on the interval $0 < r < \frac12\sqrt{2}$ to answer your first question.
This approach generalizes to dimension $d$, although you may have to take into account more than 2 spheres intersecting.
Answer: This question can be cast into the problem of finding the expectation number of lattice points say, $L_d$ that fall inside a hypersphere in  $d$-dimensions. Now for large values of $d$
$$E[L_d] \approx V_d(r)$$
Where $V_d(r)$ is the volume of the hypersphere with radius $r$. In our case $E[L_d] = 1$. Therefore, solving $r$ for $V_d = 1$ should give us the solution which will become increasingly accurate as $d$ and $r$ increases. Hence,
$$ V_d  = \frac{\pi^{d/2}r^{d/2}}{\Gamma(\frac{d}{2}+1)}$$
$$r =  \frac{\Gamma(d/2+1)^{2/d}}{\pi}$$
The error on $r$ will approach zero as $d \rightarrow \infty$ as $ L_d - V_d \approx  O(r^{d-2}) $(check paper 1).
Also, notice that the value of $r$ satisfying the above conditions are much larger than $1$ for $d > 10$. Again pushing down the error. Hence, for $d \rightarrow \infty $, the obove relation holds.
The last thing is that, Is this expectation translation-invariant? And again you may verify this by noticing that the lattice points are uniformly distributed samples over $R^{n}$ and the number of lattice points in each sphere centered at a lattice point is the same. And hence this expectation value holds.
In the case of $d=2$, $r = 0.564$ (with respect to your answer to GausB), which is already quite a small error, so we can expect this error to go down fast.
NOTE: I think I am not able to make the translation invariance point clearly but it will hold and the arguments I gave were based on chapter-8 of Introduction to Geometric Probability by Klein and Rota.
paper-1 : https://www.jstor.org/stable/2003508?seq=1
paper-2 : https://en.wikipedia.org/wiki/Gauss_circle_problem
paper-3 : http://www.dtc.umn.edu/~odlyzko/doc/arch/high.dim.spheres.pdf


Does solution exists for this equation ?

Question: Is it possible to proove that solution exists for this equation ?
$2^x\equiv 30930818124575525495\pmod {3^{41}}$
I know $x < 3^{41}$ if solution exists. I tried brute force approach couldn't find any solution up to $x < 10^{10}$. Any help will be appreciated
Comment: I haven't tried but you could try proving that there exists a solution $2^x\equiv n\pmod {3^{41}}$ for all odd numbers $n$.
Answer: Sticking to brute force methods:
According to wolfram alpha, the order of $2$ $\pmod {3^{41}}$ is $24315330918113857602$  But this is $2\times 3^{40}=\varphi(3^{41})$.  Thus $2$ is a primitive root $\pmod {3^{41}}$.  As your number is not divisible by $3$, we conclude that there is indeed a solution to your congruence.  Granted, this approach doesn't tell us what the solution is.
Note:  computing the order of $2$ isn't that hard. After all, it has to be either $2\times 3^n$ or $3^n$ for $n\in \{0,\cdots,40\}$.  Even if you just check each case (not necessary), it's only $82$ cases.
Comment: Just learned how to compute order on modulo, thanks very much.
Comment: You're welcome.  Must say:  this is a tough problem to assign shortly after introducing the concept.
Comment: What about finding actual value of x ? Is there any shortcut ?
Answer: Hint $ $ Use this theorem: if $g$ is a primitive root modulo an odd prime $p,$ then $g$ is a primitive root modulo all powers $p^k,\,$ unless $g^{p-1}\equiv 1 \pmod{p^2}$; in that case, $\,g+p\,$ is.
Comment: @safarov Your question asks only about *existence* of a solution - which is solved easily by the above. As for computing a solution $x$, this is a difficult  problem in general, know as the *discrete logarithm* problem. Follow the link in [this answer](http://math.stackexchange.com/a/32353/242) for a good introduction.
Comment: I will look into this, thanks
Comment: @safarov Note that if you use this result then no large calculations are required, only a few seconds of mental arithmetic.Almost surely this is what was intended by the author of the problem (assuming it was an exercise).
Comment: What about finding actual value of x? Is there any shortcut ?


Ban command not working JDA please help debuged and everything

Question: Hello so i am making a bot in JDA and i just made a ban command but it aint banning anyone the code is
i mention the user and also put a reason and put the user id and still make no difference
package me.programmer.CodeDevelopment.Commands;

import me.programmer.CodeDevelopment.Bot;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;

import java.util.List;

public class Ban extends ListenerAdapter {

    public void onMessageGuildReceived(List<String> args, GuildMessageReceivedEvent e){
        String msg = e.getMessage().getContentRaw();
        if(msg.equalsIgnoreCase(Bot.PREFIX + "ban")){
            TextChannel channel = e.getChannel();
            Member member = e.getMember();
            List<Member> mentionedMembers = e.getMessage().getMentionedMembers();

            if (mentionedMembers.isEmpty() || args.size() < 2) {
                channel.sendMessage("Missing Arguments").queue();
                return;
            }

            Member target = mentionedMembers.get(0);
            String reason = String.join(" ", args.subList(1, args.size()));

            if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)){
                channel.sendMessage("You dont have pmerission to run this command").queue();
                return;
            }

            target.ban(1)
                    .reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
        }

    }

}

Please help i have been stuck on this for a little while.
Comment: You didn't override the method from ListenerAdapter properly. The name and parameter list has to match.
Comment: already tried that and doesnt work
Answer: Like Minn mentioned, You didn't override the method from ListenerAdapter properly. The name and parameter list have to match.
Also, You're checking if the entire message is equal to {PREFIX}ban yet your ban command is structured like so {PREFIX}ban (user) so your code always stops on this line:
    if(msg.equalsIgnoreCase(Bot.PREFIX + "ban"))

Because that is never true when using the command correctly.
This should work instead (I've changed the msg check to starts with from equals, I've changed the method name to the right one with the right parameters from ListenerAdapter and I've then kept your usage of args by splitting the msg string and putting that into a list):
public class Ban extends ListenerAdapter {

    @Override
    public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
        String msg = e.getMessage().getContentRaw();
        if (msg.startsWith(Bot.PREFIX + "ban")) {
            TextChannel channel = e.getChannel();
            Member member = e.getMember();
            List<Member> mentionedMembers = e.getMessage().getMentionedMembers();

            List<String> args = Arrays.asList(msg.split(" "));
            if (mentionedMembers.isEmpty() || args.size() < 2) {
                channel.sendMessage("Missing Arguments").queue();
                return;
            }

            Member target = mentionedMembers.get(0);
            String reason = String.join(" ", args.subList(1, args.size()));

            if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)) {
                channel.sendMessage("You dont have pmerission to run this command").queue();
                return;
            }

            target.ban(1)
                    .reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
        }
    }
}


Should I use In memory SQL (Hekaton) for queue messaging system?

Question: I work with a platform that have a messaging system that uses SQL server tables as queues.
That system was based on this:  Using Tables as queues
ATM we are facing some scalability issues, since this distributive schema is mainly based on SQL Locks and disk operations in order to guarantee the durability/coherence of data.
In order to solve the disk based I/O bottleneck and to improve the bad distributive logic, we are thinking in changing disk based SQL tables to In memory SQL (Hekaton) available at SQL 2014 & 2016.
I've read some stuff about Hekaton already, but I'm still not sure if this is the best approach, or if is possible to implement those queues into In memory and if this is the best approach.
Most of those queues are implementing pessimistic concurrency, and Hekaton uses no locks system only optimistic concurrency (based on multi-versioning). Is it "always" (I know this is a bad word) possible to change the pessimistic concurrency into an optimistic one? For example on the above queues.
Is Hekaton made for many inserts/deletes (enqueue/dequeue), order rows (FIFO queues), and a lot of variations of table sizes (workload variations on the server will increase/decrease the queues size)? It will be possible to update properly the Statistics for the query performance of native store procedures?
I feel like native compiled SQL store procedures will improve a lot the performance, but I'm not sure if this kind of implementation (correlated FIFO queues) are good to be used on Hekaton, since I'm not finding any examples of "In memory queues" implementations using Hekaton.
Answer: You can implement in Hekaton what you described - as you mentioned, the app will have to take care of retrying in case of the transaction being aborted due to concurrency on the same row. Having said that, you also have to consider that SQL 2014 does not support large binary objects, you will need to use SQL 2016 or workaround it as we do it for ASP.NET Session state:
http://blogs.msdn.com/b/kenkilty/archive/2014/07/03/asp-net-session-state-using-sql-sever-in-memory.aspx
Hekaton is designed for OLTP, that means, lots of inserts, updates, deletes.
Plan ahead the memory requirements:
https://msdn.microsoft.com/en-us/library/dn133186.aspx
Comment: I've already implemented 3 types of queues using Hekaton. Made a workaround to support more than 8060b limitation: when the payload of a message is higher than the limit I only store a reference to a table in disk. I think this will work since I won't have many messages higher than the limit, but 2016 will release a version with much higher limit. I've implemented also a retry logic when a concurrency happens. I'm not sure yet if I have much gains from this implementation since the project is in standby, but I feel that Hekaton has A LOT of limitations that need a lot of workarounds.
Comment: We closed the gap for 2016 a lot, including the T-SQL surface area. I think your effort will be worthy, we are heavily investing in Hekaton. I forgot to mention that you should stick to natively compiled procedures as much as possible. Also, the ASP.NET session state mentioned above comes with source code, so take a look and compare notes with your implementation.


odds ratio for two variants of covid

Question: I need to calculate the odds ratio for mechanical ventilation and death in relation to
different early COVID-19 symptoms for two COVID variants - delta and omicron. How should I do it? I want to showcase that delta held higher risk of mechanical ventilation and death than omicron.
So far, I have calculated it from such table (example fo cough):
<code>                      |Delta|Omicron|
mechanical ventilation|   a      c  |
no mech.ventilation   |   b      d  |
</code>
odds ratio: $\frac{a/b}{c/d}$
Is it correct?
Answer: I think you got the odds ratio right (check also the definition on Wikipedia)
Note that if you use software like R to run a Fisher test, you will get a slightly different odds ratio relative to the formula you have (see Why do odds ratios from formula and R's fisher.test differ? Which one should one choose?). For example:
<code>mat <- matrix(c(10, 2, 10, 8), nrow= 2, byrow=FALSE)
mat
     [,1] [,2]
[1,]   10   10
[2,]    2    8

fisher.test(mat)

    Fisher's Exact Test for Count Data

data:  mat
p-value = 0.2353
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
  0.5567896 45.8529162
sample estimates:
odds ratio
  3.823229
  ^^^^^^^^
</code>
Manual calculation:
<code>(10/2)/(10/8)
[1] 4
   ^^^
</code>

I want to showcase that delta held higher risk of mechanical ventilation and death than omicron.

This may be beyond the scope of the question, but I would be careful in interpreting the odds ratio directly as the difference between variants. If this were a randomized control trial you could assume that the only difference between groups is the variant (delta or omicron) and other differences are random. In such case, you can interpret the odds ratio as a consequence of the variants. However, presumably you have observatioanl data and the two groups differ for things other than the variant (for one thing, omicron came after delta).
Comment: Thank you so much for your help :))

odds ratio for two variants of covid


two samples z test in Python

Question: Does Scipy have a z test to compare the mean of two samples?
I searched this page but couldn't find one.
Comment: This question appears to be off-topic because it is about available functions in Python.
Comment: I haven't used Python for Stats in a little while but, as I recall, it's best to use **Statsmodels** instead of **Scipy.Stats**.
Answer: Statsmodels has a ztest function that allows you to compare two means, assuming they are independent and have the same standard deviation. See the documentation here
If you need to compare means from distributions with different standard deviation, you should use CompareMeans.ztest_ind. See documentation here.
There might be other functions I'm missing so search through the documentation!
Answer: No, but this wouldn't be that hard to write a function for:
def twoSampZ(X1, X2, mudiff, sd1, sd2, n1, n2):
    from numpy import sqrt, abs, round
    from scipy.stats import norm
    pooledSE = sqrt(sd1**2/n1 + sd2**2/n2)
    z = ((X1 - X2) - mudiff)/pooledSE
    pval = 2*(norm.sf(abs(z)))
    return round(z, 3), round(pval, 4)

where X1 = $\bar{X1}$, X2 = $\bar{X2}$, mudiff = null = $\mu_1 - \mu_2$, sd1 = $\sigma_1$, sd2 = $\sigma_2$, n1 = $n_1$ and n2 = $n_2$. So, going off of this example:
z, p = twoSampZ(28, 33, 0, 14.1, 9.5, 75, 50)
print z, p

Comment: Just a little tip: `1 - norm.cdf` can be replaced in numpy using `norm.sf`, which gives better precision.

two samples z test in Python


Hover over child, affect parent. Possible with just CSS?

Question: Is it possible to affect the parent object on user hover over it's child in just CSS3?
i.e.

.random img:hover {
   somehow affect .random?
}

I know it's pretty easy to do with JQuery, JS etc. But want to steer away from JS as much as possible.
Comment: At the moment this is not possible, but there is a discussion about introducing a parent selector in CSS.
Comment: Possible duplicate of [Is there a CSS parent selector?](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) (the [accepted answer](http://stackoverflow.com/a/1014958/419956) mentions CSS2, CSS3, and CSS4)
Comment: Ah shame that, cheers for the answer though. And sorry couldn't find that previous asked question.
Answer: Using ONLY css is impossible today, but if you want to do simple things, like changing the parent's background when you hover the inner element, you can simulate the background using a sibling. This way you will be able to achieve the result using the "+" selector.

    something

However, to do this, you'll have to work using absolute positioning and deal with it's side effects, like centering things and explicit dimensions, here's an example: http://jsfiddle.net/PYN6P/


Placing a HTML control over top of a Silverlight Application and have it scroll with the application

Question:    I have a Silverlight Application (VS2010/C#) that is full screen.
   I also have a html control that is positioned overtop of the Silverlight Application.
   When the browser window is maximized the position is correct.  However when I restore down the window to a smaller dimension I get scrollbars for the silverlight application (as expected).  When I scroll down my html does not scroll and remains floating relative to its window position.  I want the html to scroll with the silverlight application.  How can this be done?
   I can not put the html in the silverlight application for business flow reasons.
Here are my style sheets

here is my html code
<form id="form1" runat="server" style="height:100%">

        --HTML CONTROLS

        <object id="silverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
              <param name="windowless" value="true"/>
              <param name="enablehtmlaccess" value="true" />
      <param name="onError" value="onSilverlightError" />
      <param name="background" value="white" />
      <param name="minRuntimeVersion" value="4.0.50826.0" />
      <param name="autoUpgrade" value="true" />

    </object>

</form>

   Thank you in advance for any help offered in this.
   I feel like the scroll bar that is appearing belongs to the silverlight application and that is why when scrolling the html content seems to float, but I have been unable to confirm this theory.
~~~EDIT~~~
   It has been confirmed that the scroll bars belong to the Silverlight instance.  To confirm this I set my html controls position to be to the far right and bottom by setting a large "LEFT" and "TOP" property in the CSS.
   At this point both the browser and the Silverlight App got scroll bars upon a resize.  The scroll bars for the browser and the silverlight app were different styles.
   After reseting the LEFT and TOP attributes and reproducing the original issue the scrollbars that were appearing had the same style as the Silverlight App and not the window.  So all scrolling is happening on the Silverlight App itself.

   Moving forward a solution may be to break the business flow and imbed the html within the Silverlight.  If someone can think of a different way to accomplish this it would be appreciated.
Answer: By capturing the scroll event I was able to adjust the top attribute of my control and allow a scrolling like effect.  Here is the basis of the solution.
Note: svMainViewer is the scroll View in the MainShell.xaml page
C# MainShell.xaml.cs code
public partial class MainShell : UserControl
{
    #region Private Variables
    private double svHorizontalOffset;
    private double svVerticalOffset;
    #endregion

    #region Constants
    const string JAVASCRIPT_FUNCTION_VERTICALOFFSETCHANGED = "SilverlightScrollViewerVerticalOffest";
    const string JAVASCRIPT_FUNCTION_HORIZONTALOFFSETCHANGED = "SilverlightScrollViewerHorizontalOffest";
    #endregion
    public MainShell(IUnityContainer container)
    {
        InitializeComponent();

        #region Code required registering scroll bar offset notifications
        NotificationHelper.RegisterForNotification("HorizontalOffset", svMainShell, OnHorizontalOffsetChanged);
        NotificationHelper.RegisterForNotification("VerticalOffset", svMainShell, OnVerticalOffsetChanged);
        #endregion
    }

    #region Methods using dependency properties
    public void OnHorizontalOffsetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        svHorizontalOffset = double.Parse(e.NewValue.ToString());
        System.Windows.Browser.HtmlPage.Window.Invoke(JAVASCRIPT_FUNCTION_HORIZONTALOFFSETCHANGED, svHorizontalOffset);
    }

    public void OnVerticalOffsetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        svVerticalOffset = double.Parse(e.NewValue.ToString());
        System.Windows.Browser.HtmlPage.Window.Invoke(JAVASCRIPT_FUNCTION_VERTICALOFFSETCHANGED, svVerticalOffset);
    }
    #endregion

}

public class NotificationHelper
{
    public static void RegisterForNotification(string property, FrameworkElement frameworkElement, PropertyChangedCallback OnCallBack)
    {
        Binding binding = new Binding(property)
        {
            Source = frameworkElement
        };

        var dependencyproperty = System.Windows.DependencyProperty.RegisterAttached("ListenAttached" + property,
                                 typeof(object), typeof(UserControl), new System.Windows.PropertyMetadata(OnCallBack));

        frameworkElement.SetBinding(dependencyproperty, binding);
    }
}

Javascript Code Snippet
function SilverlightScrollViewerVerticalOffest(offset)
{
        contentDivElement = document.getElementById("contentDiv");
        if (contentDivElement != null && contentDivElement.style.display != 'none')
        {
            contentDivElementTop = 15 - offset;
            contentDivElementTop += 'px';
            contentDivElement .style.top = contentDivElementTop ;
        }
}

You may find more detail on the code I implemented at Weareon's blog at  http://blog.weareon.net/scrollviewer-scroll-change-event-in-silverlight/


Webform Conditionals and Email Values

Question: The scenario is, I have a form that you order multiple types of stationery. Depending on what items are ordered determines, what email needs to be sent the form results.
The issue I am running into is I need a way to prevent emails from being sent to the other print vendors if their fields are left blank.
Right now they all receive every email it just shows up blank because I have it set to exclude blank fields.
Any guidance would be greatly appreciated!
Answer: You may want to try out the Rules module. It allows a lot of powerful conditions and actions to be configured. You may also pair it with the Webform Rules module to connect it to your Webforms (https://www.drupal.org/project/webform_rules).

Webform Conditionals and Email Values


Deploy multiple Web services versions at same domain

Question: I would like to have all my Web services versions deployed at the same domain, like this:

rest.mydomain.com/v1/
rest.mydomain.com/v2/
...

But these different versions are in different servers. Do I need to use a load balance server to configure this behavior? Or is there a better way to to that?
Answer: Load Balancing is the best option. Nginx, haproxy, apache, etc. support load balancing / reverse proxy based on the url path.
Layer 7 Load Balancing with HAproxy
Reverse Proxy with Nginx
Comment: Can't see performance problems unless that the latency between the Load Balancers and the backend servers is high (different networks). CPU / Memory usage on LBs is very low . All the requests will pass through the LB so you'll need the combined bandwidth from all your backends in the LB.
Comment: HD, and all the requests will pass through the load balancer, or just the first?
Comment: All requests will pass through it.
Comment: Performance problems?
Comment: Always same network. Got it!


Downcasting without being explicit

Question: I have a Base which has two child classes. bar creates a unique_ptr who's type is Base and attempts to initialize it with one of its child classes.
Certainly I can't downcast without being explicit of the type which I don't want to do. Are there ways around it?
struct Base
{

};

struct A : public Base
{
    int val;
};

struct B : public Base
{
    int val;
};

struct C : public Base
{
  // does not have val
};

void bar(bool x, int value)
{
    std::unique_ptr<Base> ptr;
    if (x)
    {
        ptr = std::make_unique();
    }
    else
    {
        ptr = std::make_unique();
    }
    ptr->val = value;  // ERROR
}

Comment: Btw. the code has undefined behavior because `Base` doesn't have a virtual destructor that is required when destroying the derived class object through a base class pointer as `std::unique_ptr` will do.
Comment: You can't. Why is `val` not a member of the base class?
Comment: @xyf And what do you expect `ptr->val = value;` to do if `ptr` doesn't actually point to an object that has a `val` member in its parent object?
Comment: But ptr is a pointer to `Base` and you can't make any assumptions in your code on how it was initialized (from `A`, `B` or some other derived class. That's just how C++/polymorphism works. If you need to access `val` through `Base`, you have to make it part of `Base`s interface. Either by moving `val` to `Base`, or by creating a virtual getter method for `val` in `Base`.
Comment: You need to use polymorphism: Give your base class a pure virtual getter and override it in the two derived classes. Then you can call the virtual method in bar and it will be dispatched to the derived classes
Comment: @user17732522 `num` won't be used in ALL the child classes per se (there may be additional in the future)
Comment: `A` and `B` are guaranteed to have `val` as you can see
Comment: The fact the members are of same type and have the same name is not sufficient for accessing them this way.
Comment: Ok, so this question is just about not wanting to duplicate the `ptr->val = value;` line with casts in the two cases?
Comment: @user17732522 basically
Comment: *'`A` and `B` are guaranteed to have `val`'* -- But how does `ptr` know it's not a `C`?
Comment: ...cause the casts are explicitly made for `A` and `B`
Answer: Types in C++ don't work this way.
If *ptr needs to have val, this must be reflected in the static type of *ptr.
In your case the static type of *ptr is Base. There is no val there.
Data flow analysis may prove that the dynamic type of *ptr always has val, but that's irrelevant. The implementation doesn't do data flow analysis. It only looks at static types.
If you need some descendants of Base to have val and others not, create an intermediate class BaseWithVal and work with that.
Answer: You can use a generic lambda or helper function template to avoid code duplication:
void bar(bool x, int value)
{
    auto make_ptr = [&]<typename T>(){
        auto ptr = std::make_unique<T>();
        ptr->val = value;
        return ptr;
    };

    std::unique_ptr<Base> ptr;
    if (x)
    {
        ptr = make_ptr.operator()();
    }
    else
    {
        ptr = make_ptr.operator()();
    }
}

This requires C++20 for the explicit template parameter on the lambda. Before C++20 a helper function is easier to manage, although the following alternative also works:
template<typename T>
struct type_identity {
    using type = T;
};

void bar(bool x, int value)
{
    auto make_ptr = [&](auto t){
        using T = typename decltype(t)::type;
        auto ptr = std::make_unique<T>();
        ptr->val = value;
        return ptr;
    };

    std::unique_ptr<Base> ptr;
    if (x)
    {
        ptr = make_ptr(type_identity{});
    }
    else
    {
        ptr = make_ptr(type_identity{});
    }
}

But as the other answer says, if there is a need to uniformly access a subset of derived classes with a val member, then these should very likely share an intermediate base class with that member. That way you can simply replace std::unique_ptr<Base> with std::unique_ptr<IntermediateBase> and everything will work.
Comment: Apologies. I did not see the information from the comment and assumed he wanted extended usage of `val` with a simple syntax.
Comment: the error I am getting `reference to 'type_identity' is ambiguous`
Comment: both of your solutions don't seem to work: this is the first one -> https://godbolt.org/z/o4cTG4Kc1
Comment: @xyf The ambiguity would only happen if you use `using namespace std;` and C++20 or later, because then the standard library also has a `std::type_identity` which is what I am replicating here for C++17 and below. That's precisely why `using namespace std;` is a bad idea.
Comment: @xyf For your latest comment: You can't access `ptr->val` when `ptr` is a pointer to `Base`. That was explained in the question comments and other answer. The point of my answer is that you can move all code that requires access to `val` to the lambda where I put `ptr->val = value;` as well. That way you don't need to duplicate any code. Of course this can be done simpler using a helper function template instead of the lambda and as mentioned at the end that is not really an ideal design of the class hierarchy. https://godbolt.org/z/b78hj48e4
Comment: @user17732522 this lambda creates a unique_ptr of type T. How's `ptr` going to be used in the caller? Say `ptr` is to be passed to another function and that would be parsing `num`? What good would it be if that isn't possible
Comment: @xyf You can't do that. If you pass `ptr` on from the caller to another function, then how can this function be sure that `ptr` actually points to an object that has the member? It could be called with a pointer to any `Base`. As the comments under the question say it is impossible. That's why I asked you whether you just want to avoid code duplication in the two `if` branches, which is possible.

Downcasting without being explicit


Não mover com Mouse o

Question: Pergunta besta porem não achei em canto nenhum, gostaria de não permitir o usuário mover o p:dialog aberto.

 ...meu código...

Answer: Basta adicionar o atributo draggable como false.
Por exemplo:

Na página 181 da documentação tem mais especificações do componente.
Você também pode baixar a documentação completa do PrimeFaces aqui.
Comment: Isso ae @Luidne
Comment: Muito obrigado! não tinha achado na internet nenhum exemplo.

Não mover com Mouse o


How can I locate an embedded h2 db based on my SQuirrel configuration?

Question: I have a simple h2 database example, I assume it is a database that is stored in a single file. But where do I find this file? I'd like to connect to that db using SQL clients like Squirrel. Where is this file placed by default?
    <property name="eclipselink.jdbc.platform"
        value="org.eclipse.persistence.platform.database.H2Platform" />
    <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
    <property name="javax.persistence.jdbc.url" value="jdbc:h2:~/myDB;FILE_LOCK=NO" />
    <property name="javax.persistence.jdbc.user" value="sa" />
    <property name="javax.persistence.jdbc.password" value="sa" />

Answer: Based on the following value:
jdbc:h2:~/myDB;FILE_LOCK=NO"

It appears that your database file is located in your home directory in a file called myDB
The ~ denotes your home directory.
Answer: You can use the following code to run H2 in server mode and connect using SQuirrl SQL client.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:target/h2/ps;AUTO_SERVER=TRUE" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>

You can use SQuirrel SQL client (http://squirrel-sql.sourceforge.net/) to connect to you H2 database and look at the tables.
Create new connection.
Select H2 in the driver dropdown menu
Set url to your project target folder h2 folder (jdbc:h2:C:\projects\workspace\TestProject\target/h2/ps;AUTO_SERVER=true)
Enter user name ("sa")
Enter password ("")
Answer: In your example the file is placed in the file myDB under your home (represented as ~ ) directory :
  <property name="javax.persistence.jdbc.url" value="jdbc:h2:**~/myDB**;FILE_LOCK=NO" />


Can't make Vue.js + TypeScript + RequireJS stack work after Vue.js 2.5 upgrade

Question: I have a project using Vue.js 2.4 + TypeScript + RequireJS stack that needs to upgrade to the latest Vue.js. Upgrade to Vue.js breaks it and I could not fix this after making changes per documentation.
index.html:
<!DOCTYPE html>

  <title>Vue.js Scratchpad</title>
  <link rel="icon" type="image/png" href="favicon.png">
  <meta charset="UTF-8">

Vue.js Scratchpad

  <input v-model="user" autofocus="true" placeholder="Enter any user name">

Loading...

  <router-view v-show="!loading" :user="user"
               @loading="onLoading" @success="onLoaded"
               @loading-error="onLoadingError"></router-view>

app-pure-vue.ts:
import * as Vue from "vue";
import * as VueRouter from "vue-router";
import { AxiosError } from "axios";

//region App components
import MessageComponent from "./messageComponent-pure-vue";
//endregion

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: MessageComponent
  }
];

const router = new VueRouter({
  routes
});

const appOptions = {
  router,
  data() {
    return {
      user: null,
      loading: false
    };
  },
  methods: {
    onLoading() {
      // @ts-ignore
      this.loading = true;
      console.log("Loading...");
    },

    onLoaded() {
      // @ts-ignore
      this.loading = false;
      console.log("Loaded.");
    },

    onLoadingError(error: AxiosError, serviceUrl: string) {
      // @ts-ignore
      this.loading = false;
      console.log("Loading error for", serviceUrl, error.response);
    }
  }
};

new Vue(appOptions).$mount("#app");

messageComponent-pure-vue.ts:
import * as Vue from "vue";
import * as VueRouter from "vue-router";
import { AxiosError } from "axios";

//region App components
import MessageComponent from "./messageComponent-pure-vue";
//endregion

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: MessageComponent
  }
];

const router = new VueRouter({
  routes
});

const appOptions = {
  router,
  data() {
    return {
      user: null,
      loading: false
    };
  },
  methods: {
    onLoading() {
      // @ts-ignore
      this.loading = true;
      console.log("Loading...");
    },

    onLoaded() {
      // @ts-ignore
      this.loading = false;
      console.log("Loaded.");
    },

    onLoadingError(error: AxiosError, serviceUrl: string) {
      // @ts-ignore
      this.loading = false;
      console.log("Loading error for", serviceUrl, error.response);
    }
  }
};

new Vue(appOptions).$mount("#app");

This example works fine. Now, to upgrade to Vue.js 2.5.0 + the latest vue-router, here are the required documented changes:

package.json: update to "vue": "~2.5.0" + "vue-router": "~3.1.5"
*.ts: import * as Vue from "vue"; => import Vue from "vue";
app-pure-vue.ts: import * as VueRouter from "vue-router"; => import VueRouter from "vue-router";

The code would compile, but blow up on Vue.extend() in messageComponent-pure-vue.ts:
Uncaught TypeError: Cannot read property 'extend' of undefined
    at Object.<anonymous> (messageComponent-pure-vue.ts:5)

Could you help me to fix this? The minimal reproducible example is available here: https://github.com/DKroot/Scratchpad/tree/master/Client_Side/Vue.js-2.5. The working 2.4 code is at https://github.com/DKroot/Scratchpad/tree/master/Client_Side/Vue.js-2.4.
What I did so far on this:

Isolated the issue to 2.5.0 upgrade
Carefully reviewed 2.5.0 release notes (https://github.com/vuejs/vue/releases/tag/v2.5.0) and the corresponding blog post (https://medium.com/the-vue-point/upcoming-typescript-changes-in-vue-2-5-e9bd7e2ecf08)
Reviewed changes in TypeScript declarations in 2.5.0. The exports are a bit too complex for me to figure out what the root cause might be.
Comment: ```Previously, we already recommend using ES-style imports (import Vue from 'vue') everywhere with "allowSyntheticDefaultImports": true in tsconfig.json. The new typings will officially move to ES-style import/export syntax, so that config is no longer necessary, and users are required to use ES-style imports in all cases.``` So you need to use `import Vue from 'vue'`, as that's the official ES-style import sytnax
Comment: @Ohgodwhy This is exactly what I did with 2.5.0:

import Vue from "vue";
import VueRouter from "vue-router";

This allows code to compile. It blows up at runtime though.
Comment: What version of `vue-template-compiler` do you have installed?
Comment: @Ohgodwhy None. All of the dependencies in this minimal example are listed in `package.json`.
Comment: Can you verify that the `vue-template-compiler` version in your `lock file` matches the installed `Vue` version?
Comment: @Ohgodwhy I checked `package-lock.json`. `vue-template-compiler` is not there (I'm not using it).
Comment: I must have misunderstood. Are you not using vue in a runtime environment? If you are, go ahead and require it and pin it at the same version as your `vue` is.
Comment: The code above is a full running example, not requiring a build. The example stack is using 1) Vue, 2) TypeScript (compile-time) and 3) RequireJS. Additionally, it's using 4) vue-router and 5) axios, but #4 and #5 look immaterial to the problem. That's all.
Comment: Ah. Thanks for clearing that up. Sorry I couldn't have been more helpful.
Comment: You might set up a minimal Github repo which reproduces the error so we can properly figure out what's going on and help.
Comment: @Aer0 Done: https://github.com/DKroot/Scratchpad/tree/master/Client_Side/Vue.js-2.5
Answer: TL;DR:
Try this instead:
import Vue from "vue";
import VueRouter from "vue-router";

Explanation:
When a module is written this way:
// module.ts
export function x() { ... }
export function y() { ... }

you would import it like so:
import * as Module from "./module";

but when it is written like this:
// module-with-default.ts
export default class Module {
  public static function x() { ... }
  public static function y() { ... }
}

you would import it like this:
import Module from "./module-with-default";

in both cases you will be able to use it like this:
Module.x();
Module.y();

Changes in Vue.js:
This is how it is exported in v2.5.0:
export default Vue

and this is is how it is exported in v2.4.0:
export = Vue;

Comment: It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.
Comment: Excellent! Thank you! This site is special, and a place where we can make a difference. It's about paying it forward!
Comment: @DoronG This is exactly what I did in https://github.com/DKroot/Scratchpad/tree/master/Client_Side/Vue.js-2.5, but it blows up: see #2 and #3 in the original question.
Comment: @DoronG I realized that I probably should have posted the non-working 2.5 version rather than the working 2.4 + changes. Let me know how you want to handle this. I can clarify the question or just leave it be. I just would like to get the fix ultimately.
Comment: @DKroot I'll take a look at your repos
Comment: @DoronG Thanks in advance!
Comment: @DKroot Added another answer, but keeping this one as it is a valid answer to the TypeScript portion of the issue
Answer: TL; DR
Add these to the project:
// vue-loader.ts
import * as AllVue from "Vue";
import Defaults from "Vue";

export const Vue = AllVue as unknown as Defaults;
export default Vue;

// vue-router-loader.ts
import * as AllVueRouter from "Vue-router";
import Defaults from "Vue-router";

export const Vue = AllVueRouter as unknown as Defaults;
export default Vue;

configure RequireJS like this:
paths: {
  Vue: "node_modules/vue/dist/vue.min",
  vue: "vue-loader",
  "Vue-router": "node_modules/vue-router/dist/vue-router.min",
  "vue-router": "vue-router-loader"
}

Explanation
The issue is caused by how TypeScript generates the JavaScript for an amd module with default exports as well as how RequireJS loads those default exports.
When you do:
import Vue from "vue";

Vue.extend(...);

TypeScript translates it into:
define(["require", "exports", "vue"], function (require, exports, vue_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    vue_1.default.extend(..);
});

Note that .default part? the issue is that RequireJS, sets vue_1 to be the actual default, so vue_1.default ends up being undefined (hence your original error)
When you use the loaders above, you are re-exporting the * which is actually the default export as both the non-default export AND the default export. This is the code that is generated for the vue-loader.ts:
define(["require", "exports", "Vue"], function (require, exports, AllVue) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Vue = AllVue; // <--- this resolves your problem
    exports.default = exports.Vue;
});

in order to use our loaders, we're "re-routing" the resolution. So if real code tries to require vue it will go to our loader, which will load Vue, which is the real Vue code.
Recommendation
I guess the best way to avoid this issue is by not using RequireJS - if you don't need IE support, you can just do native module loading or use Webpack
Another possible solution
Look here: Missing default export when using SystemJS or RequireJS makes Vue unusable with TypeScript
Comment: This is absolutely fantastic! You helped a lot with TypeScript skills that go far beyond my level.

We do need IE 11 (at least) and did prototype Webpack, but decided against using it because the value-add was not high enough for the existing codebase, which uses RequireJS.
Comment: A small addition: this solution worked perfectly on Mac and Windows. On Linux TypeScript compiler paths have to be added otherwise `tsc` can't resolve imports from "Vue" because of file system case sensitivity. To fix:

`tsconfig.json`:
```
"compilerOptions": {
    // Base directory to resolve non-relative module names. This must be specified if `paths` is.
    "baseUrl": "node_modules",
    "paths": {
      // Mappings are relative to `baseUrl`
      "Vue": ["vue"],
      "Vue-router": ["vue-router"]
    }
}
```


Invertible ideals are finitely generated.

Question:
Let $R$ be an integral domain and let $I,J \subseteq R$ be ideals. Suppose $IJ=(a)$ for some $a \in R$. We wish to show that $I$ and $J$ are finitely generated.

Since $a \in IJ$ we know $a$ can be written as the finite sum of products of the form $xy$, where $x \in I$ and $y \in J$. I want to show that $I$ is generated by these particular $x$'s (and analogously $J$ is generated by these particular $y$'s). But I'm having some trouble & I'm ready for a bigger hint.
Comment: See Lemma 1 from [this answer](http://math.stackexchange.com/a/162779/121097).
Answer: By hypothesis, there exist elements $r_i\in I, s_i\in J,\enspace i=1,\dots, n$ such that $\displaystyle a=\sum_{i=1}^n r_is_i$.
Now for any $x\in I$, one has $\;\displaystyle x=\sum_{i=1}^n r_i\frac{s_i}a x$. Observe that, since $s_ix\in IJ=(a)$, $\dfrac{s_ix}a\in R$, so that $x\in (r_1,\dots, r_n)$.
By symmetry, the same is true for $J$.
Incidentally, it also proves $I$ and $J$ are projective ideals (Bourbaki, Algebra, Ch. II Linear Algebra, §2, n°6, prop. 12).
Answer: If $IJ=0$ then $I=J=0$. Otherwise, $a\ne0$ and then $a^{-1}IJ=R$. Thus $1=a^{-1}\sum_{i=1}^na_ib_i$ with $a_i\in I$ and $b_i\in J$. Let's show that $I=(a_1,\dots,a_n)$. For $x\in I$ we have $x=\sum_{i=1}^na_i(a^{-1}xb_i)$, and since $a^{-1}xb_i\in a^{-1}IJ=R$ we are done. (Similarly for $J$.)
Comment: Why is $a$ invertible?
Comment: @Nitrogen $a$ is not invertible. The equality $a^{-1}IJ=R$ holds in the field of fractions. (For more details look for fractional / invertible ideals.)


Change all layout background colors depends on the button's value

Question: I'm trying to make an activity where user can choose a color from the buttons, after clicking one of it the entire application's layouts change base on the value of the button. I'm sorry I just started android programming already a week now, noob here.
Here is my code in theme_layout
<?xml version="1.0" encoding="utf-8"?>

`<RelativeLayout` xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#618685"
android:id="@+id/relative"
tools:Context="com.majimechibireminder2.Themes" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="26dp"
    android:text="@string/save" />

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="260dp"
    android:layout_height="280dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:fillViewport="false"
    android:orientation="vertical"
    android:padding="10dp" >

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="395dp"
        android:background="#618685" >

        <Button
            android:id="@+id/colorBlue"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#4d4dff" />

        <Button
            android:id="@+id/colorPurple"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#d11aff" />

        <Button
            android:id="@+id/colorPink"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#ff4dc4" />

        <Button
            android:id="@+id/colorRed"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#ff0000" />

        <Button
            android:id="@+id/colorYellow"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#ffff00" />

        <Button
            android:id="@+id/colorOrange"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#ffaa00" />

        <Button
            android:id="@+id/colorGreen"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="#5cd65c" />
    </TableLayout>
</ScrollView>

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/scrollView1"
    android:layout_alignLeft="@+id/scrollView1"
    android:layout_marginBottom="24dp"
    android:text="@string/theme_color"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Recent code in my java class
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    relLayout = (View) findViewById(R.id.relative_theme);
     SharedPreferences preferences = getSharedPreferences("MY_APP",MODE_PRIVATE);
     setTheme(preferences.getInt("MY_CURRENT_THEME",R.style.AppTheme));
    setContentView(R.layout.theme_layout);

    findViewById(R.id.colorBlue).setOnClickListener(this);
    findViewById(R.id.colorGreen).setOnClickListener(this);
    findViewById(R.id.colorOrange).setOnClickListener(this);
    findViewById(R.id.colorPink).setOnClickListener(this);
    findViewById(R.id.colorPurple).setOnClickListener(this);
    findViewById(R.id.colorRed).setOnClickListener(this);
    findViewById(R.id.colorYellow).setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()){
    case R.id.colorRed:
        preferences.edit().putInt("MY_CURRENT_THEME",R.style.red_theme).commit();
        finish(); startActivity(getIntent());
        break;
    }

}

}
Answer: Changing entire application colors or themes requires a configuration changes of the application. Initially We need to create a list of styles depending on your no of colors in your app. So in your styles.xml update the code like below and make changes accordingly for your app needs.

Since your styles require different colors so maintain them in colors.xml file
<?xml version="1.0" encoding="utf-8"?><resources>
<color name="windowBackground">#FFFFFF</color>
<color name="navigationColor">#000000</color>
<color name="colorAccent">#FF4081</color>

<color name="redprimary">#F44336</color>
<color name="redprimary_dark">#D32F2F</color>
<color name="redprimary_light">#FFCDD2</color>
<color name="redaccent">#FF4081</color>
<color name="redprimary_text">#212121</color>
<color name="redsecondary_text">#727272</color>
<color name="redicons">#FFFFFF</color>
<color name="reddivider">#B6B6B6</color>

<color name="brownprimary">#795548</color>
<color name="brownprimary_dark">#5D4037</color>
<color name="brownprimary_light">#D7CCC8</color>
<color name="brownaccent">#9E9E9E</color>
<color name="brownprimary_text">#212121</color>
<color name="brownsecondary_text">#727272</color>
<color name="brownicons">#FFFFFF</color>
<color name="browndivider">#B6B6B6</color>

<color name="greenprimary">#4CAF50</color>
<color name="greenprimary_dark">#388E3C</color>
<color name="greenprimary_light">#C8E6C9</color>
<color name="greenaccent">#FFC107</color>
<color name="greenprimary_text">#212121</color>
<color name="greensecondary_text">#727272</color>
<color name="greenicons">#FFFFFF</color>
<color name="greendivider">#B6B6B6</color>

<color name="yellowprimary">#FFEB3B</color>
<color name="yellowprimary_dark">#FBC02D</color>
<color name="yellowprimary_light">#FFF9C4</color>
<color name="yellowaccent">#448AFF</color>
<color name="yellowprimary_text">#212121</color>
<color name="yellowsecondary_text">#727272</color>
<color name="yellowicons">#212121</color>
<color name="yellowdivider">#B6B6B6</color>

We update all the activities with the below code to set the theme when user opens the activity. add before setting the layout //setContentView()
 SharedPreferences preferences = getSharedPreferences("MY_APP",MODE_PRIVATE);setTheme(preferences.getInt("MY_CURRENT_THEME",R.style.default_theme));

So now when ever user clicks on different color button just set the new theme and update the app by calling finish and start activity respectively
preferences.edit().putInt("MY_CURRENT_THEME",R.style.new_theme).commit();
        finish();
        startActivity(getIntent());

Comment: I appreciate your answer :) but how am I suppose to make that NEW THEME base on the button to be applied on every layouts? it seems the 2 codes use to apply the changes not make a change :) should I use case statements for the buttons by doing onClickListener?
Comment: Yes. In on click listner of each button apply the theme for example : On Brown Button click preferences.edit().putInt("MY_CURRENT_THEME",R.style.brown_theme).commit();
        finish();
        startActivity(getIntent()); Similarly On red Button click preferences.edit().putInt("MY_CURRENT_THEME",R.style.red_theme).commit();
        finish();
        startActivity(getIntent());
Comment: I still got an error in the onClick event, I just followed your instruction
Comment: remove this line below super.onCreate `relLayout = (View) findViewById(R.id.relative_theme);`
Comment: Still the same error, I'm thinking, in the button click it does not specify the color of the layout that should be changed although I commit changes in preferences, since button click should be use to apply changes to all layouts not to only to commit changes in the preferences


ReSharper VS CodeRush performance

Question: I have seen extensive articles and blogs posts on the comparison, but what about the performance?
I am fine with the function of ReSharper but the performance is unbearable.
I am willing to change to escape that pitfall, but will I actually be escaping it?
I'm not asking anyone to do statistics on a fresh machine, but what is the approximate factor? I'm looking for something more than just "blank is faster".
2 / 1?
Answer: Firstly, full disclosure: I have just finished running through the full trial period for both Resharper and Coderush, and in the end I spent my money on Resharper.
To directly answer your question - yes, in my experience Coderush is much faster than Resharper. Often with Resharper the entire UI will pause for a fraction of second or so while it performs the dynamic compile to test for errors in the code, and you can visibly see the sidebar refresh. Coderush on the hand added very little noticeable performance penalty.
I stuck with Resharper though for two reasons: Firstly the feature set it provides is simply a better fit for my work style. I gave Coderush four weeks to win me other, but its main selling point (the frankly brilliant templating engine) never made up for the lack of functionality that I had learnt to rely on in my four weeks with Resharper. Secondly I noticed that the performance of Resharper dramatically improved with the latest version the slowdown was only really bad on files that were in need of refactoring anyway - files created with Resharper in mind tended to work very well as there were less errors being flagged.
Both tools have generous trial period though and I had no problem installing, uninstalling and flip-flopping between the two of them, so the best thing I can suggest is to try for yourself. For me Coderush is faster and feels more professional, but Resharper has functionality I wasn't willing to give up.
Comment: Can you please name those features of Resharper? I tried to compare trial versions but didn't find anything that R# does better than CR.
Comment: FWIW Coderush 9.2 (available currently only as a trial. Contact me on twitter @RoryBecker if you'd like a link) is insanely fast and memory efficient compared to any previous version.
Comment: CodeRush 9.2 performance is detailed here -> http://community.devexpress.com/blogs/markmiller/archive/2009/06/17/performance-and-memory-milestones-in-coderush-and-refactor-pro-preview-of-9-2.aspx.
Answer: Thanks for the feedback. Can you go into more detail on which features you found one had over the other? what were you not willing to give up?
For me, the only feature I like in ReSharper that CodeRush is lacking is Unit Testing. Everything else, I find CodeRush to exceed in...but I'm new to both products, so I would like to know more.
Comment: Off the top of my head there is the unit testing, better support for interfaces (Resharper has useful features to move to and from the implementations of an interface methods. Since pretty much everything in my current project is accessed through interfaces this is a God send), and better (though not perfect) XMAL support. In the end CodeRush made it faster to write the code and Resharper made it faster to navigate and refactor it, and I do far more of the later.
Answer: I agree with Martin, but also would say that since version 4.5 ReSharper is alot faster especially on large projects.
I went with coderush for sometime but having worked with in a dev team I would say R# is still the most useful.
I have some discount coupons and extended trials for ReSharper if you are interested:
http://web2asp.net/2009/09/resharper-discount-and-extended-trial.html

ReSharper VS CodeRush performance


Writing lecture notes on a tablet

Question: I'm a graduate student concerned with taking lecture notes from courses I attend. I can type in real-tie in latex (except in tikz) but I find writing sometimes more intuitive (and using laptop is clumsy in some lecture halls as well). Since this question was asked many years ago, the technology has massively changed.
What do you think on writing on ipad pro? Is the "usual" ipad enough (with an appropriate stylo)? Is there any change for the android tablets?
Answer: I've tried to do it with my iPad. The obvious problem is the speed. You cannot write on iPad as fast as you can with a pen and paper.

Writing lecture notes on a tablet


Is there a way to see which groups/users have access to an RSA key container?

Question: I used aspnet_regiis to create an RSA key container (machine container).
I want to secure it and I know I can use the -pa and -pr commands to specify access.  But is there a way to see which accounts/groups have access to it?
My concern is I created a container that is basically an open book that anyone can access on this machine and get the private key.
Answer: Machine Keys are stored in: %ProgramData%\Microsoft\Crypto\RSA\MachineKeys
They have normal file permissions, you can view as you'd like. Be careful changing permissions, they're easy to screw up.
Comment: You are my hero, the wind beneath my wings.  Not sure why this eluded me -- I was aware of this storage location but for some reason I was thinking these key containers were "magic".  Thank you!
Comment: The files in this folder have hex-formatted names, so how do I find a key container with specific name? Any idea?


Gluster snapshot directory error: Transport endpoint is not connected

Question: When I try to access the snapshot directory for a volume, I keep getting <code>.snaps: Transport endpoint is not connected</code> I killed and started the glusterd service but still keep getting that error message. Does anyone has an idea how I can resolve this? I am at a loss as to what else to do to fix this issue. I am able to access the volume fine and all bricks in the cluster are online.
Answer: Rebooting the nodes seemed to have fixed the issue.


How to code a jButton to turn the laptop or device to battery saver mode

Question: I haven't tried any coding, because I'm inexperienced.
But for an application I'm currently making (for an assignment) I want to enable the user to turn the battery saver mode when the count down ended, (if the user previously selected the 'turn battery saver when resting' checkbox) the power-saver mode will be automatically enabled by the software. (OS - Windows 10).
Comment: Doing that would require the programming language to get deep into the guts of the OS. Java is **not** that language, as it takes a 'higher level' approach which tries to work across all machines. BTW *"I'm inexperienced. .. (for an assignment)"* A **good** instructor / teacher would realize this was not a job for Java, so I'm guessing you're trying to do this above and beyond the task assigned. Just .. **don't**. Your time would be better spent (and the teacher more impressed) if the code for the assigned task was well written and well documented. Save these extras for your own apps.
Comment: The command line would be something like `powercfg.exe /setactive ...`. With ProcessBuilder you could execute such a command line. (1) Find exact command line working. (2) Execute such a command in Java with ProcessBuilder. Or you could separate things by trying first to start Notepad.exe with ProcessBuilder.
Comment: What is your os? If it's android, please use the tag.
Comment: @NomadMaker please read the post :) OP did tell what the OS is ;)
Answer: You can implement such an action by executing a cmd command via the ProcessBuilder.
I have put together a program that works for me:
<code>public static void main(String[] args) throws Exception {

  JPanel panel = new JPanel();
  JFrame frame = new JFrame();
  frame.setSize(200, 200);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.add(panel);

  JButton button = new JButton("Standby");
  panel.add(button);
  frame.setVisible(true);

  button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
      ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "rundll32.exe powrprof.dll,SetSuspendState");
      builder.redirectErrorStream(true);
      try {
        builder.start();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  });
}
</code>
Maybe you need to change the command "rundll32.exe powrprof.dll,SetSuspendState" to something else.


Variable cannot access outside .then()

Question: I am trying to set a authenticator for my local application. Found that I am not able to access my var outside my .then() method
var authenticated = false;
Auth.findtheUser({
}).then(user => {
  verified= user.name.verified;
  console.log("authenticated11", verified)
}
).catch(err => console.log(err));
console.log("authenticated", verified)

the output for authenticated11 output comes as true but not the one at the end
Could anyone help me out on this. New to javascript.
Answer: You cant use the result of an asynchronous function directly after it in JS.  See this question: How to return the response from an asynchronous call
Comment: The question does have lot of information in it i am not sure promise would work for my case
Comment: You are using a promise in your current code.  Then .then() function is called after findtheUser resolves.
Answer: According to what you described in a comment in this answer. You are facing an exception related to the scope.
var authenticated = false;
Auth.findtheUser({
  }).then(user => {
    verified= user.name.verified;
    console.log("authenticated11", verified)
}
).catch(err => console.log(err));
// This will throw an exception because verified does not exist in this scope
console.log("authenticated", verified)

You should change that to this
var authenticated = false;
var verified;
Auth.findtheUser({
  }).then(user => {
    verified= user.name.verified;
    console.log("authenticated11", verified)
}
).catch(err => console.log(err));
// This will throw an exception because verified does not exist in this scope
console.log("authenticated", verified)

Comment: When i declare in this way
The compiler days verified is not defined no-undef
Comment: Ok that is different! You got that exception because you had not declared the variable before and the console log is out of the scope of "verified" variable. I'll edit my answer to you
Comment: I tried this approach before asking the question in stackoverflow. The answer you posted did not work, the output for the verified var is undefined
Comment: You can't log it out of the scope of the promise
Comment: That is what my issue is
I want the variable to be used outside of the promise block

Variable cannot access outside .then()


Reactive Plotly in R Shiny is producing odd looking data

Question: I'm trying to create a plotly plot of a few variables from a csv file that gets updated hourly. The resulting graph is a straight 1:1 line for the pm_cor series, the other series are missing.
I'd like to eventually be able to turn series on and off, but for now, I just want to see my data looking as expected. I do need to perform some transformations on the data to get it corrected, so it has complicated the code a bit, but here's what I have:
library(shinydashboard)
library(plotly)
library(readr)
library(xts)
library(lubridate)
library(tidyr)
library(dplyr)

ui <- dashboardPage(
    dashboardHeader(title = "Sensors", disable = T),
    dashboardSidebar(
        disable = T,
        sidebarMenu()
    ),
    dashboardBody(
        fluidRow(
            box(width= 9, title = "Sensors", background = "black", plotlyOutput("plot1"))
        ),
        shinyjs::useShinyjs()
    )
)

percentage_difference <- function(value, value_two) {
    abs((value - value_two) / ((value + value_two) / 2)) * 100
}

server <- function(input, output, session) {
    ez.read = function(file, ..., skip.rows=NULL, tolower=FALSE) {
        if (!is.null(skip.rows)) {
            tmp = readLines(file)
            tmp = tmp[-(skip.rows)]
            tmpFile = tempfile()
            on.exit(unlink(tmpFile))
            writeLines(tmp, tmpFile)
            file = tmpFile
        }
        result = read.csv(file, ...)
        if (tolower) names(result) = tolower(names(result))
        return(result)
    }

    data <- reactivePoll(1000 * 60 * 15, session,
                         checkFunc = function() { file.info("sensor.csv")$mtime},
                         valueFunc = function() {
                             data <- ez.read("sensor.csv", tolower = T)
                             data$time_stamp <- as_datetime(data$time_stamp)
                             names(data)[1] <- "date"
                             names(data)[5] <- "pm_a"
                             names(data)[6] <- "pm_b"
                             data$humidity <- as.numeric(data$humidity)

                             #only keep data where a and b are within 5, then perform correction factors based on the bin of their average
                             data <- data %>%
                                 mutate(pm_cor = case_when(
                                     abs(pm_a - pm_b) < 5 ~
                                         ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 30,
                                                0.524 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity + 5.75,
                                                ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 50,
                                                       (0.786 * ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 20) - 3/2) + 0.524 * (1 - ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 20) - 3/2))) * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity + 5.75,
                                                       ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 210,
                                                              0.786 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity + 5.75,
                                                              ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 260,
                                                                     (0.69 * ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50) - 21/5) + 0.786 * (1 - ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50) - 21/5))) * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity * (1 - ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50) - 21/5)) + 2.966 * (rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50 - 21/5) + 5.75 * (1 - (rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50 - 21/5)) + 8.84 * 10^-4 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE)^2 * (rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50 - 21/5),
                                                                     2.966 + 0.69 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) + 8.84 * 10^-4 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE)^2
                                                              )
                                                       )
                                                  )
                                                ),
                                                TRUE ~ NA_real_
                                         ))

                                     data$pdiff <- percentage_difference(data$pm_a,data$pm_b)
                                     data <- pivot_wider(data,names_from = sensor_index,values_from = c(humidity, temperature, pm_a, pm_b, pdiff,pm_cor))
                                     data
                         })

                             output$table <- renderTable(data())

                             # Plot
                             output$plot1 <- renderPlotly({
                                 plot_data <- data()
                                 plot_data <- plot_data %>% arrange(date)
                                 fig <- plot_ly()

                                 fig <- add_trace(fig, x = plot_data$date, y = plot_data$pm_a, name = "pm_a_93325", type = 'scatter', mode = 'lines')
                                 fig <- add_trace(fig, x = plot_data$date, y = plot_data$pm_b, name = "pm_b_93325", type = 'scatter', mode = 'lines')
                                 fig <- add_trace(fig, x = plot_data$date, y = plot_data$pdiff, name = "pdiff_93325", type = 'scatter', mode = 'lines')
                                 fig <- add_trace(fig, x = plot_data$date, y = plot_data$pm_cor, name = "pm_cor_93325", type = 'scatter', mode = 'lines')

                                 fig <- layout(fig, title = "Sensor 93325 Data", xaxis = list(title = "Date"), yaxis = list(title = "Values"))

                                 fig
                             })
}

shinyApp(ui, server)

sensor.csv snippet:
time_stamp,sensor_index,humidity,temperature,pm2.5_atm_a,pm2.5_atm_b
1697000400,93325,67.867,52.7,6.048,5.279
1697004000,93325,67.5,53.6,5.442,4.786
1697040000,93325,42.5,73.067,4.239,3.941
1697011200,93325,62.267,54.666,5.662,5.16
1696399200,93325,68.267,65.0,8.456,8.181
1696377600,93325,57.633,74.25,9.389,8.784
1696122000,93325,71.334,72.467,21.392,19.959
1696176000,93325,46.567,83.733,10.662,9.479
1696168800,93325,66.8,72.667,15.885,14.849
1696338000,93325,72.867,67.966,15.727,14.604
1696374000,93325,46.058,79.342,7.748,7.088
1696294800,93325,66.534,71.7,20.221,18.643
1696546800,93325,77.867,68.966,18.733,17.2
1696492800,93325,62.733,71.7,17.677,16.736
1696222800,93325,72.566,66.534,14.466,13.815
1696230000,93325,75.3,64.2,15.539,14.407
1696010400,93325,43.1,90.8,11.642,11.361
1695924000,93325,98.6,67.2,17.668,16.203
1696593600,93325,78.233,66.434,20.581,19.08
1696690800,93325,49.3,57.0,0.814,0.725
1696644000,93325,47.067,62.466,1.255,0.933
1696658400,93325,53.2,53.8,1.522,1.256
1696089600,93325,47.534,84.433,16.819,15.394
1696060800,93325,80.0,65.066,24.43,21.921
1696068000,93325,80.0,63.966,21.581,19.63
1696734000,93325,61.034,49.767,1.782,1.402
1696806000,93325,40.267,61.034,2.359,2.224
1696759200,93325,76.0,41.3,6.032,5.632
1696784400,93325,32.466,68.8,0.494,0.325
1696824000,93325,63.0,51.233,2.014,1.639
1696874400,93325,35.5,78.1,3.917,3.566
1696816800,93325,65.5,51.067,3.525,3.069
1696834800,93325,62.067,50.133,1.827,1.571
1696888800,93325,35.341,73.966,2.612,2.024
1697029200,93325,56.5,59.833,5.155,4.486

I do get a warning in the console:
Warning: Unknown or uninitialised column: 'pm_a'.
Warning: Unknown or uninitialised column :'pm_b'.
Warning: Unknown or uninitialised column :'pdiff'.
Warning: Unknown or uninitialised column :'pm_cor'.

Answer: In your above code the y parameters of your add_trace calls don't meet the column names of your dataset (plot_data). Furthermore, in your resulting graph the other series are not missing - they are covered. Try clicking the legend items to see them.
library(shinydashboard)
library(plotly)
library(readr)
library(xts)
library(lubridate)
library(tidyr)
library(dplyr)

ui <- dashboardPage(
  dashboardHeader(title = "Sensors", disable = T),
  dashboardSidebar(
    disable = T,
    sidebarMenu()
  ),
  dashboardBody(
    fluidRow(
      box(width= 9, title = "Sensors", background = "black", plotlyOutput("plot1"))
    ),
    shinyjs::useShinyjs()
  )
)

percentage_difference <- function(value, value_two) {
  abs((value - value_two) / ((value + value_two) / 2)) * 100
}

server <- function(input, output, session) {
  ez.read = function(file, ..., skip.rows=NULL, tolower=FALSE) {
    if (!is.null(skip.rows)) {
      tmp = readLines(file)
      tmp = tmp[-(skip.rows)]
      tmpFile = tempfile()
      on.exit(unlink(tmpFile))
      writeLines(tmp, tmpFile)
      file = tmpFile
    }
    result = read.csv(file, ...)
    if (tolower) names(result) = tolower(names(result))
    return(result)
  }

  data <- reactivePoll(1000 * 60 * 15, session,
                       checkFunc = function() { file.info("sensor.csv")$mtime},
                       valueFunc = function() {
                         data <- ez.read("sensor.csv", tolower = T)
                         data$time_stamp <- as_datetime(data$time_stamp)
                         names(data)[1] <- "date"
                         names(data)[5] <- "pm_a"
                         names(data)[6] <- "pm_b"
                         data$humidity <- as.numeric(data$humidity)

                         #only keep data where a and b are within 5, then perform correction factors based on the bin of their average
                         data <- data %>%
                           mutate(pm_cor = case_when(
                             abs(pm_a - pm_b) < 5 ~
                               ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 30,
                                      0.524 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity + 5.75,
                                      ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 50,
                                             (0.786 * ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 20) - 3/2) + 0.524 * (1 - ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 20) - 3/2))) * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity + 5.75,
                                             ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 210,
                                                    0.786 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity + 5.75,
                                                    ifelse(rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) < 260,
                                                           (0.69 * ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50) - 21/5) + 0.786 * (1 - ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50) - 21/5))) * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) - 0.0862 * humidity * (1 - ((rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50) - 21/5)) + 2.966 * (rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50 - 21/5) + 5.75 * (1 - (rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50 - 21/5)) + 8.84 * 10^-4 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE)^2 * (rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) / 50 - 21/5),
                                                           2.966 + 0.69 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE) + 8.84 * 10^-4 * rowMeans(cbind(pm_a, pm_b), na.rm = TRUE)^2
                                                    )
                                             )
                                      )
                               ),
                             TRUE ~ NA_real_
                           ))

                         data$pdiff <- percentage_difference(data$pm_a,data$pm_b)
                         data <- pivot_wider(data,names_from = sensor_index,values_from = c(humidity, temperature, pm_a, pm_b, pdiff,pm_cor))
                         data
                       })

  output$table <- renderTable(data())

  # Plot
  output$plot1 <- renderPlotly({
    plot_data <- data()
    plot_data <- plot_data %>% arrange(date)
    fig <- plot_ly(data = plot_data, type = 'scatter', mode = 'lines')

    fig <- add_trace(fig, x = ~ date, y = ~ pm_a_93325, name = "pm_a_93325")
    fig <- add_trace(fig, x = ~ date, y = ~ pm_b_93325, name = "pm_b_93325")
    fig <- add_trace(fig, x = ~ date, y = ~ pdiff_93325, name = "pdiff_93325")
    fig <- add_trace(fig, x = ~ date, y = ~ pm_cor_93325, name = "pm_cor_93325")

    fig <- layout(fig, title = "Sensor 93325 Data", xaxis = list(title = "Date"), yaxis = list(title = "Values"))

    fig
  })
}

shinyApp(ui, server)

Btw. instead of re-rendering the plot you could modify it via plotlyProxyInvoke, which is faster. Please see my related answer here.
Comment: Thank you, not sure how I missed that but the graph output gave me enough to scratch my head! I will have to look into the plotlyProxyInvoke, not sure how to work that into my code, I'm not proficient with Shiny yet.


Como pesquisar um trecho em um PDF remotamente?

Question: Existe uma forma de eu pesquisar um trecho, ou uma palavra em um PDF que está na internet? Eu pesquisei sobre o CURL, algumas bibliotecas, mas não achei nada. Mais ou menos dessa forma:
Eu tenho um site e nele o cara inseriria um nome por exemplo: João.
Após isso o script do meu site verificaria se dentro do arquivo: http://www.bu.ufsc.br/ArtigoCientifico.pdf existe o nome João, e me retornaria se existe ou não.
Tem como fazer isso? Alguém conhece alguma biblioteca ou pode me dar um norte?
Answer: A biblioteca http://www.pdfparser.org/ permite pegar o texto de arquivos PDF.
<code>$url = 'http://www.bu.ufsc.br/ArtigoCientifico.pdf';
$nome = 'João';

$parser = new \Smalot\PdfParser\Parser();

$pdf = $parser->parseContent(file_get_contents($url));
$text = $pdf->getText();

if (strpos($text, $nome) !== false) {
    // achou o nome
}
</code>
Comment: Era isso mesmo, valeu cara!
Comment: Só mais uma duvida, vamos supor que eu eu tenho uma página, mas o link do PDF não está de forma clara nela, por exemplo: www.bu.ufsc.br/downloadArtigo.php?id=19898454 e somente ao clicar nesse link que o pdf é baixado. Se eu usar o file_get_contents funciona do mesmo jeito ou nao?
Comment: O file_get_contents funcionará do mesmo modo nesse caso, pois ele coleta o conteúdo sem se importar com a extensão.
Comment: Hmmm, entendi, muito obrigado o/
Comment: agora vou fazer uma outra pergunta, se tiver resposta eu crio a pergunta e você responde. Eu percebi que no site que o ID do download do PDF é gerado automaticamente, e eu não queria ter de inserir no sistema toda vez. Então existe alguma forma de eu colocar um file_get_content só com o link até o id= e ele baixar do mesmo jeito, alguma gambiarra do tipo?
Comment: No caso o id identifica qual documento baixar, você precisa saber o id, porém se houver uma página que contém um link para o artigo e não é uma página gerada dinamicamente por javascript, pode-se pegar o conteúdo usando `file_get_contents` na página com o link e achar o link com `preg_match` ou `preg_match_all` ou se for uma página muito complexa usando o https://code.google.com/p/phpquery/
Comment: Puxa, isso seria o ideal, mas a maldita página usa JavaScript.
Comment: Já que a página é montada por javascript não conheço um modo de fazer com php, só conheço o http://casperjs.org/ em conjunto com http://phantomjs.org/ eles não são para php mas pode-se criar scripts deles e executar no php com funções como `exec`, porém sua hospedagem deve permitir adicionar e executar programas, o phantomjs é um programa base standalone sem interface gráfica que carrega páginas e executa o javascript, e o casperjs é um frontend para o phantomjs com facilidades para fazer as coisas.
Comment: Vou dar uma olhada. Valeu!


why is unsupervised learning said to be learning probability distribution?

Question: In the book Deep Learning by Ian Goodfellow et al., it is mentioned that

unsupervised learning involves observing several examples
of a random vector x, and attempting to implicitly or explicitly learn the probability distribution p(x)

However when I think about the typical unsupervised algorithms such as clustering and anomaly detection, I fail to understand why such algorithms are learning $p(x)$. For example in anomaly detection, is it not more accurate to say that it is learning $p(Y|X)$ where Y = 1 if the data is an anomaly and 0 otherwise?
Answer:
For example in anomaly detection, is it not more accurate to say that it is learning $p(Y|X)$ where Y = 1 if the data is an anomaly and 0 otherwise?

If that was the case, how would this differ from classification? In anomaly detection you don't have labels, or have insufficient labels to treat this as classification. In such a case, you don't observe $Y$ so cannot learn $p(Y|X)$ from the data. Instead, you observe only $X$ and can learn $p(X)$, so you could make judgements like "$x'$ is not alike what we observed for $X$" (anomaly), or "$x'$ looks like the data $X$ that we previously observed". We can think of those as of probabilistic statements that $\Pr(X = x')$ is small. The models themselves can either be probabilistic and return the predictions in terms of probabilities or can do this indirectly by telling us what is the distance between $x'$ and the rest of the data. In each case, the model that is able to tell us things like this needs to have a notion of the underlying probability distribution, hence we say it learned to approximate the distribution.