Replacement for Linksys WRV54G?

Question: I work at a small company that has two offices, each with its own Business DSL connection to the Internet.  In order to create a LAN between the two offices, my predecessor purchased and installed two Linksys WRV54G Wireless VPN Broadband Routers to provide a hardware solution to make the computers at both locations see each other and think they are on the same LAN.
Despite keeping up with every firmware update, I still finding myself driving to one office or the other (it's almost always the office I am not at) about once or twice a week to power-cycle its router to either get the wireless part working again for somebody's laptop, or to get the Internet gateway part working again.  The VPN tunnel always seems to stay up, however.
I am looking to replace these WRV54Gs with something (perhaps multiple pieces of hardware) that can perform all the functions of the WRV54Gs, but that don't misbehave so much.  It will be easy to just pick up a wireless access point off the shelf.  It will be similarly easy to pick up a couple 8-port switches off the shelf.  The real trouble is that I can't seem to find any hardware to do the VPN part.  I want this to be completely hands-off the workstations, so it has to be a hardware solution.
What type of router can I use to work as an Internet gateway for our Business DSL connections, as well as be the endpoint of a VPN tunnel that, for lack of better terms, fools windows into thinking that the remote LAN is actually local?
Comment: Do you have a budget limit?
Comment: I'm not sure.  I haven't even considered the cost yet.  I just want to gain some direction.  After I have all of the alternatives, I can then make my decision.  Cost will be a factor, but only after functionality.
Answer: You could use pfSense it has many features:

Firewall
Network Address Translation (NAT)
Redundancy
Load Balancing
Reporting and Monitoring
RRD Graphs
The RRD graphs in pfSense maintain historical information on the following.

CPU utilization
Total throughput
Firewall states
Individual throughput for all interfaces
Packets per second rates for all interfaces
WAN interface gateway(s) ping response times
Traffic shaper queues on systems with traffic shaping enable

VPN

IPsec
PPTP
OpenVPN

Dynamic DNS
Through:

DynDNS
DHS
DyNS
easyDNS
No-IP
ODS.org
ZoneEdit

Captive Portal
DHCP Server and Relay

It has a nice, easy to use web-based configuration, just look at the screen-shots.
Best of all you can build it yourself with commodity hardware, and it's Open Source.
Comment: Pfsense rocks so much you can't even imagine how much until you test it :-)
Comment: I also recommend pfSense, so far the best firewall/router I have used on both small and medium businesses. Also easy to use and capable as mentioned above.
Comment: +1 for pfSense.  Depending on the requirements I typically recommend either pfSense or IPCop.
Comment: VPN was a confusing setup but I got it working at home on a low powered amd machine with 256 megs of ram - it has never crashed or caused problems on it's own. It's about 10,000 times better then my linksys routers which crashed all the time.
Comment: Another +1 for pfsense.  Unlike a lot of VPN devices, it let's you choose between multiple types of VPN technologies.
Answer: If you aren't ready to purchase business grade routers (I am guessing they might be too expensive based on the previous usage of the WRV54G), I'd recommend a router that runs dd-wrt.
http://www.newegg.com/Product/ProductList.aspx?Submit=ENE&DEPA=0&Order=BESTMATCH&Description=dd-wrt&x=0&y=0
dd-wrt is a custom firmware which supports a lot of great features including VPN. I use them at home with a linksys WRT54GL which currently has an uptime of 60 days. dd-wrt uses OpenVPN which supports linking two offices. This solution is a little more manual and involved, but it is cheap and has been rock steady for me.
Comment: I've been using DD-WRT at home for a few years now, it's brilliant.
Comment: I use DD-WRT myself and haven't had any problems with it all. I had more problems with my DSL line until I got them to replace my modem and Optical Network Card servicing my line.
Answer: I would highly recommend you utilize Sonicwall TZ210 appliances to replace your Linksys WRV54Gs.  The Sonicwall TZ210 has built-in Wireless N, 7 Ethernet Interfaces, as well easily support your Site-to-Site VPN configuration required between your two locations.  I have personally used these unit as well as the older TZ170 & TZ180 appliances to execute your exact same requirements.  The TZ210 also has the capability of handling both Client VPN Termination for Work@Home users, Reporting on Bandwidth Abuse, and UTM (Unified Threat Management).
Comment: +1 for Sonicwall. Excellent product.
Comment: Only complaint I've had with Sonicwall is don't try to use the VPN for remote clients unless they run Windows. Mac and Linux are poorly supported if you even get someone to attempt to help you out. I ended up having to upgrade to a higher level firmware version at the suggestion that it would work better for Linux clients but it didn't so we dropped the Sonicwall completely.
Comment: We have many users on Mac that connect to our SonicWall VPN (4060 Pro). While Soicwall does support a Windows client our Mac users are very happy (happier than their windows counterparts) with VPN Tracker by Equinox.
Comment: I would also recommend the Sonicwall.  Rock solid and great set of features for the price.
Answer: If you are willing to shell out the cash, a lot of Cisco routers can do this with a site-to-site VPN IPSEC tunnel.  I know my 2800s do.
Comment: Better still get them second hand on eBay!
Comment: Unfortunately Jon seems to be suggesting breaching the licensing terms of the IOS which runs upon them. Software licenses from Cisco are not legally transferable so you have to go through a relicensing process which often costs as much as buying the thing new :)

Please also note you cannot get hardware/software support contracts on devices bought from the 'grey' market.
Answer: If you enable web-access (on the router) maybe you could powercycle by connecting via web-browser.
Also, I believe you can install DDWRT on the WRV54G.
Answer: There are several option with different capabilities.
(In order of my preference.)

Cisco 1800 router. This is all good, just a few things to set up and you are ready to go. It is stable, but not the cheapest. (You can buy more devices instead of one, as someone suggested earlier.)
Mikrotik. Not as good as the first one, but it is easy to set up and quite stable. It is cheaper than Cisco, bit slower and not as much features.
Linksys anything. I do not recommend this. It is a bit better if you can use some OpenSource firmware, but even then it sucks. Not reliable, unstable. Other vendor like dlink smc .... are the same if not worse (they can be OK for home use, but as the load increases on the devices it will hang).
PC with some software. You can try this but in this case you have to set up and maintain everything (all software) if you are not familiar with this then you should not try. You can try some appliance like software, then it can be easier.
Comment: I think the 1800 is huge overkill for this solution though they will go forever it sounds like the OP might need a pro to set this up...
Comment: You are right, that's why suggested Mikrotik. Which is cheaper and I use it myself at some places. But having Cisco is a good win, if the OP has budget for it.
Answer: I like the Secure Computing SnapGear 300/310s (Now Owned by McAfee) for this scale of point to point VPN. You can find them online for under $300  each. They will handle your VPN and firewall needs perfectly and are easy to configure with a nice web interface. They are linux based and you have access to the IP Tables if you really want.
Also, if you are looking for a wireless access points to go with the firewall I would check out the Netgear WG104 for about $130. You could always get a combo "ProSafe" brand device from Netgear that can do the VPN and wireless but I really like the SnapGear and separate WAP a lot better. We have a dozen or so setups out in the field.
I also like this setup way better than any firewall from the SonicWall TZ Series - less restrictive licensing, less costly and much more intuitive interface.
Answer: Get some real security first off on your edge and have an inbound and outbound policy in place. For a small business with less than 10 hosts, a Cisco ASA 5505 or for cheaper and something thats EOS and coming near to EOL but great a Cisco Pix 501.
These devices can limit what is also going over your Lan2Lan VPN tunnels and also the internet when applying policies to the interfaces.
For excellent wireless reception and the dedicated device for that, A Cisco Aironet 1200 for indoor reception. You won't get anything better with a wireless AP/Root/Bridge than those Aironets. These AP also have features like SPF so wireless hosts can't talk to other wireless hosts. In addition, you can VLAN the wireless interface! Which means you can broadcast mutliple SSID with different security settings and segment your networks just like a switch. A great device and not terribly expensive if you look.
A Cisco Router would not be feasable because you are not doing heavy routing. The firewalls can do all the work since they are robust enough.
Answer: Maybe you can affort a SSG20 (or at least the SSG5 without wifi) from Juniper Networks with the Wireless option, Juniper make very good and secure products with high perfs. This would certainly be my choice having in the past worked with Juniper Netscreen products and now with SSG series.
Answer: Maybe it's just that model of router that is the issue.
I use the Linksys RV042 routers.  I can't remember the last time I had to power cycle them (6 months plus atleast).  I have 3 sites that connect back to a primary site all using RV042's.
The only time the VPN between the routers goes down is when one of the remote site's IP addresses changes.  This is because the ISP for those sites does not offer static IP's for a decent price.
Part two of this is I have Logmein installed on all the computers on the remote sites.  (there are desktops there)  So when the router's IP address changes at the remote site, the internet still works.  This means Logmein can still connect and I can still login to a deskop at the remote site, remotely.  I then from this desktop login to the router since the internal IP is still the same, and reset the VPN.  This happens maybe 2x year to me.
Also with using logmein I can remotely work on anyone's computer as long as its connected to the internet, even if the its not connected to the servers correctly or if the user is at home.
Answer: I agree that Sonicwall is a great solution, but you can still have a look at other options like Fortinet FortiGate 60B or Vyatta 514.
You may also find this question useful.
Answer: I recommend the Snapgear SG300/SG310.  They are a bit cheaper than the SonicWall units and they do IPSEC site to site very well.  They also support PPTP VPNs so you don't have to install anything special on client PCs that need to remote in (SonicWall requires you have the SonicWall VPN client).  The SG310 has more memory than the SG300 so it can run the newer 4.0 software.
That being said the SonicWall units are also very good, especially if you need an anti-virus solution.  The enforce antivirus and gateway antivirus works very good and is much less of a pain than most other corporate antivirus software.
Answer: As recomended Sonicwall has some very nice appliances out there. But they tend to be on the high side of pricing.
But staying in the low end on the price range, Linksys makes some very nice business class devices. I've used the WRV200 in a few locations and it's worked flawlessly. I ahd one at my home for a while and I only ever needed to restart it once in 6 months for an ISP change.
This gives you your wireless, also give you VPN support and VLAN support. There is also a newer modal that has gigabit support with wired connections.
Answer: I have always found that the Netgear products seem to be more stable than the Linksys. They have a small business class that may be what you are looking for: Wireless VPN Firewalls
Answer: I've used the NETGEAR WGR614L router with dd-wrt installed. Although I haven't used the VPN features of it I've found it to be much more stable then any other router running the default firmware.

Replacement for Linksys WRV54G?


Menu Dropdown do Bootstrap não funciona em site asp.net

Question: Tenho uma página index.html que o recurso do menu dropdown funciona normalmente, mas quando eu migrei para asp.net parou de funcionar.
Estou usando uma página Default.aspx que herda da masterpage.master.

    Home

        Quem Somos
        <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">

        </button>

Certificações

Alianças Estratégicas

Answer: Fala, cara.

Certifique-se de que o jQuery está sendo carregado;
Certifique-se de que o bootstrap.js está sendo carregado;
Certifique-se de que não ocorre nenhum erro de javascript que impede que o dropdown seja ativado;

Assumindo que o problema não é um dos itens acima:

Tente ativar o toggle dropdown manualmente no evento document.ready.

Comment: Olá, Fabricio.
Provavelmente você tem algum código jquery ativado no evento document.ready.
Se não tiver, coloque o trecho abaixo antes do fechamento da tag body ():
Comment: Funcionou Alan.
Muito obrigado.
Deus lhe abençoe.
Comment: Obrigado por tentar ajudar, Alan.
Eu tenho outro recurso na mesma página que funciona, mas esse recurso não funciona.
Eu gostaria de tentar a terceira opção, mas não sei como fazer.
Obrigado.
Comment: Como eu faço para testar a 3ª opção?
Obrigado.
Answer: Pelo que vi o código funciona normalmente.
http://jsfiddle.net/moykn/Lz82E/
Certifique se, além do que já foi citado pelo Alan R., de que o Jquery também esteja sendo carregado inclusive antes do próprio Bootstrap.
Comment: Moykn.
Esse link é muito útil para efetuar testes.
Obrigado.
Answer: Olá!
Tive o mesmo problema em meu layout,ao utilizar o inspector do Google chromer para verificar se tinha algum erro em meu código, fui informado da versão que estava utilizando do jquery não era compatível, que deveria usar da versão do jquery 1.9.1 em diante,mudei e o meu problema foi resolvido, espero ajudar.


Why is the moon jumping to another position when I am trying to drag the sun?

Question: Every time I click to drag the sun, the moon which was initially on the left side of the sun moves to the right side of the sun instead. I didn't put it anywhere in my CSS to put it in that position. I am not sure why it is doing that. http://whatisupson.tumblr.com/

Comment: A better question is: 'Why is the moon out at the same time as the sun?'
Comment: I'll fix that later. At the moment I am just worried about this.
Comment: In `moon.css`, is it's `left` supposed to be based of the suns position?
Comment: Yes, it is supposed to be based on the sun's position.
Comment: Well that's wrong, because each time on drag, `left` is being updated with the suns position. That means, each time the moon will be beside the sun.
Comment: @MunizaSiddiqui i would say try looking into your javascript from where you are changing the position of sun and moon. Because right now as you are moving sun same query is also affecting moon.
Comment: That's the point. My plan is to have the moon behind the sun, so it can gradually turn into the moon like I did with the sun, but that's obviously not working since it keeps on jumping to a different position.
Answer: You have this:
var x = sun.offset().left + (sun.width() / 2);
...
moon.css({
    left:x -(sun.width()/2)
});

When you add sun.width() / 2 to left and then subtract it later, you are left with left.  You may as well have put:
moon.css({
    left: sun.offset().left
});

Your moon image is 500px wide, but your sun image is only 300px wide.  The actual moon part of the image is roughly the same size as the sun image, but has extra padding, pushing the moon further to the right.
Since their top left corners are positioned in the same location, the moon appears to the right of the sun because it is wider.
Comment: Yeah I noticed that. But if I keep the size constant in all three elements (sun, dark_sun, moon) then the moon would appear too small compared to the other two.
Comment: While debugging, give your images a border.  That will help you better visualize what is happening.  http://i.stack.imgur.com/ezRwm.png
Comment: @MunizaSiddiqui - Use images that are all the same size, and use a draggable container.  It works way better:  http://jsfiddle.net/cxo7bru9/


The statistical test for the change and the statistical test for percentage change do not agree

Question:     mydata<-structure(list(Before = c(24.6, 17, 18.9, 14.6, 16.5, 20.3, 21.6,
14.1, 18.9, 21.1, 25.4, 14.4, 23.8, 20, 24.5, 25.7, 20.4, 19.4,
14.7, 17.4, 19.8, 23.3, 20.1, 17.3, 21.2, 17.5, 18.9, 20.3, 17.8
), After = c(20.4, 16.6, 20.7, 17.3, 20.4, 19.8, 22.6, 15.9,
20, 19.1, 28.4, 16.2, 26.8, 20.4, 26.2, 20.4, 19.8, 19.3, 16,
20.4, 16.6, 24.1, 24.1, 19.5, 22.4, 21.8, 18.5, 21.9, 16.6)), row.names = c(NA,
-29L), class = "data.frame")

This is paired data of about 30 individuals. I want to test if the change is significantly different from 0 but also the percentage change.
The change is 0 at time before
mydata$pourcent_evol_0<-
  ((mydata$Before-
      mydata$Before)/
     mydata$Before)*100

Below the % change at time After:
mydata$pourcent_evol_1<-
  ((mydata$After -
     mydata$After)/
  mydata$After)*100

Then I test if the percentage of change is different from 0
t.test(mydata$pourcent_evol_1,
   mydata$pourcent_evol_0, paired = T)

Paired t-test

data:  mydata$pourcent_evol_1 and mydata$pourcent_evol_0
t = 2.2347, df = 28, p-value = 0.0336
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 0.4039322 9.2861680
sample estimates:
mean of the differences
                4.84505

I also test the absolute change by
t.test(mydata$After,
       mydata$Before, paired = T)

Paired t-test

    data:  mydata$After and mydata$Before
    t = 1.7932, df = 28, p-value = 0.08375
    alternative hypothesis: true difference in means is not equal to 0
    95 percent confidence interval:
     -0.1113977  1.6769149
    sample estimates:
    mean of the differences
                  0.7827586

Sorry for my silly question, I know that my calculations for the percentage of change most likely have an effect on the difference in significance between the two tests, but I'm a little embarrassed to have differing conclusions. I was expecting to have either both tests significant or both not significant. Can someone give me a more reasonable explanation
Answer: This is because percent change and absolute change really are different questions, so there is no reason to expect that the answers would have to be the same.  This may be easier to see with a much simplified example.
Let's look at a simple case with data on just you and me.  At the beginning of our experiment I can lift 50 pounds and you can lift 100 pounds.  We both exercise and get stronger, in fact we both improve by 50%, so I can now lift 75 pounds and you can lift 150 pounds (you still lift double what I can).  So the percent change is identical, but you can lift 50 more pounds than you did before, while I only improved by 25 pounds, so the absolute differences are different even though the percentage was identical.
We can go the other way as well.  Start with 50 and 100 again, but this time we both improve by an absolute difference of 25 pounds.  I can now lift 75 pounds which is a 50% improvement, but you only improved 25% at lifting 125 pounds, so our absolute differences are the same, but the percentage improvements are different because we started at different points.
With real data it is not quite as obvious, but if you have groups starting at different places, then percent and absolute changes can be quite different.


Flutter url_launcher ignores number sign(#) when call

Question: I'm using url_launcher in my app. When I dial numbers that includes a number sign like "*123#" it ignores the number sign and dial just *123
Answer: You should use Uri.encodeComponent to encode # too
onPressed: () {
        String no = Uri.encodeComponent('*123#');
        launch('tel:$no');
      },

Comment: Cheers mate, no problem. Because it is a special character, it should be encoded
Comment: Thank you so much. It worked but I don't know why it was not working before.
Answer: You must use Uri.encodeComponent to encode # your string
onPressed: () {
        String mycode = Uri.encodeComponent('*#06#');
        launch('tel:$mycode');
      },

Because special characters need to be encoded to be able to use by your device


HAML submit form in rails link_to

Question: I have a small search form written in HAML in my rails application, here is the code:
= search_form_for @q do |f|
  .field
    = f.label :first_name_cont, "Name Contains"
    = f.text_field :first_name_cont
  = f.button :submit, "Search"

I want something like a link_to for the submit action so that it knows what controller action to call, how can I do that in HAML? Thanks a lot.
Answer: I am not a HAML guru, but form_for, and likely Ransack's search_form_for have a submit method on the block object to make a submit button. Therefore, that last line should resemble = f.submit "Search"
Comment: this would output an input type["submit"] and not an  tag however. other option would be to use jQuery and submit the form when clicked on the  tag
Answer: It's hard to tell from your question, but it looks like you're using Ransack. According to their documentation, If you are trying to send the form to a particular route, you can set the :url option in your form_for line. You don't have to modify the submit button at all.
For example:
= search_form_for @q, :url => your_controller_action_path do |f|
   ... # The rest of your code

HAML submit form in rails link_to


If $f\circ q,g\circ q$ are homotopic on $S^1$, are $f,g$ homotopic?

Question: Let $f,g:S^1\rightarrow S^1$ be continuous functions.
Define $\alpha:[0,1]\rightarrow S^1:t\mapsto (\cos 2\pi t, \sin 2\pi t)$.
If $f\circ \alpha$ and $g\circ \alpha$ are homotopic, then are $f,g$ homotopic?
How do I prove this?
Comment: Well [0,1] is contractible, so...
Comment: A homotopy between maps from a point is the same thing as a path. What can you say about paths between points in $S^1$?
Comment: IF you have two maps $f,g:X\to Y$ and either $X$ or $Y$ is contractable, then the maps are homotopic.
Comment: @Aaron provided $Y$ is path connected.
Comment: @MattS Yes.  I have a bad habit of assuming all spaces are path connected (and locally path connected and hausdorff and locally compact and...) unless I have a particular example that isn't.
Comment: Do you mean $f\circ \alpha$ and $g\circ \alpha$ are homotopic paths with respect to their end points? That would make more sense and is still true.
Answer: Notice that since $I$ is contractible and $S^1$ is connected, $f \circ \alpha, g \circ \alpha : I \to S^1$ are always going to be homotopic. A proof of this statement is included below.
However, if your statement is correct, it would follow that $f, g : S^1 \to S^1$ are always homotopic, which isn't true.

A space $X$ is contractible if the identity map $i_X : X \to X$ is nullhomotopic.
Lemma: If $X$ is contractible and $Y$ is path connected, then $f, g : X \to Y$ are homotopic.
Proof: Since $X$ is contractible, $i_X \simeq e_c$ for some $c \in X$.
So there exists a homotopy $H : X \times I \to X$ with $H(x, 0) = e_X(x) = x$ and $H(x, 1) = e_c(x) = c$.
Notice that $f \circ H$ is a homotopy between $f = f \circ i_X$ and $f \circ e_c = e_{f(c)}$. and $g \circ H$ is a homotopy between $g = g \circ i_X$ and $g \circ e_c = e_{g(c)}$.
Since $Y$ is path connected, there exists a path $\alpha : I \to Y$ with $\alpha(0) = f(c)$ and $\alpha(1) = g(c)$. This induces a homotopy between $e_{f(c)}$ and $e_{g(c)}$: Define $K : Y \times I \to Y$ by $K(s, t) = \alpha(t)$; observe that $K(s, 0) = \alpha(0) = f(c)$ and $K(s, 1) = \alpha(1) = g(c)$.
Hence we have $f \simeq e_{f(c)} \simeq e_{g(c)} \simeq g$.
Conclude that $f$ is homotopic to $g$.


Spring ws org.springframework.ws.soap.saaj.SaajSoapEnvelopeException XSD?

Question: i always get the error
HTTP Status 500 - Request processing failed; nested exception is org.springframework.ws.soap.saaj.SaajSoapEnvelopeException: Could not access envelope: Unable to create envelope from given source: ; nested exception is com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source:
when i try to run a soapRequest with two complex types like:
<xs:element name="blub">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="mainheader" type="header" />
            <xs:element name="mainbody" type="body" />
        </xs:sequence>
    </xs:complexType>
</xs:element>

I use org.springframework.oxm.jaxb.Jaxb2Marshaller as Marshaller and org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection for the xsd.
Anyone has an idea?
Answer: You might be missing the soap:Envelope:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://www.example.org/stock">
      <m:StockName>IBM</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>


A question about close votes (please read it before migrating it to meta)

Question:
Suppose, on close.stackexchange.com there are $m$ active users with sufficient reputation to cast close votes and $n$ open (not closed) questions (the number of open questions never changes - whenever a question is closed, a new one is posted, no new questions are posted otherwise and no questions are reopened). Every day, each of the active users reviews (and choses, whether to cast a close vote or not) $r$ randomly chosen distinct open questions (with uniform distribution). All close votes are cast from review. Due to a bug on close.stackexchange.com, a user can cast a close vote any time they find that question in their review queue (which means the same user can cast multiple close votes on the same question on separate days). $t$ close votes are needed to actually close a question. Close votes on an open question age away in $k$ days.
Suppose, that a question was posted, such that the probability of it receiving a close vote during any review is $p$ (all reviews are independent and identically distributed, even if done by the same user). What is the probability, that this question will ever be closed?

It is not hard to see, that under those conditions the number of close votes received on a single day is independent and identically distributed for every day, and its distribution is binomial: $Bin(m, \frac{C_{n-1}^{r-1}}{C_n^r}p)$
Thus the problem is reduced to the following one:

Suppose $\{X_i\}_{i = 1}^\infty$ are i.i.d. random variables, distributed as $Bin(m, \frac{C_{n-1}^{r-1}}{C_n^r}p)$. What is the probability that $\exists N \in \mathbb{N}$, such that $\Sigma_{i=N}^{N+k-1} X_i \geq t$?

And here I am stuck.
Answer: The probability is $1$ if $t \leq mk$ and $p > 0$, and $0$ otherwise.
If $mk < t$ then question will not ever be closed even if every user will vote to close it every day. If $p = 0$ then no close votes will ever be casted.
Otherwise let $Y_n = \sum\limits_{i=nk}^{nk + k - 1} X_i$. $Y_n$ are i.i.d., $P(Y_n < t) = a < 1$ and $P(\exists N\in \mathbb N\colon \sum_{i=N}^{N+k-1} X_i \geq t) \leq P(\exists N \in \mathbb N \colon Y_N \geq t)$.
$P(\exists N \in \mathbb N \colon Y_N \geq t) = 1 - P(\forall N \in \mathbb N\colon Y_N < t)$. For any $n$, $P(\forall N \in \mathbb N\colon Y_N < t) \leq P(Y_1 < t \wedge Y_2 < t \wedge \ldots \wedge Y_n < t) = P(Y_1 < t) \cdot \ldots \cdot P(Y_n < t) = a^n$.
As $a < 1$, $\lim_{n \to \infty} a^n = 0$, so $P(\forall N \in \mathbb N\colon Y_N < t) = 0$.


EntityFieldQuery: number of field values as condition

Question: I have a node type which has a field that can contain an unlimited amount of images.
I want to retrieve a set of entities, but only entities that contain at least one image.
So far this is my query:
$result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'reference')
    ->propertyCondition('promote', 1)
    ->propertyOrderBy('created', 'DESC')
    ->pager(12)
    ->execute();

How should I use the extra fieldCondition to indicate I only want nodes with at least 1 value for field_images?
Answer: Seems like stating the obvious but you need to count the number of values in 'field_images', then you can set the condition to check that result and make sure it is greater than 0.
There's a good overview of adding expressions and conditions with the count() function on this question.
You'll also need to perform a join between 'node' and the table that holds your field values before you make your count, something like this:
$query = db_select('node', 'n');
$query->join('field_images', 'fi', 'n.nid = fi.nid');
...rest of query

Answer: You have to use a propertyCondition for this.
A code like:
$result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'reference')
    ->propertyCondition('promote', 1)
    ->propertyCondition('field_images', 1)
    ->propertyOrderBy('created', 'DESC')
    ->pager(12)
    ->execute();

-would help. But I don't know whether it works with 'node' 'entity_type'.
If not, please comment below and/or edit this answer.
Thank you.


placing bets to maximize the difference between two random numbers

Question: Suppose you are asked to bet on the difference between two independent randomly numbers $r_1$ and $r_2$, both uniformly distributed between 0 and 1. Your bet size is $w$ is between -1 and 1. Your winning each time will be $w_i \cdot (r_1 - r_2)$.
Of course the expectation of this bet is zero. But suppose now you know the value of $r_1$ before placing your bet, what is the optimal bet size that will maximize your sharp ratio: $\frac{E[w_(r_{1}-r_{2})]}{\sqrt{\text{Var}[w\cdot(r_1-r_2)]}}$ , assuming that you can change your bet size each time, and you repeat this process many times?
Comment: This question is singularly uninteresting: since all positive bets give identical values of that ratio and all negative bets give the negatives of those values, you are asking your readers merely to choose the larger of a number and its negative.
Comment: The question states that you know $r_1$. Therefore the bet is chosen based on an expectation of $r_2$ given that $r_1$ is known. Averaging over $r_1$ is not relevant to this optimization.
Comment: do you know all $r_1$s before any bet or know $r_1$ right before your each bet and after your previous bets?
Comment: You know one $r_1$ right before you place each bet.
Comment: @whuber, I think that will maximize the expectation, but not necessarily sharpe ratio
Comment: Ah, I guess OP didn't make it clear. My understanding is that the sharpe ratio isn't taken on each bet. There is (infinitely) many rounds of betting, each earns you $x_i = w_i(r_{1i}-r_{2i})$, and you wish to maximize avg($x_i$) / std($x_i$)
Comment: The "sharp ratio" simplifies because $w$ factors out of the expectation and $|w|$ factors out of the square root of the variance.  Therefore only the *sign* of the bet, not the amount, has any effect on that ratio.
Comment: I guess I didn't clarify this, but the bet size is different each time depending on your knowledge of $r_1$, so I don't think it can be factored.
Comment: your bet size should be dependent on r1, and that's the whole idea behind this. So I am not sure what you meant by "averaging over r1 is not relevant", or "only the sign matter"
Comment: If the goal is to only maximize the expectation, then this becomes too easy, just bet 1 when r>0.5 and vice versa. The standard deviation is suppose to encourage betting small when the chance of winning is small.
Answer: Sharp ratio simplifies to
$\text{sign}(w) \sqrt{12} (r_1 - E(r_2))$
So, by way of "thinkin' about it", you just choose $w > 0$ if $r_1 > 0$ or $w < 0$ if $r_1 < 0$.
Comment: I believe you meant to use $1/2$ (which is $E(r_2)$) rather than $0$ in your criterion.


How to pronounce accidental letter notes when sight reading?

Question: When reading sheet music and playing a stringed instrument, I find it helpful to softly sing the names of the notes.
"A", "B", "C", etc. are easy, they are all once syllable.
But accidentals take two syllables to pronounce, which throws off my rhythm and is just not feasible when playing quickly.
For sharps, it's OK to to add "sh" or "eesh" at the end, so "C#" is "ceesh" and "F#" is "Fish". But I can't figure out anything for flats that works for both vowels and consonants and doesn't sound too similar to other things.
Is there a standard way of doing this sort of thing?
There's a similar question for solfege but I don't want to use solfege, it gets confusing for different scales.
Answer: The short answer is "No," there isn't a standard way to refer notes with accidentals, using letter names, and taking up only one syllable—in English. The Germans, though, are all over it, adding "es" the letter for flats and "is" for sharps. Of course, it works best when you actually pronounce the letters themselves as they're pronounced in German; if your A is a Fonzie-like "Ayyy," it's harder to distinguish "Ais" from "As" than if it's an A as in "father."
But if you're inventing a convention for your own personal habit, you can pretty much do whatever works for you. Surely you can blurt out "geesharp" or "beeflat" on all but the shortest notes. Or for that matter, I would be inclined to leave the sharps and flats unspoken and simply sing "E" for E flat, for instance, and just understand that it's flat. Especially when they're part of the key signature; if I'm singing in a key with lots of sharps and flats, it seems unnecessary to be constantly saying them. I take a similar approach myself with chord qualities: If I'm thinking through a chord progression, I'm likely to sing to myself "C, F, D, G." The D chord is minor, but I don't bother saying "D minor"; of course the ii chord is a minor triad. On the other hand, if it is in fact major (as the V of V), I'm likely to mumble "C, F, D major, G."
(Meanwhile, I do encourage you to explore the benefits of moveable-do sight-singing, which is less about absolute pitch designation and more about tonal function. Although perhaps "confusing," it serves a totally different purpose, and a useful one. If you're learning "Rudolph the Red-Nosed Reindeer," then "G A G E C A G" tells you something about the physicality of the absolute pitches in your range, but "sol la sol mi do la sol" tells you about the melody, no matter what key it's in.)
Comment: "Aes" is NOT used in German. It is called "As", to help distinguishing it from "Ais". Same goes for "Eis" and "Es". Also be careful with "B" for B flat, "H" for B natural, "His" for B sharp.
Comment: The French use "dièse" for sharp and "bémol" for flat. For example, "ré bémol majeur" is French for D flat major. The French don't name notes "ra" or "ri", and I expect no other language does, either.
Comment: Re moveable-do, thanks for the recommendation. I have trouble seeing how it could work when there's chromaticism and mode changes. Plus, I'm n00b and it's hard enough right now juggling note names, note numbers (in a scale), roman numerals, and bass and treble clefs. Maybe one day I'll do do.
Comment: @Dekkadeci Thanks, and come to think of it, I think I've heard something similar from Asian students; solfege syllables plus a modifying word. I went ahead and yanked that paragraph.
Comment: There are adjustments to movable do for accidentals, too.
Answer: Stick with your 'sh' for sharp, and use 'f' for flat. Thus 'Beef', Eef, Aieef, etc.
The other way would be to call the notes the number they are in the scale. Thus in key B♭, B♭ is 1, C is 2, D is 3, E♭ is 4, and so on. You'll still have to find an alternative for the five accidentals, then, though.
Comment: If in B♭ you call B♭ "do", then there is a [standardised way of saying accidentals](/q/28538)
Comment: Works pretty well, but my mind sees "F" when I say "Ayff" (A ♭) or "EEf" (E♭ ). And it's a bit hard to distinguish "A♭ " from "A, F". Maybe with practice saying accidentals will seem natural.
Comment: Or even eschewing the idea, and just play the appropriate notes!
Answer: Not a convention- see Andy Bonner answer- but how about "t" after A and E or "at" after the other letters.

Ate
Bat
Cat
Dat
Eet
Fat
Gat

Or of you like the note letter name, just add "t"

Ate
Beet
Ceet (seat)
Deet
Eet
Feet
Geet (hard g)

Risk of this is that if you talk like me your T could sound like D and Ceet gets confused with Cee-Dee but if it's in your head you should be able to enunciate the hard t. (At least I do more than when I talk.)
Answer: My first instinct when reading the question, given the shape of the flat sign, was to add a "b" sound, and (for no consciously-determinable reason other than it sounded right) making it "ub" where necessary. This would give "ab", "bub", "cub", "dub", "eb", "fub" and "gub".
Comment: b also sounds flatter to me than t, which is a sharp sound
Answer: I'm imagining your sight reading scenario is one with relatively long note values and slow to moderate tempo. Otherwise, if you have fast tempo sixteenth notes, how could you say the letter even without sharps/flats?
If that is the case, long values and slower tempi, it seems to me a line like...

...could be handled like this...

If the line was more florid, some thing similar like...

...could work, but maybe unvoiced so pitches don't become a mess.
When I play piano and want to speak the notes for various reasons, I do it like this.
Comment: And then there's the phenomenon of calling out chord names while singing a song. "G-terdayyy. F sharp, all my B-bles seemed so E awayyyy / C, now it D as though they're G to stay..." Again, sometimes you just gotta leave some details assumed, or pause the flow while you blurt out "F sharp minor 7 over C sharp with an added G shaaaarp!"
Comment: @AndyBonner, and if you are actually calling out chords, because someone doesn't know them/have a chart, you need to call them a beat early. A bit different then singing to yourself only.
Comment: I'm sightreading basslines from a bass lesson book. There are often a lot of accidentals because of walking bass lines or just for the finger exercise.
You're right that saying names out loud won't work for fast-tempo sixteenth notes!

Nice touch, putting the voice part into music notation


ASP - Imprimindo JSON sem ultima virgula e com aspas dupla

Question: Estou precisando fazer uma consulta no banco de dados, e retorna um JSON.
Tentei usar JSON for ASP do Google, mas deu uns erros, então resolvi fazer manualmente:

<%
medico = replace(request("medico"),"'","")
crm = replace(request("crm"),"'","")

sql = "SELECT nome_pro, crm FROM medicos WHERE nome LIKE UPPER('%" & medico & "%') "
set rs = server.createobject("adodb.recordset")
rs.cursorlocation = 3
rs.open sql,conexao

response.write("[")
If Not RS.EOF Then
Do
    response.write("{")
    for each x in rs.fields

        response.write("'" & x.name & "'")
        response.write(":")
        response.write("'" & x.value & "'")
        response.write(",")

    next
    response.write("}")
    response.write(",")
    RS.MoveNext()

Loop Until RS.EOF
End If
response.write("]")
%>

O problema que estou tendo, é que quando ele imprime o JSON, sai a ultima virgula, assim:
[{'NOME_PRO':'ALCINDO','CRM':'000000',},{'NOME_PRO':'PEDRO ','CRM':'000000',},{'NOME_PRO':'PEDRO','CRM':'111111',},]
Nunca usei ASP, estou usando pela primeiravez pra gerar esse JSON, e queria saber se tem algum metodo de não imprimir essa ultima virgula.
E tambem queria saber se tem como fazer com que o:
response.write("'" & x.name & "'")

Imprima aspas duplas em vez de imprimir unica.
Answer: Ao invés de escrever diretamente, armazene o resultado em uma variável, e no final do processo, remova a virgula no final e depois escreva o resultado.
Veja:

<%
medico = replace(request("medico"),"'","")
crm = replace(request("crm"),"'","")

sql = "SELECT nome_pro, crm FROM medicos WHERE nome LIKE UPPER('%" & medico & "%') "
set rs = server.createobject("adodb.recordset")
rs.cursorlocation = 3
rs.open sql,conexao

Dim resposta

resposta = "["

If Not RS.EOF Then
Do
    resposta = resposta & "{"

    for each x in rs.fields

        resposta = resposta & "'" & x.name & "'"
        resposta = resposta & ":"
        resposta = resposta & "'" & x.value & "'"
        resposta = resposta & ","

    next

    resposta = resposta & "}"
    resposta = resposta & ","

    RS.MoveNext()

Loop Until RS.EOF
End If

'Aqui removemos a ultima virgula no final da string.'
resposta = Left(resposta, (len(resposta)-1))

resposta = resposta & "]"

response.write resposta
%>

Answer: Vou mostrar somente o techo do loop, pois é somente nesse trecho que modifiquei:
c2 = 0;
Do
    If c2 > 0 Then
        response.write(",")
    End If
    response.write("{")
    c = 0;
    for each x in rs.fields
        If c > 0 Then
            response.write(",")
        End If
        response.write("'" & x.name & "'")
        response.write(":")
        response.write("'" & x.value & "'")
        c = 1
    next
    response.write("}")
    c2 = 1;
    RS.MoveNext()
Loop Until RS.EOF

A lógica é adicionar a vírgula antes e permitir somente quando o contador for maior que 0, ou seja, quando o laço de repetição estiver rodando o segundo registro em diante.
Note que existe o contador c2 e c.
O c2 é para o loop primário.
Dentro do loop primário há outro loop, onde usei uma variável chamada c.
O importante é iniciar os contadores com valor 0 antes de iniciar cada loop, não dentro do loop.
Também cuidado com caracteres reservados do json. É mais seguro escapar as strings caso contenham caracteres reservados como double quote, por exemplo.
Replace(str, ""","\"")

Exemplo prático
response.write("'" & Replace(x.name, ""","\"") & "'")


Transitivity of Wilcoxon signed-rank test

Question: I have performed Wilcoxon signed-rank tests for variables $X$, $Y$, and $Z$, where it appears that (speaking informally) $X < Y < Z$. Indeed, the p-value for the one-sided Wilcoxon signed-rank test for $X$ vs $Y$ is $p_{X<Y} = 8 \cdot 10^{-3}$, and that for $Y$ and $Z$ is $p_{Y<Z} = 4 \cdot 10^{-6}$. Yet I have $p_{X<Z} = 3 \cdot 10^{-4}$.
Clearly $p_{X < Z} \nless \min(p_{X<Y},p_{Y<Z})$, but what sort of relationship is guaranteed to hold? I would think that $p_{X < Z} \le \max(p_{X<Y},p_{Y<Z})$. Is this in fact the case? And is there something stronger that one can say?
Comment: You do have transitivity.
Comment: You're doing signed rank tests on three sets of pair-differences? Is this with complete data (no missing values anywhere)?
Comment: @Glen_b - yes and yes!
Comment: I'm not even sure you necessarily have transitivity in the population version of the one-sample Hodges-Lehmann statistic (median Walsh-average) on pair-differences across three populations. If you don't then p-values might end up anywhere.
Comment: ... at least in large samples, by the look of it. +1
Comment: Actually, I'm no longer convinced about transitivity, but the rest holds
Answer: Update: I'm no longer convinced that the ordering is transitive, but it is still described by the pseudomedians.  It's just that when you don't have a location shift the pseudomedians need not be additive: you don't necessarily have $m_{XZ}=m_X-m_Z$, so $m_{XZ}=m_{ZY}-m_{YZ}$. I think everything else holds -- because most of the results below are negative rather than positive.
We can think in terms of the estimated pseudo-medians and their standard errors.
If the distributions are continuous and differ only by location shift, not in shape or scale, then the large-sample distributions of the pseudo-medians will be $N(m_i,\sigma^2/n)$ for $m_X$, $m_Y$ and $m_Z$ pseudo-medians and the same $\sigma^2$.  Since $\hat m_Z-\hat m_X=(\hat m_Z-\hat m_Y)+(\hat m_Y-\hat m_X)$, the $X:Z$ $p$-value will be smaller than the minimum of the other two if the other two are both less than 0.5 (so that the pseudomedians are ordered the right way).
When the distributions differ in scale or shape it's more complicated, because the $\sigma^2$s will differ.  For example, if $Y$ is less variable than $Z$ and $X$ it's a lot easier to get the $p$-values not to be ordered the way you want.  For example, consider
r<-replicate(1000,{x<-rnorm(500)
y<-rnorm(500,0.15,s=0.1)
z<-rnorm(500,0.4)

c(wilcox.test(x,y,paired=TRUE)$p.value,
wilcox.test(y,z,paired=TRUE)$p.value,
wilcox.test(x,z,paired=TRUE)$p.value)})

table(r[3,]<pmin(r[1,],r[2,]))
table(r[3,]<pmax(r[1,],r[2,]))

You get quite a few examples where $p_{XY}>p_{XZ}>p_{YZ}$ even with all the $p$-values less than 0.5.
However, if $\hat m_X\sim N(m_X, \sigma^2_X/n)$ in large samples (and similarly for $Y$ and $Z$), we know that the variance of $m_X-m_Y$ is $(\sigma^2_X+\sigma^2_Y)/n$ (and similarly).
Now, $\sigma^2_X+\sigma^2_Z$ is not necessarily less than  $\max\{\sigma^2_X+\sigma^2_Y, \sigma^2_Y+\sigma^2_Z\}$, so we might not expect even to have $p_{XZ}<\max \{ p_{XY}, p_{YZ}\}$, but it's going to be a pain to prove.
Simulation to the rescue:
> set.seed(2023-9-18)
> r<-replicate(10000,{x<-rnorm(500)
+ y<-rnorm(500,0.1,s=0.1)
+ z<-rnorm(500,0.2)
+
+ c(wilcox.test(x,y,paired=TRUE, alternative="less")$p.value,
+ wilcox.test(y,z,paired=TRUE, alternative="less")$p.value,
+ wilcox.test(x,z,paired=TRUE, alternative="less")$p.value)})
> which(!(r[3,]<pmax(r[1,],r[2,])))
[1] 1420 1745 2226 3959 5440 6158 9463 9844

Now:
> r[,1420]
[1] 0.4756392 0.5053687 0.6037722

Nope: one is bigger than 0.5
> r[,1745]
[1] 0.6671444 0.6444861 0.6835040

Nope: they are all bigger than 0.5
> r[,2226]
[1] 0.2439124 0.2258590 0.2484954

Success: it is possible to have $p_{XZ}<\max \{ p_{XY}, p_{YZ}\}$.  The constraint does seem to be almost true, but not quite.
I think any sharp results will have to be on the Normal-approximation scale rather than on the $p$-value scale.
Answer: Does this meet the conditions of a counterexample? Or have I misunderstood something somewhere?
x <- c(3.51, 3.75, 3.914, 4.118, 4.77, 6.31, 6.53, 9.59, 15.117, 14.301)
y <- c(3.29, 3.32, 3.413, 3.66, 3.78, 10.143, 10.22, 10.31, 11.88, 12.4)
z <- c(0.01, 0.55, 5.22, 6.11, 7.115, 7.94, 8.48, 9.51, 10.503, 11.604)

wilcox.test(x,y,"less",paired=TRUE) # p-value = 0.6523
wilcox.test(y,z,"less",paired=TRUE) # p-value = 0.7217
wilcox.test(x,z,"less",paired=TRUE) # p-value = 0.7842


get list on bases of input parameter

Question: I have the below method in Java:
public <T> List<?> getList(String str, Class<T> clazz ){
    List<T> lst = new ArrayList<>();
    String[] arr = str.split(",");
    for(String s : arr){
        lst.add(clazz.cast(s));
    }
    return lst;
}

I want the output of this method like this:
List<Integer> lst = getList("1,2",Integer.class)

List<String> lst = getList("ab,cfv",String.class)
...
...
etc

But the problem here is when I am passing "1,2" and Integer.class, I am getting classCastException at "clazz.cast(s)"
What I am doing wrong here?
Comment: You are not guaranteed that `String s` can be cast to type`T`. How would `List sockets  = getList("asdf", Socket.class);` work?
Comment: Thanks .. for string, it is working
Comment: Not surprising. You can cast a `String` to a `String` with no problem.
Answer: Your problem is related to the fact that you try to cast a String into an Integer which cannot work since String is not a sub class of Integer, you should provide a Function that will convert your String into the target type instead as next:
public <T> List<T> getList(String str, Function<String, T> parser){
    return Arrays.stream(str.split(",")).map(parser).collect(Collectors.toList());
}

Example:
List<Integer> lst = getList("1,2", Integer::valueOf);
System.out.println(lst);

Output:
[1, 2]

The previous code works with Java 8 and above, for previous versions, the logic is the same, you simply need to use FluentIterable from Google Guava to replace the Stream and use com.google.common.base.Function instead of java.util.function.Function the result is the following:
public <T> List<T> getList(String str, Function<String, T> parser){
    return FluentIterable.from(Arrays.asList(str.split(","))).transform(parser).toList();
}

Example:
List<Integer> lst = getList(
    "1,2",
    new Function<String, Integer>() {
        public Integer apply(final String input) {
            return Integer.valueOf(input);
        }
    }
);

Output:
[1, 2]

Comment: Thank you very much
Answer: Integer and string are not in the same hierarchy. They both derive from object but branch different ways. You could do as the other answer says or change the parameter String to Object.
      Object
     /      \
    /        \
String     Integer

Answer: Another way is to create ICaster interface:
public interface ICaster<T> {
    T cast(String a);
}

and its implementations e.g:
public class IntegerCaster implements ICaster<Integer> {
    @Override
    public Integer cast(String a) {
        return Integer.parseInt(a);
    }
}

Then instead of Class<T> clazz parameter in getList method, you should use ICaster<T> caster.
Here is new getList method:
public static <T> List<?> getList(String str, ICaster<T> caster){

    List<T> lst = new ArrayList<>();

    String[] arr = str.split(",");
    for(String s : arr){
        lst.add(caster.cast(s));
    }

    return lst;
}

And usage example:
List<Integer> lst = (List<Integer>) getList("1,2",new IntegerCaster());

The output should be: [1, 2]

get list on bases of input parameter


The model item passed into the ViewDataDictionary EF but this ViewDataDictionary instance requires 'System.Collections.Generic.List

Question: I want to connect my ASP.NET MVC web app with the database using Entity Framework Core (v5.17).
But when trying to make it work finally it show me this message :

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet1[test_deploiement.Models.PublisherModel]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List1[test_deploiement.Models.PublisherModel]'.

Model class:
public class PublisherModel
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }

    public PublisherModel(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

Controller
public class HomeController : Controller
{
    private readonly ApplicationDbContext _db;
    public IEnumerable<PublisherModel> Publishers { get; set; }

    public HomeController(ApplicationDbContext db)
    {
        _db = db;
    }

    public IActionResult adminpublishermanagement()
    {
        //List<PublisherModel> publisher = new List<PublisherModel>();
        //publisher.Add(new PublisherModel(101, " Lafond"));
        //publisher.Add(new PublisherModel(102, " Casio"));
        //publisher.Add(new PublisherModel(103, "J'aime lire"));
        //publisher.Add(new PublisherModel(104, "Time ofpost"));
        //publisher.Add(new PublisherModel(105, "Le quotidien"));
        Publishers = _db.Publisher_master_tbl;
        return View(Publishers);
    }
}

View

@foreach (var Publishers in Model)
{

      @Html.DisplayFor(modelItem => Publishers.Id)
      @Html.DisplayFor(modelItem => Publishers.Name)

}

I tried to look if the name of my classes were disfunctional but I'm not sure of it.
Comment: You should look at the error, "requires a model item of type 'System.Collections.Generic.List' which says it requires a `System.Collections.Generic.List` type. As john said, we can use the Tolist method.
Answer: You should call .ToList() on the DbSet before passing it to your view:
Publishers = _db.Publisher_master_tbl.ToList();

Comment: That it, as simple as that, Thank you very much John.


Verificação e criação de pastas em python

Question: Olá,
Estou criando um código que deve verificar se uma pasta existe, se ela não existir o código deve criá-la e então prosseguir, caso contrário, apenas segue com o fluxo.
Já tentei com If e While porém não obtive sucesso. Na maioria das vezes ele cria a pasta que eu desejo porém me retorna o erro "Não foi possível criar uma pasta já existente". Para que isto ocorra deve haver um loop que não estou conseguindo identificar, podem me ajudar?
Segue as duas formas que tentei abaixo:
MODO 1:
if username and password != None:

    while os.path.exists('C:\ Backup') == False:

        makedirs("C:\ Backup\ ")

        if os.path.exists('C:\ Backup') == True:
            break

else:
    print "nao foi possivel logar"

            #for ip in radius:

            #gravar = open(ip+".txt", "w")
            #gravar.write("Configuração")
            #gravar.close()

MODO 2:
if username and password != None:

    if pass os.path.exists('C:\ Backup') == False:

        makedirs("C:\ Backup\ ")

        else:

            for ip in radius:

            gravar = open(ip+".txt", "w")
            gravar.write("Configuração")
            gravar.close()

else:
    print "nao foi possivel logar"

PS: Talvez seja algo simples que não consegui identificar, não tenho muita experiência com programação mas estou tentando melhorar. So, i'm sorry.
Obrigado!
Answer: Faça assim:
import os.path

# nao tenho bem a certeza se e isto que quer, nao sera: if username == 'USERNAME CORRETO' and password == 'PASSWORD CORRETA': ?
if username != None and password != None:
    pasta = 'C:\Backup'
    if os.path.isdir(pasta): # vemos de este diretorio ja existe
        print ('Ja existe uma pasta com esse nome!')
    else:
        os.mkdir(pasta) # aqui criamos a pasta caso nao exista
        print ('Pasta criada com sucesso!')

    # prosseguir com o codigo aqui, nesta linha onde esta o cardinal (hash)

else:
    print 'nao foi possivel logar'

Comment: Obrigado Miguel, me ajudou muito!
Comment: De nada @CristhianMiguel. Ainda bem que resolveu


Can't use chrome.runtime.getPackageDirectoryEntry in service work with the manifest v3 Chrome Extension standard

Question: In manifest v2, I've used chrome.runtime.getPackageDirectoryEntry in the background script to list all the files within a subfolder that came with the extension to realize a specific design feature.
Now that Google is forcing me to  migrate my extension from manifest v2 standard to manifest v3, I tried to do the same feature using the chrome.runtime.getPackageDirectoryEntry method but chrome would simply report this error:
<code>Uncaught TypeError: chrome.runtime.getPackageDirectoryEntry is not a function
</code>
Can anyone help with this please?
or provide an alternative method for me to list all the filenames in a specified subfolder that would be shipped within the extension?
Comment: I googled and came across this https://stackoverflow.com/questions/66066405/chrome-runtime-missing-properties-in-manifest-v3 which linked to this https://stackoverflow.com/questions/65975659/how-do-i-get-access-to-all-the-files-in-the-extension-in-chrome-extension-manife/65976345#65976345 all here on stackoverflow
Comment: you had me at really sucks :p
Answer: After some trial and error, I've found a workaround!
For those having the same problem, one can simply choose to invoke the chrome.runtime.getPackageDirectoryEntry method in a js script that is added onto the pupup html of the chrome extension.


Volume of n-dimensional convex hull

Question: I have 2 algorithms for a problem. A solution to the problem is a set of n-dimensional vectors of 0/1's. A given solution covers any point inside the convex hull of the n-dimensional solution vectors. I want to find out, which algorithm covers a larger area. For instance, assume in the 4d space, algorithm 1 gives the solution:
$$\langle 1,0,0,1 \rangle,\langle 0,1,0,1 \rangle,\langle 0,0,1,0 \rangle$$
while algorithm 2 gives,
$$\langle 1,0,1,1 \rangle,\langle 0,1,0,1 \rangle,\langle 1,1,0,0 \rangle,\langle 1,0,1,1 \rangle$$
The question is that which algorithm covers a larger area? And by how much?
Edit:
Given a set of n-dimensional vectors $\mathbf v_1,\mathbf v_2,\dots,\mathbf v_k$ as the solution, the solution covers any point,
$$\alpha_1 \mathbf v_1+\alpha_2 \mathbf v_2+\dots+\alpha_k \mathbf v_k$$
satisfying the condition $\alpha_1+\dots+\alpha_k=1$. I just don't know if I should use the term "area" or "volume" for the set of points that are covered by the solution.
Edit 2:
The problem above actually is related to a real problem in computer networks. Assume in a computer network, because of some technical issues, we can enable only some of the users at any time. In the above example, for instance, $\langle 0,1,0,1 \rangle$ means users 2 and 4 can be enabled while users 1 and 3 must be disabled. Enabling a user means the user can transmit at rate 1 while disabling means rate 0 (generally the $i$th cell in the vector shows the rate of user $i$). In addition, we can use any of the vectors for a portion of time. This makes a convex hull of the given vectors. If a point is inside the convex hull, it means that the network can support the rates requested by the point (by choosing appropriate portion of time for each vector). Otherwise, the network cannot support the requested rate.
Comment: What do you mean by area?
Comment: The convex hull of the first three points is two-dimensional, while that of the second four points is three-dimensional. Both of them have zero four-dimensional volume. You'll need at least five points to have nonzero volume in four-dimensional space.
Comment: Your update makes it an interesting and rather open-ended problem. I think volume, area, etc. may be the wrong tools for the job -- for example, adding the vector $\langle0,0,0,0\rangle$ to both data sets will probably increase these measures, but that's clearly not useful in terms of network throughput! Unfortunately I can't think of any alternatives to suggest off the top of my head.
Comment: @copper.hat: see my edit.
Comment: I don't know what it means for an algorithm to cover an area (or a volume, or anything else). How does an algorithm cover something?
Comment: @RahulNarain: I added a brief description about why one algorithm gives 3 vectors while the other gives 4 vectors as the output. It is actually somewhat technical and I cannot describe more details. But this is the issue that I have to deal with. I am looking for a fair/reasonable measure to compare the algorithms. I need to add that 3 and 4 are just special cases. In general, we can have more vectors.
Comment: @RahulNarain: As you mentioned volume/area is a wrong tool. Thanks for your comments that made the issue clear for me too. Just to complete your comment, assume an algorithm gives only one vector $⟨1,1,1,1⟩$. That's the best solution but it's volume/area is absolutely zero.
Answer: Here's an idea related to the concept of Pareto efficiency that should work for your application. To support a requested rate $\mathbf x$, you don't really need $\mathbf x = \sum \alpha_i\mathbf v_i$ exactly for some $\alpha_i$; it is enough to have $\mathbf x \le \sum \alpha_i\mathbf v_i$ where the comparison is taken componentwise. That is, every component of $\mathbf x$ is at most the corresponding element of $\sum \alpha_i\mathbf v_i$; every user gets at least as much bandwidth as they asked for. So instead of the convex hull, you should look at the volume of the set
$$\left\{\mathbf x \in [0,1]^n:\mathbf x \le \sum_{i=1}^k \alpha_i\mathbf v_i\ \text{for some $\alpha_i$}\right\}.$$
I believe, though I haven't proved, that this is nonzero as long as there is no component for which all $\mathbf v_i$ are zero, and equals $1$ if and only if one of the $\mathbf v_i$ equals $\langle1,1,\ldots,1\rangle$. I'm not sure how to efficiently compute this, however; if you think this would be the right metric for you to use, you may want to ask a new question about how to compute it.
Comment: Thanks Rahul, that's a great idea. I'd post another question regarding the computation of the above problem.
Comment: http://math.stackexchange.com/questions/177488/computing-the-volume-of-a-set-efficienly

Volume of n-dimensional convex hull


Comando não encontrado bash

Question: Estou encontrado o seguinte erro ao executar esse script:

linha 7: [1: comando não encontrado

<code>#!/bin/bash

#$ for counter in $(seq 1 255); do curl -X POST -H 'Content-Type: application/json' http://127.0.0.1:5000/api/echo-json -d '[{"id": "123", "name": "oi"}]'; done
for counter in $(seq 1 600)
do
    if ["$counter" == 2]; then
        echo oi
        curl -X POST -H 'Content-Type: application/json' http://127.0.0.1:5000/api/echo-json -d '[{"id": "123", "name": '"$counter"'}]'
    fi
    curl -X POST -H 'Content-Type: application/json' http://127.0.0.1:5000/api/echo-json -d '[{"id": "123", "name":'"$counter"'}]'

sleep 1
done
</code>
Comment: 1) `sudo apt-get update` 2) `sudo apt-get install curl`
Comment: Eu ja tenho instalado, acho que o problema esta no if, pois o echo oi não ta aparecendo tbm
Comment: oi não teria que estar entre aspas?
Comment: botei e não adiantou
Answer: Tudo certo?!
Tente executar o "if" exatamente da seguinte forma:
<code>   if [ $counter == '2' ]; then
    echo "oi"
   fi
</code>
Fiz um teste daqui e funcionou. Segue:

Espero ter ajudado. Abraços!

Comando não encontrado bash


Devo criar um container para cada site/app ou posso colocar todos em um mesmo?

Question: Estou começando a estudar o Docker, tenho brincado um pouco num servidor VPS que eu tenho, mas ainda persistem alguma duvidas.
Já entendi que é uma boa prática separar em containers o banco de dados e o sistema em si, mas devo criar um container para cada site que eu quiser hospedar ou posso simplesmente criar um container com apache e PHP e rodar vários sites lá dentro, mas fazendo o link com o container mysql?
Sei que a duvida pode ser meio básica, mas é que esse conceito não ficou muito claro
Comment: Pode das 2 formas. O que determina isso é a própria razão de você usar ou não um container. Você quem escolhe o que separar e o que não, de acordo com suas necessidades. Antes de mais nada, você realmente precisa de um container? Por outro lado, se é só exercício, faça versão separada e teste, e faça versão sem separar e teste. Assim você passa a saber fazer dos 2 (ou mais) jeitos. Da forma como está a pergunta, é uma questão de opinião, mas talvez com um clique no [edit] pondo mais detalhes da necessidade real (ou hipotética, no caso) talvez fique possível alguma resposta objetiva.
Answer: Se você estiver pensando em boas práticas, sim, cada site em um container.
Isso para que você se beneficie de fato do isolamento, e garanta assim que um não impacte o outro, além de conseguir monitorar e isolar o consumo de recursos individualmente, inclusive te resguardando caso haja um eventual downtime.
Answer: Recomendo essa criação apartada, pois também existe a possibilidade de você conseguir reaproveitar algum container já criado, para subir apenas um site específico você pode trabalhar com o docker-composer e assim isolar os sites em diversos composers.


Let $H$ be a subgroup of a group $G$ and suppose that $g_1,g_2 ∈ G$. Prove that the following conditions are equivalent:

Question: Let $H$ be a subgroup of a group $G$ and suppose that $g_1,g_2 ∈ G$. Prove that the following conditions are equivalent:
(a) $g_1H = g_2H$,
(b) $Hg_1^{-1}=Hg_2^{-1}$,
(c) $g_1H \subset g_2H$,
(d) $g_2 \in g_1H$,
(e) $g_1^{-1}g_2 \in H$.
I'm beyond confused with this problem, all I know is that to prove the conditions are equivalent, I need to show that (a) implies (b), (b) implies (c), (c) implies (d), (d) implies (e), and (e) implies (a).

I have now gotten answers for (a) implying (e) and (e) implying (d). I'm overthinking all of this and am still confused about (d) implying (c) and (c) implying (b). When it comes to (b) implying (a), I thought I was getting somewhere but it doesn't seem to be working.
Comment: Have you started with anything? What have you tried to get from (a) to (b)?
Answer: I'll get you started, maybe you're having trouble with the order of the clauses, but you should take the effort to do the rest yourself, as this is a basic question:
Assume $g_1H = g_2H$. Then $g_1^{-1}g_2H = g_1^{-1}g_1H = H$ so $g_1^{-1}g_2 \in H$. So (a) implies (e).
Assume (e). Then there is $h \in H$ such that $g_1^{-1}g_2 = h$. Thus $g_2 = g_1h\in g_1H$. So (e) implies (d).
Comment: it's definitely the order of the clauses, because this seems so much simpler to me when you go in this order
Comment: @Claire I suspected so, as going from a to b is weird without e :)
Comment: ok im still lost when it comes to finding (d) implies (c) and (c) implies (b) so far. i know how to find (b) implies (a) though @Mariah
Comment: @Claire you should make an equivalence between (e) and (a). Can you see that if you assume that $g_1^{-1}g_2 \in H$ then also $g_2^{-1}g_1 \in H$ as well? Many of the conditions above are symmetric, and will help you proving (d) implies (c) and (c) implies (b) for instance.
Comment: okay yes i do see how we can assume that


Is it correct to say that ($\color{red}{(} \limsup |W_k|/k\color{red}{)} \le 1) \supseteq \limsup \color{red}{(}|W_k|/k \le 1\color{red}{)}$?

Question:
Let $W_0, W_1, W_2, \dots$ be random variables on a probability space
  $(\Omega, \mathscr{F}, \mathbb{P})$ where
$$\sum_{k=0}^{\infty}P(|W_k|>k) <\infty$$
Prove that $$\limsup \frac{|W_k|}{k} \le 1 \ \text{a.s.} $$

I initially thought the conclusion meant $(**)$ when it really means $(*)$:
$$P(\color{red}{(} \limsup |W_k|/k\color{red}{)} \le 1) = 1 \ \text{(*)}$$
$$P(\limsup \color{red}{(}|W_k|/k \le 1\color{red}{)}) = 1 \ \text{(**)}$$

What I tried:
By the first Borel-Cantelli Lemma, we have $P(\limsup (|W_k| > k)) = 0$
$\to P(\limsup (|W_k|/k > 1)) = 0$
$\to P(\liminf (|W_k|/k > 1)) = 0$
$\to P([\liminf (|W_k|/k > 1)]^C) = 1$
$\to P(\limsup \color{red}{(}|W_k|/k \le 1\color{red}{)}) = 1$
$\to P(\color{red}{(} \limsup |W_k|/k\color{red}{)} \le 1) = 1$ QED assuming $(**)$ implies $(*)$.

Is it really the case that $(**)$ implies $(*)$? Here is why I think such:
$\forall \omega \in \Omega, \omega \in (\limsup \color{red}{(}|W_k|/k \le 1\color{red}{)})$
Then $\forall m \ge 1, \exists n \ge m$ s.t.
$\omega \in (\frac{|W_n(\omega)|}{n} \le 1)$
$\to \omega \in (\limsup \frac{|W_n(\omega)|}{n} \le \limsup 1 = 1)$
Now if $(\color{red}{(} \limsup |W_k|/k\color{red}{)} \le 1) \supseteq \limsup \color{red}{(}|W_k|/k \le 1\color{red}{)}$, then it follows by monotonicity that
$(**)$ implies $(*)$ QED.

However $(*)$ does not imply $(**)$ because it does not hold that $(\color{red}{(} \limsup |W_k|/k\color{red}{)} \le 1) \subseteq \limsup \color{red}{(}|W_k|/k \le 1\color{red}{)}$. Counterexample given in comments below. I guess the intuitive explanation is that
$\limsup \frac{|W_n(\omega)|}{n} \le \limsup 1$
--/--> $\frac{|W_n(\omega)|}{n} \le 1$
for similar reasons that
$x_n \le y_n \to \lim x_n \le \lim y_n$, if those limits exist (1)
but
$\lim x_n \le \lim y_n$ --/--> $x_n \le y_n$ (2), which makes sense:
(1) has an infinite number of statements which imply 3 statements (limsup, liminf, limsup=liminf)
(2) has 3 statements that claims to imply an infinite number of statements
Is that right?

Edit based on what Daniel Fischer said:
To prove $$\liminf \{\frac{W_k(\omega)}{k} \le 1\} \subseteq \{\limsup \frac{W_k(\omega)}{k} \le 1\}:$$
Suppose $$\omega \in \liminf \{\frac{W_k(\omega)}{k} \le 1\}$$
Then $\exists m \ge 1$ s.t. $\forall k \ge m$,
$$\omega \in \{\frac{|W_k(\omega)|}{k} \le 1\}$$
Since $\frac{|W_k(\omega)|}{k} \le 1 \to \limsup \frac{|W_k(\omega)|}{k} \le \limsup 1 = 1$, we have
$$\to \omega \in \{\limsup \frac{|W_k(\omega)|}{k} \le 1\}$$
Comment: "I initially thought the conclusion meant (∗) when it really means (∗∗)" The conclusion definitely means (∗), **obviously**. For the nth time I suggest to stop asking questions which puts you completely out of your depth (which is basically also the advice you received on meta). But you know better, yes? So you will continue to try to take advantage of the vulnerabilities of the mse system, I guess.
Comment: $(**)$ implies $(*)$ but not the reverse. Counter-example: $W_k/k$ is constant and converging to $1$ from above. Then $(*)$ holds but $(**)$ does not.
Comment: @FardadPouran No, this is not a characterization of $\limsup a_n\leqslant1$ (consider $a_n=1+1/n$, say).
Comment: Thanks for your notice. I was wrong.
Comment: @BCLC For example $W_k/k=1+1/k$.
Comment: @A.S. it's gonna be complicated ! $a.s$ is different from A.S. !!
Comment: Are my eyes bad or the inequality looks exactly the same to me?
Comment: What does $\limsup$ of a numerical sequence mean ?
$$\inf_N\left(\sup_{n\geq N}a_n\right)=\limsup a_n \leq1 \Longleftrightarrow \forall k\; \exists N\;\::\:\sup_{n\geq N} a_n\leq1-1/k $$
$$\Longleftrightarrow \forall k\; \exists N\;\forall n\geq N\::\: a_n\leq1-1/k$$
Comment: FIRST OF ALL,  "$a.s$" doesn't mean anything in the convergence of that series !
Comment: @A.S. Thanks! How do you know $(**)$ implies $(*)$?
Comment: @A.S. What do you mean by constant and converging to 1 from above? $W_k/k = 1$ if it is constant and converges to 1 right?
Comment: @A.S. Oh constant in terms of $\omega$. Thanks. I'll try it out later
Comment: @Did Dr. MV, kjetil b halvorsen, Cameron Williams, avid19, I edited my question
Comment: @Nameless I used colours?
Answer: Let's try to get things straight. We have two conditions,
\begin{align}
P\left(\left\{\omega \in \Omega : \limsup_{k\to\infty} \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1\right\}\right) &= 1,\text{ and} \tag{$\ast$}\\
P\left(\limsup_{k\to\infty} \left\{\omega\in \Omega : \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1 \right\}\right) &= 1. \tag{$\ast\ast$}
\end{align}
The question is whether one condition implies the other. An inclusion between the sets $A := \left\{\omega \in \Omega : \limsup_{k\to\infty} \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1\right\}$ and $B := \limsup_{k\to\infty} \left\{\omega\in \Omega : \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1 \right\}$ would give us such an implication.
However, in general we have neither $A \subset B$ nor $B \subset A$. We can use the verbal description of the limes superior of sets to describe $B$ as
$$B = \left\{\omega \in \Omega : \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1 \text{ for infinitely many } k \right\}.$$
This implies $\liminf\limits_{k\to \infty} \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1$ for all $\omega \in B$, but it doesn't say anything about $\limsup\limits_{k\to \infty} \frac{\lvert W_k(\omega)\rvert}{k}$. We could for example have $W_k \equiv 0$ for odd $k$, and $W_k \equiv 5k$ for even $k$. Then we have $B = \Omega$ and $A = \varnothing$, since for this example $\limsup\limits_{k\to \infty} \frac{\lvert W_k(\omega)\rvert}{k} = 5$ for all $\omega$.
On the other hand, we could have $W_k \equiv k(1+2^{-k})$ for all $k$, then we have $A = \Omega$ and $B = \varnothing$, since $\frac{\lvert w_k(\omega)\rvert}{k} \to 1$ uniformly on $\Omega$, but $\frac{\lvert W_k(\omega)\rvert}{k} = 1 + 2^{-k} > 1$ for all $k$ and $\omega$.
Thus, we have no implication whatsoever between the conditions $(\ast)$ and $(\ast\ast)$.
But the Borel-Cantelli lemma yields something stronger than $(\ast\ast)$. Namely, from
$$\sum_k P(\{\omega\in \Omega : \lvert W_k(\omega) \rvert > k\}) < +\infty$$
we conclude that the set of $\omega$ such that $\lvert W_k(\omega)\rvert > k$ for infinitely many $k$ is a null set. In other words, for almost all $\omega$, we have $\lvert W_k(\omega)\rvert \leqslant k$ for all but finitely many $k$. In other words, from the Borel-Cantelli lemma we obtain
$$P\left(\liminf_{k \to \infty}\left\{\omega \in \Omega : \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1\right\}\right) = 1.\tag{$\ast{\ast}\ast$}$$
And now, we note that
$$C = \liminf_{k\to \infty} \left\{\omega \in \Omega : \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1 \right\} = \left\{\omega \in \Omega : \frac{\lvert W_k(\omega)\rvert}{k} \leqslant 1 \text{ for all but finitely many } k\right\}$$
is clearly a subset of $A$. Hence we have the implication $(\ast{\ast}\ast) \implies (\ast)$. Also it's clear that $C \subset B$, whence we have the implication $(\ast{\ast}\ast) \implies (\ast\ast)$.
Comment: No, we don't need iid. And I don't see an indication of Did suggesting that in the other thread.
Comment: I'm having a hard time parsing what you're writing over there. I would recommend a) using words in addition to formulae, and b) avoiding short-cut notation. Dropping the "$\omega \in \Omega$" from the sets isn't too bad, but one should always retain the set braces "$\{\dotsc\}$", confusing $\limsup \{ f_n \leqslant c\}$ and $\{\limsup f_n \leqslant c\}$ or similar things is deadly.
Comment: $(\ast{\ast}\ast)$ says that for almost all $\omega\in \Omega$ there are only finitely many $k$ with $\lvert W_k(\omega)\rvert > k$. So for almost all $\omega$ we have $\dfrac{\lvert W_k(\omega)\rvert}{k} \in [0,1]$ for all but finitely many $k$. For these $\omega$, we clearly have $\limsup\limits_{k\to\infty} \dfrac{\lvert W_k(\omega)\rvert}{k} \in [0,1]$.
Comment: It's $\geqslant 0$ because we have an absolute value. In your edit, you're abusing notation, so strictly it doesn't make sense. When translated into proper notation, it's correct, however. Even when abusing notation, I would strongly recommend to use curly braces to denote sets. $\liminf \left\{ \lvert W_k(\omega)\rvert/k \leqslant 1\right\} \subset \left\{ \limsup \lvert W_k(\omega)\rvert/k \leqslant 1\right\}$ is easier to interpret.
Comment: You have a misplaced brace, $\{ \limsup \dotsc\} \le 1$ doesn't make sense, must be $\{ \limsup \dotsc \le 1\}$.
Comment: Well, the "$\forall \omega \in \Omega$" doesn't belong there. As written, you'd claim that $\liminf \{\dotsc\} = \Omega$, but what you actually want to say is that for all $\omega\in \Omega$ we have the implication $\omega \in \liminf \{\dotsc\} \implies \omega \in \{\limsup \dotsc \leqslant 1\}$. You could completely drop the "$\forall \omega \in \Omega$" or move it into an introductory sentence (For all $\omega\in\Omega$ we have …).
Comment: Nah, it's okay now.
Comment: However, for what apparently is called the second Borel-Cantelli lemma (not being a probabilist, I had to look up what that is), one needs independence (but not identical distribution).
Comment: Thank you very much for the brilliant elaborate answer, Daniel Fischer. I can still remember your comments on my real analysis questions last year before you became a mod, iirc. Guess A.S. was wrong
Comment: Actually Daniel Fischer, I get how $(***)$ implies $(**)$ but how does $(***)$ imply $(*)$?
Comment: How is my edit in the last part? Why $\ge 0$? Thanks Daniel Fischer! ^-^
Comment: Oh right. Thanks hahaha. How about now?
Comment: Oh because curly brackets denote sets i.e. events? Okay fixed. Anything else? ^-^
Comment: Thanks very much Daniel Fischer. Anything else? ^-^
Comment: Thank you very much for the brilliant elaborate answer + comments, Daniel Fischer. I can still remember your comments on my real analysis questions last year before you became a mod, iirc. Guess A.S. was wrong
Comment: Daniel Fischer does $(***) \to (*)$ require [iid](http://math.stackexchange.com/questions/1537905/proof-convergence-of-random-variables-almost-sure/1538627#comment3144808_1538503)? That seems to be what Did is suggesting
Comment: Thanks. What's the difference between this situation and the other one? The strict inequality?
Comment: Okay thanks. I'll edit
Comment: Daniel Fischer, I think I already got it. Thanks anyway ^-^
Answer: The difference between the two formulas in the title is that the first one makes sense and the second one is meaningless.  The second one pretends to form the lim sup of some statements (not of numbers), and there's no such thing.
Comment: This is incorrect. The second formula is $\limsup$ of a sequence of subsets of $\Omega$ which is well-defined.
Comment: @A.S. I assume you're identifying the formula $|W_k|/k\leq 1$ with the set $\{x\in\Omega:|W_k(x)|/k\leq1\}$. If so, then I agree; the lim sup of a sequence of sets does make sense.
Comment: I should clarify the status of such abbreviations. In some contexts, notably in the argument of a probability function, this abbreviation is quite commonly used.  In others, it is uncommon and, in my opinion, likely to cause confusion.
Comment: @AndreasBlass Delete answer?
Comment: @BCLC No. Although reading a formula $\phi$ as a set $S$ makes sense of the title, it destroys the sense of the second displayed formula in the question, which would then read "$S$ almost surely".
Comment: @AndreasBlass Um, what?
Comment: @BCLC "Lim sup" applies to numbers and to sets, not to statements.  "A.s." applies to statements, not to numbers or sets. Applying both to the same expression (as in the title and in the second displayed formula) requires giving that expression two different meanings.
Comment: Andreas Blass, so there IS meaning? 'the second one is meaningless' ?
Comment: @BCLC The second part of the title is meaningless as it stands. It acquires a meaning if you change your understanding of the formula so that it denotes a set instead of a formula. When you make that change, the second displayed formula in the question loses its meaning. It can regain its meaning if you change your understanding of the formula back to the normal one, a formula rather than a set, but then the second half of the title loses its meaning. If you switch back and forth fast enough, you can probably create a blur in which everything looks meaningful, but I'd rather avoid blurs.
Comment: Errrrrrrrrrrrrrrr what? What do you mean by formula? limsup(events) is an event right?
Comment: @BCLC As I said, lim sup makes sense for sets, so indeed lim sup of events is an event. What I mean by formula in this discussion is the inequality $|W_k|/k\leq1$, which you have, as I wrote before, reinterpreted as a set (an event), namely the set $\{x\in\Omega:|W_k(x)|/k\leq 1\}$.
Comment: @AndreasBlass But the set you gave is abbreviated by omitting x and $\Omega$ right?
Comment: @BCLC It seems to be so abbreviated by you.
Comment: @AndreasBlass Thanks for the info. I'll try to be clear when I ask non-probabilistic real analysis or measure theory questions I guess


How do I use Get-MailboxFolderPermission with an Office365 Group?

Question: I'm trying to figure out how to use Get-MailboxFolderPermission for an Office365 group when connnected via powershell.
If I run:
Get-MailboxFolderStatistics -Identity groupname | ft Name, Identity, folderpath, foldertype

I see (among others) a folder named Calendar with identity groupname\Calendar, path /Calendar, and type Calendar.
When I try to view this calendar via:
Get-MailboxFolderPermission -Identity groupname:\calendar

it tells me the specified mailbox "groupname" doesn't exist.
I've also tried specifying the identity as domain\groupname:\calendar and as groupname@domain:\calendar. I imagine I have to specify the identity differently but all three formats work fine with usernames and Get-MailboxFolderPermission. Get-MailboxFolderStatistics accepts both user and group names in all three formats.
How do I use Get-MailboxFolderPermissions to view the calendar that Get-MailboxStatistics says exists?
Comment: Hmm. Since Set-MailboxFolderPermission doesn't understand the -GroupMailbox switch it looks like I can't manage access rights very well via PS. The UnifiedGroup cmdlets look like they could add users to the group which would give them Editor access but I don't see a way to grant additional people just Reviewer access.
Comment: When you say "group", do you mean Distribution Group? A distribution group isn't a mailbox and doesn't have folders, so I'm not sure how the Get-MailboxFolderStatistics command worked at all. Unless there's *also* a mailbox with a similar name.
Comment: Exchange Admin Center lists it with "Office 365 Group" in the "Group Type" column. Distribution Groups have "Distribution Group" in that type column. I'm not sure exactly how the group types differ but Get-MailboxFolderStatistics consistently succeeds for groups w/ type "Office365 Group" and consistently fails with "couldn't find groupname as a receipient" for groups w/ type "Distribution Group".
Comment: Aha, that's right. There's a new group type that is only available on Office 365. Instead of "-Identity" on the Get-MailboxFolderPermission try "-GroupMailbox". I've never done this before but a couple web searches turned up that parameter. See: https://www.michev.info/Blog/Post/1525/folder-permissions-for-groups-and-getting-them-recursively
Comment: Scroll to the bottom [here](https://technet.microsoft.com/en-us/library/dn641234(v=exchg.160).aspx) to see a list of new "UnifiedGroup" commandlets. Apparently in PS commandlets, "UnifiedGroup" is the name for Office 365 groups.
Comment: Weird. Is there at least a GUI way to manage permissions in the EAC?
Comment: Not that I can tell. AFAIK EAC doesn't have a GUI for managing calendar mailbox permission at all and the normal way of adjusting another user's calendar's permission is via PS. I can adjust group membership but that'll give people edit access instead of just viewing. I tried making myself an owner of the group in EAC then opening the calendar in desktop Outlook to see if I could manage things that way but so far it's saying permission denied. Sometimes with EAC changes take a little while to fully go into effect though.
Answer: To understand why this works with your "Office 365" groups and fails with a "Distribution Group" (Also called a Distribution List now) you need to first understand the difference between the two.
Office 365 Groups
This is one of the newer features in Office 365. This basically combines a few features and is also used by Microsoft teams. An Office 365 group has its own Mailbox, so when you use the command on an Office 365 group it will return the MailboxFolderPermission for this groups mailbox, not people who are a member and uses this Office 365 Group.
Distribution Group
A distribution group is a list of recipients that you wish to receive email.
A distribution group has an email alias, but no mailbox, when you send email to a group, it sends the email on to all members of the group.
The soulution
If you want to get the statistics for each member of a Distribution Group, you need to get the mailbox of all members of your distribution group, then pipe that to your folder statistics command.


Genymotion. How to pull database from device. my /data/data/ folder appears to be empty

Question: I have an issue with my Ubuntu installation of genymotion. Mainly I am unable to debug my database since both through DBMS in eclipse and adb in shell I can not view content of /data/ folder. There are no files shown.
I log through adb by cd to /sdk/platform-tools and typing ./adb shell su . I see that tab is not working, so I blindly type the path. Anyways I am not able to pull db, maybe I'm doing something wrong with commands.
Through DBMS i try to connect but data folder does not display content.
On Emulator everything works smoothly, but emulator is slow and I would rather use genymotion.
Any suggestions how to deal with this problem?
Answer: I don't have the problem you are talking about, the default shell user on Genymotion is root, so it should not happen. Despite everything, you can use run-as command to access your data directly.
To make it short. Your app's data folder is protected by your app's user rights.
The default shell user don't have right access to the app's folder. You can change the user that the shell is using thanks to the run-as command.

Open a shell: adb shell
Then type: run-as your.package.name

This command will change the shell user to the user of your app. So you will have the right to read and write on the app's data. You will also be redirected to your app's data folder: /data/data/you.package.name
When it is done you can browse your files easily.
Notice: Your app has to be built as debug to be able to use this command. It is supposed to be displayed on the device processes list on DDMS.
Comment: this answer is too complicated to understand :(
Comment: I've updated the answer. If you still don't understand I don't know what I can do for you :-)
Answer: Run emulator on your local computer, then
localuser:~ localhost$ adb shell
shell@android:/ $ su
shell@android:/ # cp /data/data/your.package.name/databases/your_database.db /mnt/shell/emulated/0/Download/your_database.db
shell@android:/ # exit
shell@android:/ $ exit
localuser:~ localhost$ adb pull /mnt/shell/emulated/0/Download/your_database.db ~/your_database.db
What it does is:
1. Connects to the emulator
2. Requests superuser permissions
3. Copies the file that is only available to superuser to a public directory (Downloads in this case)
4. Pulls the file from public folder (Downloads) to your local machine home directory; you can also perform this step from eclipse gui.
Answer: You've to set permissions to that folder / file, then you can pull easily:

adb shell "run-as package.name chmod 666 /data/data/package.name/databases/file"
adb pull /data/data/package.name/databases/file .
Answer: I managed to kind off go around the issue so I post my solution in case someone will find it helpful.
Previously I've been creating VM's with no google apis, superUser app crashed every time I wanted to root the phone.
so I created VM that is provided with google play and downloaded SQL Debugger App. I also use this code in my test suite and so I fetch db to SD-card at the end of every test I run. That way I don't need to have superuser permissions.
public static void copyDbToSd(Context context) {
    File dbFile = context.getDatabasePath((String) DatabaseHandler.DATABASE_NAME);

    InputStream myInput;
    try {
        myInput = new FileInputStream(dbFile);
        OutputStream myOutput = new FileOutputStream(
                Environment.getExternalStorageDirectory()
                + java.io.File.separator
                + "database.db");

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Exception: ", e);
    } catch (IOException e) {
        Log.e(TAG, "Exception: ", e);
    }

}

where DatabaseHandler.DATABASE_NAME is name of my database I set at creating db.


Android EditText within a ListView

Question: I have created a custom Array Adapter to bind a custom row that contains some static text and an editable EditText. I am trying to register to be notified when the user changes the text within the edit text and when notified to determine which ArrayList row the modified EditText corresponds to.
In the past with other types of views such as a Spinner I could simply put a reference to the parent view and the row number into the tag for the Spinner view. And then when I was notified that the value changed I read the tag to determine how to correlate it back to the master ArrayList.
The problem with registering to be notifed with an EditText change is that you do not get back a view but instead get a TextWatcher and I have no way to correlate back to the parent view or ArrayList row.
What is the technique that you need to use in this circumstance?
Answer: You can use onEditorAction on your EditText in your ArrayAdapter:
mEditText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        // Parse parent tree to find position of view
        int position = 0;
        View v = null;
        while (view != v && position < mListView.getChildCount())
            v = mListView.getChildAt(position++);
        // do something
        something(position);
        // do not consume the action
        return false;
}
});

Note that using this method, you are going to trigger an event only when user press "ok", "enter", "done", etc. on the keyboard.

Android EditText within a ListView


can't delete the preview button

Question: I have used the following code to delete the preview button which is on one of my create content type pages, but its not doing anything, what am I doing wrong?
function example_module_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form.
if ($form_id == 'example_content_type_node_form') {
drupal_set_message("entering formId");

unset ($form['preview']);
}
}

the drupal_set_message does go off, so I know that I am entering the if statement. I have put this code in a custom module (example_module).
Comment: Which version of drupal are you using?
Comment: drupal 6, so @Patrick Kenny's suggestion wont work
Comment: try using [a module instead](http://drupal.stackexchange.com/a/29328/1730)
Answer: You don't need to use custom code to delete the preview button.  On the Content Type administration page at admin/structure/types/manage/your_content_type, you can selection Disabled for Preview before submitting under Submission form settings.  This will remove the preview button for that content type.
Comment: I'm using drupal 6 and I dont seem to have that url. Is that a drupal 7 url? How do you do this in drupal 6?
Comment: Yes, my solution is for Drupal 7.  On D6, I would use the Jammer module. (http://drupal.org/project/jammer)
Answer: You don't need to write the code your self, there are already modules out there for exactly that!
1. Jammer Module (Recommended)

Hide or remove items from displaying including the node and comment preview buttons, node delete button, revision log textarea, workflow form on the workflow tab, and feed icon

2. Preview module (Less Recommended)

This module hasn't officially been released yet on Drupal 6 or 7, and it hasn't been updated in quite a while, so you may not want to use it on your live site

However if your using drupal 7, it's already a built in feature:

For Jamming the Preview button for content types in Drupal 7, the functionality is built into core. Visit admin/build/node-type/blog (example for blogs), or by navigation path, Administer - Site building - Content types - edit - Submission form settings fieldset

Edit:  Since your using drupal 6, my recommendation is just to go with the Jammer Module.
Comment: If you want to use a module, use the Jammer module.  (http://drupal.org/project/jammer)  The Preview module linked above has not had an official release for D6 or D7 and no work has been done on it for more than two years.
Comment: @PatrickKenny - Good point, I updated my answer.
Comment: I just installed Jammer and I set the option to delete the preview button, but it didn't work!
Comment: could you take a screenshot of what exactly you did?
Comment: You need to clear the cache (http://drupal.org/node/152983) any time you make a change to the Jammer module's settings.
Comment: I cleared the cache but nothing changed. I also tried to use jammer to delete the submit button, but that didn't work either. I created a screenshot but I'm not sure how to upload it here...
Comment: @user1015214 - one easy way to do it is to edit your question, and click add a picture, browse to the screen shot, and click upload, then copy the link that was added at the bottom, and past it here as a comment (btw, when u do this **do NOT save the edit**)
Comment: http://i.stack.imgur.com/5uhU5.png
Comment: I still can't get the jammer module to work, any ideas?
Answer: I needed to do it programmatically; here's the code solution in case anybody else needs to do it this way.
Disables comment preview for ALL node types

/**
 * Disables comment preview button for ALL node types.
 */
function my_module_update_7001() {
  $node_types = array_keys(node_type_get_types());
  foreach ($node_types as $node_type) {
    variable_set('comment_preview_' . $node_type, DRUPAL_DISABLED);
  }
}

If you want to remove the subject/title field from all node types (as I did) add this line below the other variable_set...

variable_set('comment_subject_field_' . $node_type, DRUPAL_DISABLED);

can't delete the preview button


htaccess Redirect a folder to a new URL

Question: I have the following code:
Redirect /email http://email.secureserver.net

Which doesn't seem to be working.  Basically, I need to be able to redirect someone when they go to www.thedomain.com/email/ to http://email.secureserver.net
Now I want this to be able to work on my testing server and also when it goes live so I don't have to change the code.
So for testing the URL will be something like:
www.testingserver.com/clients/drews-garage/live/email/

And for when it goes live it will be:
www.thedomain.com/email/

So based on the code I provided above, that should work either way but it doesn't seem to work on my testing server.  I tried a 301 redirect to.
Anyone have any ideas?
Thanks!
Answer: I suggest you to use mod_rewrite's RewriteRule. Rather than mod_alias's redirect.
RewriteCond %{Request_URI} /email/?$
RewriteRule ^ http://email.secureserver.net [L,R=301]

The above will match email/ in your URI path. So, clients/drews-garage/live/email/ as well as email/ will be matched.

Redirect /email http://email.secureserver.net

Is not working because of your URL:
www.testingserver.com/clients/drews-garage/live/email/
The above is trying to redirect www.testingserver.com/email/
or mod_alias might not be loaded. But, mod_alias is usually loaded by default so this case is very unlikely.
Comment: Thank you so much! Worked great. Is there an easier way to make it work without the trailing slash?  Right now I added a second RewriteRule and just used email instead of email/ but is there a shorter way to do that without adding another rule?  thanks!
Comment: @Drew check update. but now it will also match URLs like `www.testingserver.com/blahblahblah_myemail_blahblahblahblah...`
Comment: ahh, yeah I see that. that's very strange.  is that the only way around it? I noticed when I added my second rewrite for just email it did the same thing.
Comment: Awesome! Thank you very much for all your help.  I learned a lot.

htaccess Redirect a folder to a new URL


Why doesn't the simple function works?

Question: I'm writing a simple function in an angularjs controller, to turn on/off a bool variable, but it doesn't work? Why?
app.controller("registrationCtrl", function ($scope) {
    $scope.user = {};
    $scope.wasSubmitted = false;
    $scope.showInfo = true;

    $scope.submit = function () {
        $scope.wasSubmitted = true;
    };

    $scope.switch = function () {
        if ($scope.showInfo == true) {
            $scope.showInfo = false;
        } else {
            $scope.showInfo = true;
        }
    };
});

The function is used like this:
<button type="button" onclick="switch()">Show/Hide</button> {{showInfo}}

Comment: Use ng-click instead of onclick
Comment: have you defined that "$scope.showInfo" in controller ?? or directly using in this function ?
Comment: Can you share a working demo that describes your problem?
Comment: ng-click is correct, thank very much
Answer: Use ng-click:
<button type="button" ng-click="switch()">Show/Hide</button>

Answer: You have a problem in the view. Instead of onclick it is necessary to use ng-click:
<button type="button" ng-click="switch()">Show/Hide</button> {{showInfo}}

Why doesn't the simple function works?


Rearranging a Staircase Grid into a Square

Question:
Is there any way to rearrange the above "staircase" grid into three pieces that can be rearranged into the 6x6 square grid below it? I have tried this problem for over six hours and have not arrived at any solution. There has to be some general strategy in approaching this problem other than brute force, right??
I would appreciate any and all help--hints, suggestions, anything... I've gone mad trying to solve it
:(
Answer: $$\def\r{\color{red}{1}}\def\b{\color{blue}{2}}\def\g{\color{green}{3}}
\matrix{\r\cr \r&\r\cr \r&\r&\r\cr \r&\r&\r&\r\cr \r&\r&\r&\g&\g\cr
  \r&\r&\r&\g&\g&\g\cr \b&\b&\b&\g&\g&\g&\g\cr
  \b&\b&\b&\g&\g&\g&\g&\g\cr}$$
can be rearranged as
$$\matrix{\g&\g&\g&\g&\b&\b\cr \g&\g&\g&\g&\b&\b\cr \g&\g&\g&\r&\b&\b\cr
  \g&\g&\r&\r&\r&\r\cr \g&\r&\r&\r&\r&\r\cr \r&\r&\r&\r&\r&\r\cr}$$
Comment: I started with the realisation that the three corners of the staircase must be in different pieces, because any two of them are too far apart to fit in the square if they are confined to one piece.  Extending this idea, the three squares at the top of the staircase must all be in one piece, likewise the three squares at the right, likewise the four at bottom left.  After that it was really only trial and error, building up the pieces in both staircase and square a few bits at a time and making sure they have the same shapes.
Comment: Wow.. How did you do it so quickly?? Would you care to elaborate on your approach/thought process? Thanks!
Answer: You first the 6 by 6 on the staircase. Even thought it is not total, you can take the left over pieces and do it.
Comment: Tried that. Unsuccessful, unfortunately


How to get number of selected items in a listbox?

Question: I have a listbox:
self.listBox = Listbox(self.master,
                       selectmode='multiple',
                       height = 34,
                       width = 38)
self.listBox.grid(row = 3, column = 0, rowspan = 7, sticky = W)

I don't know how to get the number of selected items in the listbox?
In C#, it's:
listView1.SelectedItems.Count

How can I do this in Python?
Answer: I am going to assume you're asking about the listbox in Tkinter as it is not a Python built-in.
curselection()

Returns a tuple containing the line numbers of the selected element or elements, counting from 0. If nothing is selected, returns an empty tuple.
Comment: curselection() is equivalent of SelectedItems or SelectedItems.Count?
Comment: @popokatepetl, `curselection() = SelectedItems`, `len(curselection()) = SelectedItems.Count`
Comment: Thanks! @CommonSense
Comment: @popokatepetl, take a look [here](http://effbot.org/tkinterbook/listbox.htm) too. IMHO, [effbot.org](http://effbot.org/tkinterbook/) is most complete (from pythonist view, of course here a Tk/Tcl docs as well), most readable and newcomers-friendly. Good luck with tkinter!