Drupal Commerce: discount for line items based on user's values?

Question: I need to have different discount rates for every customer.
I added a textfield in the user profile, where I store a Json object with all the discounts (there is a little GUI to manipulate it), so, for example, I can have this situation:
{
    'product_B': 20,
    'product_A': 15,
    'product_C': 0
}

This means that this customer will have a fixed discount for all commerce_products of type A, 15 on type B and 0 on type C.
I got stuck in the Rules configuration: I created a rule for the Subtract an amount from the unit price event; In the condition, i just check that the user and the line item match few pre-requisites, and it works, but I cant get the line_item details in the action:
// My action
global $user;
$ul = user_load($user->uid);
if(isset($ul->field_discounts))
{
  $user_discounts = field_get_items('user', $ul, 'field_discounts');
  /*
   * Here i have to get few info of the current commerce_product/commerce_line_item
   * in order to calculate the correct $item_discount
   * */
  $discount = ((int)$item_discount * $value) / 100;
  return $discount;
}
return 0;

So the question is: inside that PHP block, how to get the current line item?
Comment: Have you tried `$line_item`?
Comment: yep, both `$line_item` and `$commerce_line_item`, always get null..
Comment: @Clive and if i alter the data selector for that action, getting the line item instead of the amount, I get a error `becose the value must be an amount`
Comment: Hmm yeah, that makes sense thinking about it. I don't think the line item will be exposed to the PHP block, and I doubt there'll be anything in scope to get a reference back to it. You might need to create your own Rules action. It's pretty simple, and you can copy most of what you need from [`commerce_line_item_unit_price_subtract`](http://drupalcontrib.org/api/drupal/contributions!commerce!modules!line_item!commerce_line_item.rules.inc/function/commerce_line_item_unit_price_subtract/7), which _does_ have access to the line item entity
Comment: @Clive thanks, I never created a Rule's action before, i'll give a read at the documentation (p.s: your should be an answer, not a comment ;)
Comment: Yeah I know, I'm always doing that :P I'll put it in...
Answer: I don't think the line item will be exposed to the PHP block, and I doubt there'll be anything in scope to get a reference back to it.
You might need to create your own Rules action. It's pretty simple, and you can copy most of what you need from commerce_line_item_unit_price_subtract(), which does have access to the line item entity.
hook_rules_action_info() would be a good place to start.
Answer: HT: Clive for making the initial suggestion. If I were you, I would make an action that "provides" the amount to subtract in a Rules variable and then enter that as a parameter in the "Subtract an amount from the unit price" so you don't have to duplicate the logic that handles price components in your custom code.
Also, I wouldn't use the global $user, because an administrator may cause this order to be refreshed and it would be priced according to that administrator's discount field value. Instead you should be able to traverse from the line item to the order to the order owner. You should always use the order owner when constructing pricing logic, not the current (or global) user.
Comment: Hi, thanks for your answer. The hint to not use `global $user` is great, i'll do this way. Now i have a little question: there is a usable hook to alter the line item creation used for calculating the price? I like to add the uid and the info i need to compute the discount, instead of reloading the product and digging deep into the fields (i know they get cached, but is also more comfortable)


Doubt about Harp Sound

Question: I have some doubts about the acoustics of the harp?
What is the resonant oscillator and sound effuser on a harp?
For example, on a trumpet, the resonant oscillator is the body of the instrument through which exhaled air travels and the effuser is the bell.
Comment: Are you asking about a big harp with strings, or the other harp - otherwise known to many as a harmonica or mouth organ?
Answer: Having thought about this some more, I've decided to rewrite my answer...
Your doubts about the acoustic properties of the harp are understandable. When heard in an orchestral setting, the harp is relatively quiet, requiring careful orchestration if one wants it be heard within a multi-instrument texture. However, a concert pedal-harp is in fact capable of producing quite a large sound; one that is significant in a chamber music setting, if easily obscured in an an orchestral setting. For a good example, listen to how easily Ravel balances the harp with other instruments in his Introduction and Allegro of 1905.
I discovered just how resonant a concert harp is the hard way! While at college, I wrote some pieces for harp and classical guitar, for me and a harpist friend to play together. Following the first rehearsal, I had to significantly rethink the pieces, as the harp was far, far louder than the classical guitar.
And yet, this seems surprising: to look at, a harp seems to basically be a set of strings vibrating within a wooden frame. Intuitively, this should be quite quiet, much like an electric guitar being played without an amplifier. After all, the strings aren't going to vibrate the air molecules around them enough to significantly project their sound. But, as with all (?) acoustic stringed instruments, the sound is not projected directly from the strings themselves, but instead from a resonant hollow body, via a soundboard. Because of the shape and construction of a harp (it looks "see-through" with the strings the most identifiable element when seen from the side) it is easy to overlook the soundboard and body, which are instead a prominent feature of the shape of other stringed instruments. But they are there. Here is some simple information about the construction of a harp.
So, the strings are the elements which oscillate when plucked; these strings vibrate the soundboard, which together with the body of the instrument amplify the sound, which is then radiated to the surrounding air. I'm not sure I would describe the body as the "sound effuser", but I guess that is the part of the harp where most of the sound radiates from.
Years ago, I found a really simple exercise that can demonstrate just how important the body of a stringed instrument is for amplifying the sound: if you lie an acoustic guitar flat, place a sheet of paper over the soundhole and strum the strings, the sound is much quieter. Interestingly though, not all harps have soundholes; but they are used on harps with metal strings, to aid emanation of the sound, as the soundboard is much stiffer to accommodate the increased tension of the strings.
Comment: Can you be more elaborate?
Comment: Of course; I'll rewrite my answer with some more useful info!
Comment: The large holes in the back of the soundbox on a harp aren't primarily there to let the sound out - they are to make it easier to change the strings.  The soundboard is where the sound comes from.  It is often plywood, and is as thin as the manufacturer dares to make it.  Which is why it will be bent under the strain of all the strings.

Doubt about Harp Sound


Como identificar um único ponto e legendá-lo no R

Question: Estou querendo identificar e legendar um único ponto em um gráfico. Estou trabalhando com um gráfico de dispersão com um indicador no eixo y e os anos no eixo x. Minha intenção é destacar o Brasil e identificá-lo com uma legenda dentro do gráfico.
Os dados abaixo podem ser usados para ilustrar o problema:
pibs <- tibble::tibble(
  posicao = c(1, 2, 3, 7, 4, 5, 6, 8, 9, 11, 13, 14, 10, 12, 17, 15, 16, 18,
              20, 19, 21),
  pais = c("Brasil", "México", "Argentina", "Venezuela", "Colômbia",
           "Chile", "Peru", "Equador", "Cuba", "República Dominicana",
           "Uruguai", "Costa Rica", "Guatemala", "Panamá", "El Salvador",
           "Bolívia", "Paraguai", "Honduras", "Haiti", "Nicarágua",
           "Santa Lúcia"),
  valor = c(2055000, 1149000, 637700, 210100, 309200,
            277000, 215200, 102300, 93790, 75020, 58420,
            58060, 75660, 61840, 28020, 37120, 29620,
            22980, 8608, 13730, 1686)
)

Comment: Bem-vindo ao StackOverflow em Português! Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, [dê uma olhada neste link](https://pt.meta.stackoverflow.com/questions/824/como-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Comment: Pode, por favor, **editar a pergunta** com a saída de `dput(dados)` ou, se a base for muito grande, de `dput(head(dados, 20))`? Nota: `dados` é o nome da base, por exemplo de um data.frame.
Answer: O gghighlight é um pacote sensacional para fazer isso:
Aqui vai um exemplo de como fazer com ele:
library(tidyverse)
library(gghighlight)

ggplot(pibs, aes(x = posicao, y = valor)) +
  geom_point(color = "blue") +
  gghighlight(pais == "Brasil", label_key = pais, unhighlighted_colour = "black")

Created on 2019-02-28 by the reprex package (v0.2.1)
Comment: Ou isso. Bem mais conciso.
Answer: Primeiro vamos criar um conjunto de dados para usar na resposta. Usei o pacote datapasta para copiar e colar a tabela desta página.
library(tidyverse)
pibs <- tibble(
  posicao = c(1, 2, 3, 7, 4, 5, 6, 8, 9, 11, 13, 14, 10, 12, 17, 15, 16, 18,
              20, 19, 21),
  pais = c("Brasil", "México", "Argentina", "Venezuela", "Colômbia",
           "Chile", "Peru", "Equador", "Cuba", "República Dominicana",
           "Uruguai", "Costa Rica", "Guatemala", "Panamá", "El Salvador",
           "Bolívia", "Paraguai", "Honduras", "Haiti", "Nicarágua",
           "Santa Lúcia"),
  valor = c(2055000, 1149000, 637700, 210100, 309200,
            277000, 215200, 102300, 93790, 75020, 58420,
            58060, 75660, 61840, 28020, 37120, 29620,
            22980, 8608, 13730, 1686)
)

pibs
#> # A tibble: 21 x 3
#>    posicao pais                   valor
#>      <dbl> <chr>                  <dbl>
#>  1       1 Brasil               2055000
#>  2       2 México               1149000
#>  3       3 Argentina             637700
#>  4       7 Venezuela             210100
#>  5       4 Colômbia              309200
#>  6       5 Chile                 277000
#>  7       6 Peru                  215200
#>  8       8 Equador               102300
#>  9       9 Cuba                   93790
#> 10      11 República Dominicana   75020
#> # ... with 11 more rows

Created on 2019-02-27 by the reprex package (v0.2.1)
A forma com a qual o ggplot2 trabalha é que deve haver uma coluna na tabela indicando quais países mostrar. Podemos fazer isso assim:
pibs2 <- pibs %>%
  mutate(mostrar = pais == "Brasil")
pibs2
#> # A tibble: 21 x 4
#>    posicao pais                   valor mostrar
#>      <dbl> <chr>                  <dbl> <lgl>
#>  1       1 Brasil               2055000 TRUE
#>  2       2 México               1149000 FALSE
#>  3       3 Argentina             637700 FALSE
#>  4       7 Venezuela             210100 FALSE
#>  5       4 Colômbia              309200 FALSE
#>  6       5 Chile                 277000 FALSE
#>  7       6 Peru                  215200 FALSE
#>  8       8 Equador               102300 FALSE
#>  9       9 Cuba                   93790 FALSE
#> 10      11 República Dominicana   75020 FALSE
#> # ... with 11 more rows

Created on 2019-02-27 by the reprex package (v0.2.1)
Agora, com a coluna em mãos é possível usá-la para alcançar o objetivo. Para destacar com a cor, basta usar a nova coluna para mapear as cores.
p <- ggplot(pibs2, aes(posicao, valor, col = mostrar)) +
  geom_point() +
  scale_color_manual(values = c("black", "darkgreen"))

p

Created on 2019-02-27 by the reprex package (v0.2.1)
E depois disso é possível usar essa coluna para filtrar a tabela e usar apenas o registro que interessa para a camada com o texto.
p +
  geom_text(aes(label = pais), data = filter(pibs2, pais == "Brasil"),
            position = position_nudge(1)) +
  theme(legend.position = "none")

Created on 2019-02-27 by the reprex package (v0.2.1)
Comment: Para tirar esse `a` *"feioso"* da legenda use `position = position_nudge(2), show.legend = FALSE`. Note a mudança do valor de `position_nudge`. De resto, voto para cima.
Comment: Não quis complicar demais a resposta (dar muita informação nova), mas vou aceitar a sugestão
Comment: Obrigado pelas respostas


Show that $\left\Vert f\right\Vert _{p}\leq\left\Vert f\right\Vert _{\infty}$ for all $1\leq p<\infty$

Question: My questión is simple:
Let $f\in L^{\infty}\left(\mu\right)$   whit $\mu$  a probability.
Show that $\left\Vert f\right\Vert _{p}\leq\left\Vert f\right\Vert _{\infty}$ for all $1\leq p<\infty$.
Remark: I ask this question on this website because I looking on the internet and I can not find information about it, which makes me distrust.
Answer: Observe that the sup norm means that $f(x) \leq ||f||_\infty$ for all $x \in X$ where presumably $X$ is your measure space and $\mu(X) = 1$.  Then
$$
||f||_p \;\; =\;\; \left ( \int_X |f|^p d\mu \right )^{1/p} \;\; \leq \;\; \left ( \int_X ||f||_\infty^p d\mu \right )^{1/p} \;\; =\;\; ||f||_\infty [\mu(X)]^{1/p} \;\; =\;\; ||f||_\infty.
$$


Specific question about investment returns that needs someone smart to answer it!

Question: OK, so I'm trying to work out the answer to a very specific question and for me it's complex maths. I'm sure for you mathematicians out there it's fairly everyday. If anyone can help I'd be very grateful:
I start with $200,000 and want it to last exactly 15 years whilst making equal drawdowns each year. The funds continue to make 5% returns each year during drawdown. What is the exact equal annual drawdown so the pot is at zero at the end of year 15 taking into account the continue capital returns of 5%?
I'd be interested in the answer and also an idiots guide to how it's calculated!
Many thanks.
Comment: Why not try it for 2 years, then 3, 4, and 5 years until you spot the pattern?
Answer: Deposit of $a_0$ must fund a stream of withdrawals $d$ in the end of year $i\in [1,N]$  whose present value is $d(1+r)^{-i}$. Summing that stream in present terms we get:
$$a_0=d(1-r)^{-1}\frac {1-(1+r)^{-N}}{1-(1+r)^{-1}}$$ hence
$$d=\frac {a_0r} {1-(1+r)^{-N}}\approx \frac {a_0r}{1-e^{-Nr}}$$
which tells you by how much you can increase your withdrawal compared to forever lasting annuity (when $N=\infty$ and withdrawals are $a_0r$). The last approximation is an exact answer if interest accumulation and withdrawals are done continuously.
Comment: @martin Gotta round down to integer cents ;).
Comment: @martin Interest rate, of course.
Comment: $r=.05$ would be my guess.
Comment: Wow this is quite amazing! Way beyond my brain power but I'm extremely grateful and fascinated by the response. So the answer is a $19268 annual withdrawal would completely deplete the fund after 15 years subject to a continued annual interest rate of 5%?
Comment: @Sam you might have a few bucks left over depending on how the bank rounds their interest payments. Shoot for $19268.44$ to have a negligible amount left over. Of course if you want continuous withdrawal (not just in the end of the year) (and if the interest is compounded continuously as well), you can withdraw at the rate of only $18952.55$ dollars per year.
Comment: @Sam Which works out to $51.92$ per day in the end of the day for daily withdrawals.
Answer: While you're doing this, suppose your friend has an account that starts with
a certain amount $A$, but makes no withdrawals.  At the rate of $5 \%$ per year, the friend's account will grow to $1.05^{15} A$ in those $15$ years while yours is dwindling to $0$.  Now let's say your withdrawal happens to be just enough to cover the interest on the two accounts together.  Then the
total of the two accounts will stay constant.  It starts at $200,000 + A$ and ends with $0 + 1.05^{15} A = 2.078928179 A $.  Therefore $200,000 + A = 2.078928179 A$, which we solve to get $A = 185,369.15$.
The yearly interest on $200,000 + A = \$385,369.15$ is $.05 \times 385,369.15 = \$ 19,268.46$.
So that's your yearly drawdown.
Comment: This would need some tweaking for perpetual annuities.


Mac OS X client crashes while mounting and writing to Linux server via NFSv4

Question: We are a Linux shop with about 30 Macs to support. We have our Leopard and Snow Leopard systems set up with LDAP authentication and automounted NFSv3 home directories so our staff have the same login and file whether they use OS X or Ubuntu. The only issue we have is that with NFSv3, we can't use Firefox >= 4. That issue still exists in Lion.
Now that OS X supports NFSv4 in Lion, I decided to try that out. It failed rapidly. I am unable to open applications. When I log in with ssh, many commands related to file operations hang.
On Linux NFSv4 clients, you must set up a domain name for mapping usernames between the client and the server in /etc/idmpad.conf. Is there anything like that in Lion? Are there any other configuration setting I need to check?
I have also tried using the latest version of Netatalk, but after a while, Microsoft Word starts saying files are read only.
Updated information

We discovered that using async in NFSv3 solved our problem with
  Firefox. Unfortunately, async does not solve the problem with NFSv4.

That turned out to be a misunderstanding of the problem. async does not solve the problem for either NFSv3 or NFSv4.
Testing Method
We have a couple of test accounts in our LDAP server with autofs entries pointing to an NFSv4 server on Ubuntu. I test by logging in via the login window or by ssh. In the GUI, I try opening applications and editing text files. Via ssh, I try editing text files with vim.
For the NFS Manager suggestion, I used su to become one of those users and tried editing a file with vim.
Server Settings
This is the /etc/exports from my testing nfsv4 server. The settings are the same as the production NFSv3 servers.
<code>/var/lib/nfs/v4root @utm(ro,fsid=0,root_squash,insecure,no_subtree_check,async) @admin(ro,fsid=0,no_root_squash,insecure,no_subtree_check,async)

/var/lib/nfs/v4root/d2/export/fac @utm(fsid=31,rw,async,root_squash,no_subtree_check,insecure) @admin(fsid=31,rw,async,no_root_squash,no_subtree_check,insecure)
/var/lib/nfs/v4root/d2/export/grad @utm(fsid=32,rw,async,root_squash,no_subtree_check,insecure) @admin(fsid=32,rw,async,no_root_squash,no_subtree_check,insecure)
/var/lib/nfs/v4root/d2/export/staff @utm(fsid=33,rw,async,root_squash,no_subtree_check,insecure) @admin(fsid=33,rw,async,no_root_squash,no_subtree_check,insecure)

/d2/export/fac @utm(fsid=41,rw,async,root_squash,no_subtree_check,insecure) @admin(fsid=41,rw,async,no_root_squash,no_subtree_check,insecure)
/d2/export/grad @utm(fsid=42,rw,async,root_squash,no_subtree_check,insecure) @admin(fsid=42,rw,async,no_root_squash,no_subtree_check,insecure)
/d2/export/staff @utm(fsid=43,rw,async,root_squash,no_subtree_check,insecure) @admin(fsid=43,rw,async,no_root_squash,no_subtree_check,insecure)
</code>
Client mount options
The clients use autofs in LDAP to mount the filesystem. The options follow:
<code>intr,tcp,rw,vers=4,timeo=20
</code>
I have tried with just vers=4, but I get the same results.
Network
For this test, the client and the server are on different subnets. The traffic goes through 100 Mbps cisco switches with gigabit connections to the cisco route switch. Throughput tests show consistent 91 Mbps transfers with low .3 ms pings. This network has been appropriate for NFSv3 for many years.
Solution
Wait for 10.7.3. I am pleased to report that this was a bug in 10.7.2, and the 10.7.3 prerelease fixes it.
Comment: So you can mount via NFv4, but you just have issues with Mac OS X functioning with NFSv4? Because it seems that the question is framed incorrectly.
Comment: That is correct. I stated the question in that way because I think there must be some configuration step I am missing. There must be more to it that using the vers=4 option with mount.
Comment: It seems that the issue is more about optimizing NFS for Mac OS X Client than just mounting.

Let me ask you this - when a user logs in and automounts, did the ~/Library directory gets created? That is the folder used by most Mac OS X Apps for most user-level preferences.
Comment: ~/Library and 86 other files and directories get created in a pristine home directory before the mac crashes and says "You need to restart your computer..."
Comment: So a lot of writes then.

We probably want the exports file on the server as well as the current mount settings from the client side. Also, are you connecting over wireless or wired network? And what is the throughput speed from your client to the server and back?
Comment: The title change is good except that Lion is the first release with support for NFSv4.
Comment: Now I remember. This is what I have answered before:

http://serverfault.com/questions/113299/snow-leopard-hangs-when-using-openldap-on-linux-for-authentication

It doesn't look like the right answer, as it was not accepted. :(
Comment: Those were the good old days. My comments there remind me that I haven't tried a non-Linux NFSv4 server yet. Or maybe a newer kernel.
Answer: You may want to try using NFS Manager to help you configure your NFS mounts. It's a lot easier to use than Apple's Disk Utility.
Comment: I'm quite comfortable reading the mount_nfs man page to find mount options to use on the command line. If there is a specific option or group of options you can tell me to make OS X behave properly as client to a Linux NFSv4 server, then I would happily upvote, accept, and award the bounty to your answer.
Answer: This is a bug. It worked briefly in a prerelease update, but it is broken again. I have submitted a bug report with Apple.
Comment: @MikeBoers I think I set up samba to work around it. Then I changed jobs and no longer provide desktop support ;)
Comment: 4 years later... what became of this?


What does countably infinite mean?

Question: How would you concisely explain the concept of countably infinite to a student who isn't exposed to any set theory? I am having difficulty understanding what the concept of countably infinite is, could you please help me understand.
Thank You!
Comment: http://en.wikipedia.org/wiki/Countable_set
Comment: Jeff, I retagged the post appropriately. Please note it is redundant to tag a question with both the [set-theory] and the [elementary-set-theory] tags.
Answer: A set $S$ is countably infinite if and only if you can label its members with the positive integers in such a way that each member of $A$ gets exactly one label, and every positive integer is used as a label; it's exactly as if you were counting the members of $A$, except that you never come to an end. Of course this immediately tells you that the set of positive integers is countably infinite: its members are their own labels!
How about the set of non-negative integers, the positive integers together with $0$? I can give $0$ the label '$1$', $1$ the label '$2$', $2$ the label '$3$', and so on: each non-negative integer $n$ gets the label '$n+1$'. Every non-negative integer gets exactly one label, and every positive integer is the label of some non-negative integers. (For instance, '$100$' is the label of $99$.)
Let's get a little fancier: what about the set $E = \{2,4,6,8,\dots\}$ of even positive integers? $E$ is also countably infinite: just label the even integer $2n$ with the positive integer $n$, so that $2$ is labelled '$1$', $4$ is labelled '$2$', and so on. With just a little more work we can see that the set $O = \{1,3,5,7,\dots\}$ of odd positive is countably infinite: $$\begin{align*}
1 &= 2 \cdot 1 - 1\\
3 &= 2 \cdot 2 - 1\\
5 &= 2 \cdot 3 - 1\\
7 &= 2 \cdot 4 - 1\\
&\qquad\vdots
\end{align*}$$ That is, the $n$-th odd positive integer is $2n-1$, so giving $2n-1$ the label $n$ will correctly label all of $O$.
One more: what about all of the integers, positive, negative, and zero? We can list them systematically as $0,1,-1,2,-2,3,-3,4,-4,\dots$ and then label each integer with its position in the list: $0$ gets the label '$1$', $1$ gets the label '$2$', $-1$ gets the label '$3$', and so on. It takes a bit more work this time to write down a formula associating an integer with its label, but it can be done: if $n$ is a positive integer, it's label is '$2n$', and otherwise $n$ gets the label $1-2n$.
I'll finish with a significantly more complicated example. Let $P$ be the set of all ordered pairs of positive integers. The members of $P$ can conveniently be displayed in a two-dimensional layout: $$\begin{array}{ccccc}(1,1)&(1,2)&(1,3)&(1,4)&\dots\\
(2,1)&(2,2)&(2,3)&(2,4)&\dots\\
(3,1)&(3,2)&(3,3)&(3,4)&\dots\\
(4,1)&(4,2)&(4,3)&(4,4)&\dots\\
\vdots&\vdots&\vdots&\vdots&\ddots
\end{array}$$ By starting in the upper left-hand corner and weaving back and forth diagonally, you can properly label every member of $P$: $$\begin{array}{ccccccccc}(1,1)\leftrightarrow 1&\Rightarrow&(1,2)\leftrightarrow 2&&(1,3)\leftrightarrow 6&\Rightarrow&(1,4)\leftrightarrow 7&&\dots\\
&\swarrow&&\nearrow&&\swarrow&&\nearrow&\\
(2,1)\leftrightarrow 3&&(2,2)\leftrightarrow 5&&(2,3)\leftrightarrow 8&&(2,4)\leftrightarrow 14&&\dots\\
\Downarrow&\nearrow&&\swarrow&&\nearrow&&\swarrow&\\
(3,1)\leftrightarrow 4&&(3,2)\leftrightarrow 9&&(3,3)\leftrightarrow 13&&(3,4)\leftrightarrow 18&&\dots\\
&\swarrow&&\nearrow&&\swarrow&&\nearrow&\\
(4,1)\leftrightarrow 10&&(4,2)\leftrightarrow 12&&(4,3)\leftrightarrow 19&&(4,4)\leftrightarrow 25&&\dots\\
\Downarrow&\nearrow&&\swarrow&&\nearrow&&\swarrow&\\
\vdots&&\vdots&&\vdots&&\vdots&&\ddots
\end{array}$$ (You should check that labels '$12$', '$13$', '$14$', '$18$', '$19$', and '$25$' are right.) This shows that $P$ is countably infinite. It's possible express this correspondence by a formula, but that's going further than necessary just to get across the idea of countably infinite.
Added: The same basic idea that I used for $P$ can be used to show that the set of rational numbers is countably infinite, though some of the technical details are rather non-trivial.
Comment: +1 Now that you have come so far, you probably could also mention  that rationals are countable. :)
Comment: @Srivatsan: I thought about it, but making an honest job of it is a bit messy on account of the duplicates: showing that an infinite subset of a countably infinite set is countably infinite without a lot of handwaving isn't trivial.
Comment: Yes, I agree that will make the post a tad too long. Your answer is very good as it is. I suggested that because I think the countability of rationals is more mysterious at first sight than ordered pair of natural numbers.
Comment: @Brian: The difficulty in establishing definite bijections is why I usually define countable by 'there is an injection into $\mathbb{N}$' or 'there is a surjection from $\mathbb{N}$'.
Comment: Can't you just assign the duplicate labels (1, 5, 13), then for each member of the set [in this case 1/1=2/2=3/3] take the smallest label that applies to it, then you have a set of _unique_ labels {1,2,3,4,6,...} - are we not able to assume that this latter set of labels can be mapped to the positive integers? Or just go "1/1, 1/2, 2/1, 3/1, ... 1/3" to "1, 2, 3, 4, ... 5" directly? Is it just the fact that you can't express it as a formula, or is there some doubt that the rationals are _infinite_?
Comment: @Random832: Using the smallest label that applies is indeed one way to do it, quite possibly the easiest, but doing it rigorously requires proving that recursive definitions are legitimate. It's probably fine at an informal level, but the set theorist in me sees it as handwaving.
Comment: @Zhen Lin: I suppose that that approach might make sense in a 'Chapter 0' for a first abstract algebra course or the like, but I don't care for it. In a low-level introduction it loses the intuitive underpinning of the notion of countability, and in a rigorous approach it's not necessary, since one will *prove* that infinite subsets of a countably infinite set are infinite.

What does countably infinite mean?


What is $p_i(x_i - \sum_i p_ix_i)$ called?

Question: I was reading a paper (dont have it with me!) on statistics and found a term that I have never encountered before:
$p_{i}{(x_{i}-\mu )} = p_i(x_i - \sum_i p_ix_i)$
After some research it seems that this term some how to the variance:
$Var(X) =\sum _{i=1}^{n}p_{i}{(x_{i}-\mu )^2}$
Does anyone have a hunch as to what this term referred to in the literature?
Answer: I don't think there is a special name for that term. It's just some mathematical expression,
$$p_i(x_i - \mu),$$
in which the definition of the mean value has been inserted (--where one should better use another letter as $i$ for the summation index),
$$\mu \ = \ \sum_{j} p_j x_j.$$


SAPUI5 Page Footer doesn't show in correct place

Question: I have a problem regarding the design of the page. I can't make the header and footer look correctly in all resolutions.
I have one main App view which handles routing and places the required view to the content.
<mvc:View xmlns:mvc="sap.ui.core.mvc"   xmlns="sap.m" heigh="100%" displayBlock="true"
      controllerName="demo_pcm.App" >

<Page id="productListPage" navButtonPress="onNavBack" showNavButton="true" title="{i18n>products}">
    <headerContent>
<IconTabBar
        expanded="false"
        id="idIconTabBar"
        select="handleIconTabBarSelect"
        expandable="false"
        applyContentPadding="false"
        headerMode="Inline"
        visible="{viewModel>/visible}"
       >
    <items>
        <IconTabFilter

                icon="sap-icon://begin"
                iconColor="Neutral"
                design="Horizontal"
                text="STEP1"
                key="STEP1" />
        <IconTabSeparator icon="sap-icon://open-command-field" />
        <IconTabFilter
                icon="sap-icon://survey"
                iconColor="Neutral"
                design="Horizontal"
                text="STEP2"
                key="STEP2"
        />

    </items>
</IconTabBar></headerContent>

    <content >
<App id="app" >

</App>
    </content>
</Page>

Based on the URL, i am inserting other views to the app itself. Here my design problem comes.If i use header content and place the icontabbar there (this icontabbar should repeat on each subview that is why i placed inside the app.view)
Here how it looks;
header cannot be seen clearly
if i just remove the page control or don't use  in the app.view and just place the icontab bar itself right above to  control, it works fine. I want my icontabbar to stick header always that is why i tried to include in the header content.
Another problem is with the footer.
After i load my first first view from the router , i can't see my footer if i don't scroll down. I need to scroll down to see or set the view height to 90%.
That is how it looks;
missing footer
in the image you will see another scrollbar on the right, it is due to page vibration (Somehow it was shaking in chrome and i put below code to the css)
html{ overflow-y: scroll;}

from the app.view if i insert scroll container and set the height to 90%, it works fine but it goes higher position on higher resolutions.(so in a 4k resolution it looks very weird)
  <ScrollContainer
        height="90%"
        width="100%"
        horizontal="false"
        vertical="true">
<App id="app" >

</App>
</ScrollContainer>

and here is how it looks now (without  in app.view and scroll container with height 90% (footer can be seen but you can see white line at the bottom, it becomes bigger on higher resolutions)
(stackoverflow doesn't allow me to post 3 links :/)
Here is my index.html

where can be the problem ? I am very near to loosing my mind. I tried floating footer but same problem. Should i include my scroll container in the subview itself before the footer ?
Answer: If you are open to some CSS workaround, here's a quick fix:
The Toolbar seems to have a fixed height of around 125px(including the padding) across different resolutions. You could set the height of the App container accordingly with this.
XML
<App id="app" class="adjustedHeight">

CSS
.adjustedHeight{
    height: calc(100% - 125px) !important;
}

Note: This is not the best solution. If I find a better one, I will update this answer
Comment: thanks man! i changed the page design a bit but that also helped.


Convert from apache rewrite to nginx

Question: I want to convert from apache rewrite modules to nginx
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteCond %{QUERY_STRING} SELECT(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} UNION(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} UPDATE(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteRule ^([^.]*)/?$ index.php [L]
RewriteRule ^domain/trial/cms$ index/index.php?%{QUERY_STRING} [L]
RewriteCond %{HTTP:Range} ([a-z]+) [NC]
RewriteRule ([0-9_\-]+)flv$ http://www.domain.com [R,L]
RewriteCond %{ENV:byte-ranges-specifier} !^$
RewriteRule ([0-9_\-]+)flv$ http://www.domain.com [R,L]
RewriteCond %{HTTP_USER_AGENT} !^Mozilla/5 [NC]
RewriteCond %{HTTP_USER_AGENT} !^Mozilla/4 [NC]
RewriteCond %{HTTP_USER_AGENT} !^Opera [NC]
RewriteRule ([0-9_\-]+)flv$ http://www.domain.com [R,L]
RewriteRule ^$ index/index.php?%{QUERY_STRING} [L]
RewriteCond %{SCRIPT_FILENAME} !sss.php [NC]
RewriteCond %{SCRIPT_FILENAME} !m-administrator [NC]
RewriteRule ^([^/^.]*)$ sss.php?encrypted=$1&%{QUERY_STRING} [L]
RewriteCond %{SCRIPT_FILENAME} !sss.php [NC]
RewriteCond %{SCRIPT_FILENAME} !m-administrator [NC]
RewriteRule ^([^/^.]*)/([^/^.]*)$ sss.php?tab=$1&page=$2&%{QUERY_STRING} [L]
RewriteCond %{SCRIPT_FILENAME} !sss.php [NC]
RewriteCond %{SCRIPT_FILENAME} !m-administrator [NC]
RewriteRule ^([^/^.]*)/([^/^.]*)/([^.]*)$ sss.php?tab=$1&page=$2&queryString=$3&%{QUERY_STRING} [L]
RewriteCond %{SCRIPT_FILENAME} !sss.php [NC]
RewriteCond %{SCRIPT_FILENAME} !security.php [NC]
RewriteRule ^([^/]*)$ index/$1?%{QUERY_STRING} [L]

I tried to convert it by online tools such as : http://www.anilcetin.com/convert-apache-htaccess-to-nginx/ but it didn't convert it correctly. The conversion output is :
if ($args ~ "mosConfig_[a-zA-Z_]{1,21}(=|%3D)"){
    set $rule_0 1;
}
if ($args ~ "base64_encode.*(.*)"){
    set $rule_0 1;
}
if ($args ~* "(<|%3C).*script.*(>|%3E)"){
    set $rule_0 1;
}
if ($args ~ "GLOBALS(=|[|%[0-9A-Z]{0,2})"){
    set $rule_0 1;
}
if ($args ~ "_REQUEST(=|[|%[0-9A-Z]{0,2})"){
    set $rule_0 1;
}
if ($args ~ "SELECT(=|[|%[0-9A-Z]{0,2})"){
    set $rule_0 1;
}
if ($args ~ "UNION(=|[|%[0-9A-Z]{0,2})"){
    set $rule_0 1;
}
if ($args ~ "UPDATE(=|[|%[0-9A-Z]{0,2})"){
    set $rule_0 1;
}
if ($rule_0 = "1"){
    rewrite ^/([^.]*)/?$ /index.php last;
}
if ($rule_1 = ""){
    rewrite ^/domain/trial/cms$ /index/index.php?$args last;
}
if ($http_range ~* "([a-z]+)"){
    set $rule_2 1$rule_2;
}
if ($rule_2 = "1"){
    rewrite /([0-9_-]+)flv$ http://www.domain.com redirect;
}
#ignored: condition 0
if ($rule_3 = "1"){
    rewrite /([0-9_-]+)flv$ http://www.domain.com redirect;
}
if ($http_user_agent !~* "^Mozilla/5"){
    set $rule_4 1$rule_4;
}
if ($http_user_agent !~* "^Mozilla/4"){
    set $rule_4 2$rule_4;
}
if ($http_user_agent !~* "^Opera"){
    set $rule_4 3$rule_4;
}
if ($rule_4 = "321"){
    rewrite /([0-9_-]+)flv$ http://www.domain.com redirect;
}
if ($rule_5 = ""){
    rewrite ^/$ /index/index.php?$args last;
}
if ($uri !~* "sss.php"){
    set $rule_6 1$rule_6;
}
if ($uri !~* "m-administrator"){
    set $rule_6 2$rule_6;
}
if ($rule_6 = "21"){
    rewrite ^/([^/^.]*)$ /sss.php?encrypted=$1&$args last;
}
if ($uri !~* "sss.php"){
    set $rule_7 1$rule_7;
}
if ($uri !~* "m-administrator"){
    set $rule_7 2$rule_7;
}
if ($rule_7 = "21"){
    rewrite ^/([^/^.]*)/([^/^.]*)$ /sss.php?tab=$1&page=$2&$args last;
}
if ($uri !~* "sss.php"){
    set $rule_8 1$rule_8;
}
if ($uri !~* "m-administrator"){
    set $rule_8 2$rule_8;
}
if ($rule_8 = "21"){
    rewrite ^/([^/^.]*)/([^/^.]*)/([^.]*)$ /sss.php?tab=$1&page=$2&queryString=$3&$args last;
}
if ($uri !~* "sss.php"){
    set $rule_9 1$rule_9;
}
if ($uri !~* "security.php"){
    set $rule_9 2$rule_9;
}
if ($rule_9 = "21"){
    rewrite ^/([^/]*)$ /index/$1?$args last;
}

Please help me with the proper conversion result for nginx in order to work perfectly.  $rule_1,$rule_3,$rule_5 are not set in the conversion output.
Comment: Which part is not working ? Converted rewrite rules look pretty good to me.
Comment: aHrvojeŠpoljar $rule_1,$rule_3,$rule_5 are not set in the conversion output.
Answer: Maybe you should try this tool:
http://winginx.com/htaccess
I used it a couple of times and it worked!

Convert from apache rewrite to nginx


Upload Images to specific folders

Question: how do I upload images (Media) to specific folders inside the default directory? I will have thousands of pictures and would like to have an organized structure of folders.
Thanks a lot.
Comment: Is it D7 or D6 ? You can configure a Directory per content type, go to Edit Content Type and check image related settings.
Comment: Hi, it's D7. hmmm... Each image will be part of the same content type ("photo") so that will not solve my issue. (I have a reference for a content type "gallery" that shows all the "photos" of that gallery). If I could choose a separate folder for each "gallery" would be nice... do you know anything?
Thanks for you help
Answer: You can use File (Field) Paths module. It allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.
You can use value of any node field as folder name where files will be uploaded. Or you can create new field for this purpose.
Comment: Thanks Eugene. This sounds good. I could have a text field in my content type like "upload images to" and then use this value as the path to store the file.
Comment: @Daniel Exactly
Answer: If you wanted a programmatic solution, you could use the setting array when creating field instance:
<code>'settings' => array(
        'file_directory' => 'YOUR_DIRECTORY_HERE',
)
</code>
For example:
<code> // Create the instance.
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Article Image',
      'description' => 'An image for the article.',
      'required' => TRUE,
      'settings' => array(
        'file_extensions' => 'png jpg jpeg',
        'file_directory' => 'myModule/news', //your wanted attribute
        'max_filesize' => '20 MB',
        'alt_field' => 1,
        'title_field' => 1,
        'max_resolution' => '300x200',
        'min_resolution' => '200x125',
        'default_image' => 0,
      ),
</code>
Answer: If you just want to upload image in sub directory. their is configuration for drupal image field . Path is your_example_domain.com/admin/structure/types/manage/your_content_type/fields/field_image. you can set the file directory by using token and like static name "your_subdir_name". hope this help!

Upload Images to specific folders


Conditionally replace neighbouring cells

Question: Lets say I have a matrix A:
A =
 0     1     0     0
 0     0     0     0
 0     0     0     1
 0     0     0     0

And I want to create a new matrix B of the same dimension where all ones and accompanying neighbours are replaced by the following matrix:
X =
 1     1     1
 1     2     1
 1     1     1

The 2 in matrix X should be placed 'on top' of the 1 values as to get:
B =
 1     2     1     0
 1     1     2     1
 0     0     1     2
 0     0     1     1

Values should be added up where elements overlap and matrix X should be 'cut off' in places where it extends the dimensions of matrix A/B The idea is to eventually replace X by a 2d gaussian distribution and matrix A will be large containing many more ones. So it's essential that the code is efficient and fast. This is the code i came up with:
 A = [0 1 0 0;0 0 0 0;0 0 0 1;0 0 0 0]
 X = [1 1 1;1 2 1;1 1 1]
 B = zeros(4,4);
 t=1;

 indA = find(A==1);
 indX = find(X==2);
 all = find(X>0);
 [iall jall] = ind2sub(size(X),all);

 [ia ja] = ind2sub(size(A),indA)
 [ix jx] = ind2sub(size(X),indX)
 iv = ia-ix
 jv = ja-jx

 for t=1:numel(iv),
     ib = iall+iv(t);
     jb = jall+jv(t);

     ibjb = [ib(:), jb(:)]
     c1 = (ibjb(:,1)>4)|(ibjb(:,1)<1); c2 = (ibjb(:,2)>4)|(ibjb(:,1)<1);
     ibjb((c1|c2),:)=[]

     isel = ibjb(:,1)-iv(t)
     jsel = ibjb(:,2)-jv(t)

     B(ibjb(:,1), ibjb(:,2)) = B(ibjb(:,1), ibjb(:,2))+ X(isel, jsel)
     t=t+1;
 end

Is there a more efficient/faster way (minimizing the loops) to code this function?
Answer: What you want is a (2D) convolution. So use conv2:
B = conv2(A, X, 'same');


Would this observable be hot?

Question: Wouldn't this make the observable hot?
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;

namespace ObservableNumberGenerator.ObservableImplementationReliesOnOperator.Hot
{
    public class RandomNumbers : IObservable<int>, IDisposable
    {
        protected Random _random = null;
        protected int _maxNumbersToGenerate;
        protected int _startAfterMilliseconds = 1000;
        protected int _generateEveryMilliseconds = 1000;

        protected IObservable<int> _innerObservable = null;
        protected IDisposable _innerSubscription = null;
        protected bool _completed = false;
        private bool disposedValue = false;

        public RandomNumbers(int maxNumbersToGenerate,
            int startAfterMilliseconds = 1000,
            int generateEveryMilliseconds = 1000)
        {
            _maxNumbersToGenerate = maxNumbersToGenerate;
            _startAfterMilliseconds = startAfterMilliseconds;
            _generateEveryMilliseconds = generateEveryMilliseconds;

            _random = new Random();

            _innerObservable = Observable.Timer(
                TimeSpan.FromMilliseconds(_startAfterMilliseconds),
                TimeSpan.FromMilliseconds(_generateEveryMilliseconds))
                .Select(v => GenerateNumber())
                .Take(_maxNumbersToGenerate);

            _innerSubscription = _innerObservable.Subscribe(OnNext, OnError, OnCompleted);
        }

        protected virtual void OnCompleted()
        {
            _completed = true;
        }

        protected virtual void OnError(Exception ex)
        {
        }

        protected virtual void OnNext(int value)
        {
        }

        protected virtual int GenerateNumber()
        {
            return _random.Next();
        }

        public IDisposable Subscribe(IObserver<int> observer)
        {
            if (observer == null) throw new ArgumentNullException("observer");

            if (_completed)
            {
                observer.OnCompleted();

                return Disposable.Empty;
            }
            else
            {
                return _innerObservable.Subscribe(observer);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _innerSubscription.Dispose();
                }

                disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}

Or would I have to Publish and Connect to make it hot?
public class RandomNumbers : IObservable<int>, IDisposable
{
    protected IConnectableObservable<int> _innerObservable = null;

    public RandomNumbers(int maxNumbersToGenerate,
        int startAfterMilliseconds = 1000,
        int generateEveryMilliseconds = 1000)
    {
        _maxNumbersToGenerate = maxNumbersToGenerate;
        _startAfterMilliseconds = startAfterMilliseconds;
        _generateEveryMilliseconds = generateEveryMilliseconds;

        _random = new Random();

        _innerObservable = Observable
            .Timer(TimeSpan.FromMilliseconds(_startAfterMilliseconds),
            TimeSpan.FromMilliseconds(_generateEveryMilliseconds))
            .Select(v => GenerateNumber())
            .Take(_maxNumbersToGenerate)
            .Publish();

        _innerObservable.Connect();

        _innerSubscription = _innerObservable.Subscribe(OnNext, OnError, OnCompleted);
    }

    ...
}

Comment: @WaterCoolerv2 - You also really shouldn't be implementing your own observable classes like this. They are exceedingly tricky to get right.
Comment: But I started the subscription on the `Timer` query in the ctor of my own operator, long before any subscribers would have come to me. Wouldn't that make *my* operator a hot one regardless of what I use inside it?
Comment: @WaterCoolerv2 - No it doesn't. Your observable is cold. Just because you start a subscription in your constructor doesn't make the observable hot. It just means that you're ultimately subscribing more than once. You need to publish to make a cold observable hot.
Comment: @Enigmativity Thank you. I know I shouldn't implement observables. This is all just practice stuff.
Comment: I don't mind the downvote at all, but could you please explain what peeved you off about the question and my own answer? I might learn something new. My intention is only to educate myself. Please tell me what I am doing wrong.
Answer: Your first code is a cold observable. Here's some easy client code to demonstrate:
    static void Main(string[] args)
    {
        var x = new RandomNumbers(10, 0, 500);
        x.Timestamp().Subscribe(i => Console.WriteLine("First sub: {0} {1}", i.Timestamp.DateTime.ToString("O"), i.Value));
        Thread.Sleep(1000);
        x.Timestamp().Subscribe(i => Console.WriteLine("Second sub: {0} {1}", i.Timestamp.DateTime.ToString("O"), i.Value));
        Console.Read();
    }

With the cold observable, you'll see that the "First sub" lines don't match the "Second sub" lines. With the hot implementation, they do. You'll also notice that the cold implementation, there's the same number of "First sub" and "Second sub" lines. With the hot implementation, the max of 10 is observed globally.

Just to clarify hot vs cold. Assuming a static/stable data stream, you get this marble diagram, showing how subscriptions differ when subscribing at times t0 and t1:
hot source:  A---B---C---D---
sub at t0 :  A---B---C---D---
sub at t1 :      B---C---D---

cold source: A---B---C---D---
sub at t0  : A---B---C---D---
sub at t1  :     A---B---C---

In our case though, we have a random stream:
hot source:  R()-R()-R()-R()-
sub at t0 :  R1--R2--R3--R4--
sub at t1 :      R2--R3--R4--

cold source: R()-R()-R()-R()-
sub at t0  : R1--R2--R3--R4--
sub at t1  :     R5--R6--R7--

The results of the Random() calls get shared in a hot observable, whereas in the cold they do not. While the hot observable subscriptions get different values if you measure by index, they receive the same values at a given time t. In a stable source, the cold observable subscriptions match by index, but they don't match by time. In an unstable source, like our case, cold observables don't match by either index or time.
Comment: "With the cold observable, you'll see that the "First sub" lines don't match the "Second sub" lines. With the hot implementation, they do." - This isn't true. Whether the values match or not has nothing to do with being hot or cold. A hot observable subscribed to at different times will have different values and a cold observable can certainly produce different values. Only hot observables subscribed to at the same time (relative to it producing values) produce the same values and only cold observables that are produced from a static source produce the same values.
Comment: Added clarification to answer.
Answer: As Enigmativity points out, and as Shlomo's answer also seems to suggest, just because you subscribe to the observable in the constructor won't make it "shared" and thus want make it hot.
I thought hard about why that should be and then I looked at the source code for the Subscribe method on the Timer operator and realized something I had known earlier but had forgotten because I was looking too hard.
Most operators are implemented this way: every time you call the Subscribe method on the Timer operator, you create a new instance of an internal class that starts a new sequence on the default pool scheduler.
So, somewhere down there in the Timer class is written:
namespace System.Reactive.Linq.ObservableImpl
{
    internal class Timer : Producer<long>
    {
        protected override IDisposable Run(
                               IObserver<long> observer,
                               IDisposable cancel,
                               Action<IDisposable> setSink)
        {
            if (this._period.HasValue)
            {
                Timer.TimerImpl timerImpl =
                    new Timer.TimerImpl(this, observer, cancel);

                setSink(timerImpl);
                return timerImpl.Run();
            }

            ...
        }
    }
}

Couple this fact with the fact that in the Subscribe method of my custom observable, I was doing this:
public IDisposable Subscribe(IObserver<int> observer)
{
    if (_completed)
    {
        ...
    }
    else
    {
        return _innerObservable.Subscribe(observer);
    }
}

I can make this observable hot without using the Publish and Connect or RefCount operators if I channeled all observation through an internal observer like so:
using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Reactive.Linq;

namespace ObservableNumberGenerator.ObservableImplementationReliesOnOperator.Hot
{
    public class RandomNumbers : IObservable<int>, IDisposable
    {
        protected Random _random = null;
        protected int _maxNumbersToGenerate;
        protected int _startAfterMilliseconds = 1000;
        protected int _generateEveryMilliseconds = 1000;

        protected List<IObserver<int>> _observers =
                            new List<IObserver<int>>();

        protected IObservable<int> _innerObservable = null;
        protected IDisposable _innerSubscription = null;
        protected bool _completed = false;
        private bool disposedValue = false;

        public RandomNumbers(int maxNumbersToGenerate,
            int startAfterMilliseconds = 1000, int generateEveryMilliseconds = 1000)
        {
            _maxNumbersToGenerate = maxNumbersToGenerate;
            _startAfterMilliseconds = startAfterMilliseconds;
            _generateEveryMilliseconds = generateEveryMilliseconds;

            _random = new Random();

            _innerObservable = Observable
                .Timer(
                  TimeSpan.FromMilliseconds(_startAfterMilliseconds),
                  TimeSpan.FromMilliseconds(_generateEveryMilliseconds))
                .Select(v => GenerateNumber())
                .Take(_maxNumbersToGenerate);

            _innerSubscription =
                _innerObservable.Subscribe(OnNext, OnError, OnCompleted);
        }

        protected virtual void OnCompleted()
        {
            _completed = true;

            foreach (var observer in _observers)
                observer.OnCompleted();
        }

        protected virtual void OnError(Exception ex)
        {
            _completed = true;

            foreach (var observer in _observers)
                observer.OnError(ex);
        }

        protected virtual void OnNext(int value)
        {
            foreach (var observer in _observers)
                observer.OnNext(value);
        }

        protected virtual int GenerateNumber()
        {
            return _random.Next();
        }

        public IDisposable Subscribe(IObserver<int> observer)
        {
            if (observer == null) throw new ArgumentNullException("observer");

            _observers.Add(observer);

            if (_completed)
            {
                observer.OnCompleted();
            }

            return Disposable.Empty;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _innerSubscription.Dispose();
                }

                disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}

Note to anyone thinking of doing this:
All my examples are just practice stuff, their purpose being to educate myself about the inner workings of Rx.
As Enigmativity rightly points out, one must not implement any observable this way in production code.
For one, none of the observers I have in my List<IObserver<T>> nor the _innerObserver are safe observers. Inside the Rx source, they convert every observer we pass into a safe observer that has try/finally clauses in every OnNext, OnError and OnCompleted implementation that safeguards against exceptions. For details have a look at the source code of the System.Reactive.SafeObserver<TSource> class and the System.Reactive.AnonymousObserver<T> class.
Comment: You're basically re-implementing `Publish`.
Comment: Yes, you are right. And also just the plain `Subject` although both `Publish` and `Subject` are thread-safe while my code is not. In other words, a thread might be inside `OnNext` while another might have already disposed off all active subscriptions / disposables.
Comment: I don't have anything against the downvote but I would really love it if you could please tell me what it is that is so off in my code to bug you off? I really just want to learn. Please do not think I am revolting against the downvote. Not at all. What is so fundamentally wrong with my question and answer? It would help me to know.

Would this observable be hot?


Is there a way to get track IDs of the tracks in a Spotify playlist using the Spotify JAVA API?

Question: I've been using the Java wrapper for the Spotify API. I have been successful in retrieving the required playlist but I'm not able to get the track IDs of the tracks in the playlist.
Here is the code I'm using to get the playlist items.
playlistID = "37i9dQZF1DWXLeA8Omikj7";

        getPlaylistsItemsRequest = spotifyApi.getPlaylistsItems(playlistID).build();

        Paging<PlaylistTrack> playlistTrackPaging = getPlaylistsItems_Sync();
        PlaylistTrack[] items = playlistTrackPaging.getItems();

        System.out.println(items.length);
        for (int i = 0; i < items.length; i++) {
            System.out.println(items[i].getTrack().toString());
        }

The above code gives output in this format:
com.wrapper.spotify.model_objects.specification.Track@6c40365c

The alphanumeric in the end unfortunately isn't the track ID.
The PlaylistTrack object doesn't seem to have any way to get the track ID. Anyone know how I can get the track IDs?
Been struggling with this for a while now. Thanks!
Comment: Please always specify the version of a library so that people can help you easily :)
Comment: Also, see [CONTRIBUTING.md#your-questions](https://github.com/thelinmichael/spotify-web-api-java/blob/master/CONTRIBUTING.md#your-questions), and tag your questions regarding this API wrapper on this StackOverflow with `spotify-web-api-java`.
Answer: Yes
Of course that's possible! :)
Since v6.0.0-RC1 of spotify-web-api-java the PlaylistTracks, which are returned by your request, now contain an IPlaylistItem instead of a simple Track due to changes related to the new podcasts API, which made endpoint return types depend on the request's context.
The current solution is to cast the items to their expected type. In your example, the println within the for-loop should look like this:
System.out.println(((Track) items[i].getTrack()).getId());

Depending on incoming pull requests, this could be improved in the future though: see the discussion in issue #201.


Downloaded Excel showing blank after Microsoft's security update

Question: I have exported table values to excel file through GridView using below C# code.
Response.ContentType = "application/vnd.xls";

Response.AddHeader("content-disposition","attachment;filename="+filename+".xls");

It was working well until recent security update from Microsoft [security update for microsoft excel 2010 kb3115322].
After the update, I am unable to view the content of Excel file. It is showing blank excel.
After uninstalling the update I can view the Excel but I need a solution through C# code.
Thanks in advance.
Comment: done any basic debugging, like opening the xls file in notepad to see what's in there? maybe Excel has nothing to show, because the file's empty.
Comment: save the thingy on disk see if there you can open it, on the other hand what has excel update to do with your exported file, you are returning a file as response, are you using Microsoft.Office.Interop.Excel?
Answer: Yes due to Microsoft new security update issue is rising to current excel files format. So for solving and for a quick solution you should make csv (comma separated file) instead of xls so excel application will open the csv by ',' seperator.
Note : I faced this issue in my Php application , and I solved by making xls file with PHPExcel library.I hope you may find something like PHPExcel for C# as well.
Thanks. Feel free to comment.
Comment: Yes, I was able to open when I changed the format to .csv file. But it was not in proper format(alignment and look). It would be great if there is any solution without changing file format.
Comment: By changing only file extension it will not work just change your code so that it makes the file in csv format lkie

id,name,city
1,Mahamadali,Palanpur
2,ABC,XYZ

And then it will open in proper format.
Answer: I run into the same problem. My solution was to rewrite all Excel exports with ExcelPack. And I used XLSX and no longer XLS.
just in case rewriting is an option for you.
https://excelpackage.codeplex.com/
ExcelPackage package = new ExcelPackage();
ExcelWorksheet ws = package.Workbook.Worksheets[1];

//header
ws.Cells[1, 1].Value = "Column1";
ws.Cells[1, 2].Value = "Column2";
ws.Cells[1, 3].Value = "Column3";
ws.Cells[1, 4].Value = "Column4";
ws.Cells[1, 5].Value = "Column5";

//content
int i = 1;

foreach (Item item in list)
{
    i++;

    ws.Cells[i, 1].Value = item.Prop1;
    ws.Cells[i, 2].Value = item.Prop2;
    // format datetime
    ws.Cells[i, 3].Value = item.Prop3.ToString("yyyy-MM-dd");
    ws.Cells[i, 4].Value = item.Prop4;
    ws.Cells[i, 5].Value = item.Prop5;
}

using (var memoryStream = new MemoryStream())
{
    response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    response.AddHeader("content-disposition", $"attachment; filename=Filename.xlsx");
    package.SaveAs(memoryStream);
    memoryStream.WriteTo(response.OutputStream);
    response.Flush();
    response.End();
}


How to delete buttons in the Markitup toolbar

Question: I am using Markitup. All I want is the paragraph button on the toolbar.
Anyone know how to delete the other buttons?
Answer: Edit the file set.js in markitup/sets/default. Also you can specify the settings file to use with: $("#mark").markItUp(mySettings); where "mySettings" is the set.js file you want to use
Answer: Find the file set.js and edit mysetting to include only what you need
Comment: mysetting is the default name inside set.js


Missing \begin{document}. \chapter{E Latex new blank page

Question: I started to use Latex to write my notes and I've been having some problems when I start a new chapter or blank page
\chapter{ECS, Lambda, Batch, Lightsail}
\section{ECS}
\begin{enumerate}
\item first time
\end{enumerate}

and this is my main
\documentclass[a4paper,12pt]{book}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage[margin=1.0in]{geometry}
\begin{document}

\author{José Santiago Molano Perdomo}
\title{Aws Cloud Practicioneer}
\date{}
\let\cleardoublepage\clearpage
\frontmatter
\maketitle
\tableofcontents

\mainmatter
\include{./TeX_files/chapter01}
\include{./TeX_files/chapter02}
\include{./TeX_files/chapter03}
\include{./Tex_files/chapter04}
\include{./Tex_files/chapter05}
\include{./Tex_files/chapter06}
\include{./Tex_files/chapter07}
\include{./Tex_files/chapter08}
\backmatter
% bibliography, glossary and index would go here.

\end{document}

I get this error when I try compile chaper 08
Undefined control sequence. \chapter
Missing \begin{document}. \chapter{E
Undefined control sequence. \section
Emergency stop.
Overfull \hbox (20.0pt too wide) in paragraph

Comment: You don't compile the individual chapters, only the main file
Answer: The character é in the author name is invalid to UTF-8. Please change to \'{e}
Comment: No, no, no! The document loads `\usepackage[utf8]{inputenc}` and even if it would not this is nowadays default of up-to-date tex installations! Also the error message is totally different.


Meaning of:" un poco vivace ma cantabile"

Question: I play Sonata no 3 of Johann Quantz for flute,
in the last part of this sonata, The directive is "un poco vivace ma cantabile".
I understand that the literal meaning of this is:
"A little lively but cantabile"
but I'm not sure what "cantabile" is and in what way should I play it and what does it mean in terms of the tempo of the piece
Comment: Cantabile means in a singing style.
Answer: Push the tempo slightly, but make it sing. Don't rush the piece, just make it sound relaxed but moving, and at the same time keep it singing. Difficult to explain, and maybe difficult to play in that way, but move it along, without making it sound rushed.
Comment: To be brutal, I would not use a metronome for this.It's too mechanical, and the sort of playing needed comes from inside you, not from  a little ticking thing that tells you how fast to play.
Comment: ok - I'm starting to understand that - if you need to set the tempo on the metronome for this style - Would you set it to 80 bpm?
Comment: @ErezLieberman You can use a metronome to give you some ideas about tempo, but as Tim says, don't stick religiously to it. A metronome will also tell you if your basic tempo is consistent in different parts of a piece, if you suspect that you are playing one section slower or faster than another without realizing it.


Compiler failed with error code - missing assembly found, but why is it missing

Question: After analysis, I have the following error:
C0150004    STATUS_SXS_ASSEMBLY_NOT_FOUND

I went through the entire list of files called by the compiler (ie. C:\Windows\SysWOW64\inetsrv> "C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe"...
The only file that didn't exist is in bold

/R:"C:\Windows\assembly\GAC_MSIL\System.ServiceModel\22.214.171.124__b77a5c561934e089\System.ServiceModel.dll" /out:"C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\applications_my_app\e34a7fe0\b4388432\en\App_GlobalResources.snrifx3y.resources.dll" /D:DEBUG /debug+ /optimize-

In DEV and TEST, the corresponding file exists.
This site is .Net 2.0, Classic App Pool.
I've compared as much as I can between the environments where this works, but can't seem to find anything that would hint at why this isn't working in PROD.
Answer: The machine was seriously corrupted and had to be rebuilt.


Melhor desempenho em um sistema em WPF

Question: Como deixar um sistema em alta performance?
Seguir um padrão de projetos MVVM?
Eu tenho o seguinte XAML, mas quando eu executo ele trava na hora de passar o foco para outros textBox. Por que?
O meu sistema fica muito lento, não estou entendendo o porque.
<UserControl x:Class="Curriculos_3_Camadas.View.EmpresaView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
         xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
         mc:Ignorable="d"
         Width="auto" Height="auto" Background="White" d:DesignWidth="1232.5" d:DesignHeight="853">
<Grid Margin="0,0,0,77">

    <TextBlock Text="Código:" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="150,17,0,0"/>
    <TextBox Name="textEmpCodigo" VerticalAlignment="Top" HorizontalAlignment="Left" MinHeight="22" Height="15" Width="170" Margin="196,15,0,0"/>
    <TextBlock VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Text="F2" Margin="371,18,0,0" FontWeight="Bold" Foreground="Red"/>
    <TextBlock x:Name="labelUltimoCodigoEmpresa" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Margin="390,18,0,0" Width="177"/>
    <CheckBox x:Name="cbEmpresaInativa" Content="Empresa Inativa" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Margin="600,17,0,0" />

    <TextBlock Text="CNPJ / CPF:" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Margin="130,43,0,0"/>
    <TextBox Name="textEmpCnpjCpf" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" MinHeight="22" Height="15" Width="170" Margin="196,40,0,0"/>
    <TextBlock Text="Data de Abertura:" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Margin="390,43,0,0"/>
    <TextBlock x:Name="labelDataAbertura" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Margin="489,43,0,0" Width="111"/>

    <TextBlock Text="Razão Social / Nome:" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Margin="79,67,0,0"/>
    <TextBox Name="textEmpRSNome" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" MinHeight="22" Height="15" Width="560" Margin="196,65,0,0"/>

    <Rectangle VerticalAlignment="Top" HorizontalAlignment="Left" Width="1900" Height="25" Fill="#E8E8E8" Margin="0,115,-668,0"/>

    <TabControl Name="tabControl" Margin="150,115,0,38">

        <TabControl.Resources>

        </TabControl.Resources>

        <TabItem Name="tiDadosGeraisEmpresas" Header="Dados Gerais" FontSize="12" FontWeight="Bold" IsSelected="True" Margin="70,0,-80,-5" TabIndex="-67">
            <ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Margin="-72,0,2,-13">
                <Canvas Grid.Row="1" Height="655">

                    <TextBlock Text="Nome Fantasia:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="26" Canvas.Top="17"/>
                    <TextBox Name="textEmpNomeFantasia" VerticalAlignment="Top" HorizontalAlignment="Left" Width="290" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="15"/>
                    <TextBlock Text="Contato:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="448" Canvas.Top="17"/>
                    <TextBox Name="textEmpContato" VerticalAlignment="Top" HorizontalAlignment="Left" Width="240" MinHeight="22" Height="15" Canvas.Left="498" Canvas.Top="15"/>
                    <TextBlock Text="Site:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="784" Canvas.Top="17"/>
                    <TextBox Name="textEmpSite" VerticalAlignment="Top" HorizontalAlignment="Left" Width="240" MinHeight="22" Height="15" Canvas.Left="811" Canvas.Top="15"/>

                    <TextBlock Text="CEP:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="85" Canvas.Top="43"/>
                    <TextBox Name="textEmpCep" VerticalAlignment="Top" HorizontalAlignment="Left" Width="160" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="40"/>

                    <TextBlock Text="Código IBGE:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="329" Canvas.Top="43"/>
                    <TextBox Name="textEmpCodigoIbge" VerticalAlignment="Top" HorizontalAlignment="Left" Width="160" MinHeight="22" Height="15" Canvas.Left="403" Canvas.Top="40"/>
                    <TextBlock VerticalAlignment="Top" HorizontalAlignment="Left" Text="F2" FontWeight="Bold" Foreground="Red" Canvas.Left="568" Canvas.Top="43"/>
                    <TextBlock Text="Município:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="343" Canvas.Top="93"/>
                    <TextBox Name="textEmpMunicipio" VerticalAlignment="Top" HorizontalAlignment="Left" Width="210" MinHeight="22" Height="15" Canvas.Left="403" Canvas.Top="90"/>
                    <TextBlock Text="Bairro:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="75" Canvas.Top="93"/>
                    <TextBox Name="textEmpBairro" VerticalAlignment="Top" HorizontalAlignment="Left" Width="190" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="90"/>
                    <TextBlock Text="Estado (UF):" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="628" Canvas.Top="93"/>
                    <TextBox Name="textEmpUf" VerticalAlignment="Top" HorizontalAlignment="Left" Width="50" MinHeight="22" Height="15" Canvas.Left="696" Canvas.Top="90"/>

                    <TextBlock Text="Tipo de Logradouro:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="68"/>
                    <TextBox Name="textEmpTipoLogradouro" VerticalAlignment="Top" HorizontalAlignment="Left" Width="160" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="65"/>
                    <TextBlock Text="Logradouro:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="333" Canvas.Top="68"/>
                    <TextBox Name="textEmpLogradouro" VerticalAlignment="Top" HorizontalAlignment="Left" Width="210" MinHeight="22" Height="15" Canvas.Left="403" Canvas.Top="65"/>
                    <TextBlock Text="Número:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="644" Canvas.Top="68"/>
                    <TextBox Name="textEmpNumero" VerticalAlignment="Top" HorizontalAlignment="Left" Width="115" MinHeight="22" Height="15" Canvas.Left="696" Canvas.Top="65"/>
                    <TextBlock Text="Complemento:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="853" Canvas.Top="63"/>
                    <TextBox Name="textEmpComplemento" VerticalAlignment="Top" HorizontalAlignment="Left" Width="115" MinHeight="22" Height="15" Canvas.Left="936" Canvas.Top="60"/>

                    <TextBlock Text="Inscrição Estadual:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="118" Canvas.Left="12"/>
                    <TextBox Name="textEmpInscEst" VerticalAlignment="Top" HorizontalAlignment="Left" Width="190" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="115"/>
                    <TextBlock Text="Cód. Serv.:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="393" Canvas.Top="118"/>
                    <TextBox Name="textEmpCodServ" VerticalAlignment="Top" HorizontalAlignment="Left" Width="160" MinHeight="22" Height="15" Canvas.Left="453" Canvas.Top="115"/>
                    <TextBlock Text="Cód. Ativ.:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="638" Canvas.Top="118"/>
                    <TextBox Name="textEmpCodAtiv" VerticalAlignment="Top" HorizontalAlignment="Left" Width="355" MinHeight="22" Height="15" Canvas.Left="696" Canvas.Top="115"/>

                    <TextBlock Text="Inscrição Municipal:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="143" Canvas.Left="4"/>
                    <TextBox Name="textEmpInscMun" VerticalAlignment="Top" HorizontalAlignment="Left" Width="190" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="140"/>
                    <TextBlock Text="Regime Trib.:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="379" Canvas.Top="143"/>
                    <TextBox Name="textEmpRegTrib" VerticalAlignment="Top" HorizontalAlignment="Left" Width="598" MinHeight="22" Height="15" Canvas.Left="453" Canvas.Top="140"/>

                    <TextBlock Text="RNTRC:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="168" Canvas.Left="68"/>
                    <TextBox Name="textEmpRntrc" VerticalAlignment="Top" HorizontalAlignment="Left" Width="190" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="165"/>
                    <TextBlock Text="Tipo de Empresa:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="357" Canvas.Top="168"/>
                    <TextBox Name="textEmpTipoEmpresa" VerticalAlignment="Top" HorizontalAlignment="Left" Width="598" MinHeight="22" Height="15" Canvas.Left="453" Canvas.Top="165"/>

                    <TextBlock Text="CNAE - Classificação Nacional de Atividades Econômicas" Canvas.Left="113" Canvas.Top="195"/>

                    <TextBlock Text="Código:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="219" Canvas.Left="68"/>
                    <TextBox Name="textEmpCodigoCnae" VerticalAlignment="Top" HorizontalAlignment="Left" Width="100" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="216"/>
                    <TextBlock Text="Descrição:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="243" Canvas.Top="219"/>
                    <TextBox Name="textEmpDescCnae" VerticalAlignment="Top" HorizontalAlignment="Left" Width="644" MinHeight="22" Height="15" Canvas.Left="302" Canvas.Top="216" FontWeight="Normal"/>
                    <Button Name="btnAdicionarCnae" Content="Adicionar" Width="100" Canvas.Left="951" Canvas.Top="214" FontWeight="Bold" TabIndex="-76"/>
                    <DataGrid Name="dataGridCnae" Height="100" Canvas.Left="113" Canvas.Top="243" Width="938" FontWeight="Normal" IsReadOnly="True"
                              AutoGenerateColumns="False" GridLinesVisibility="All">

                        <DataGrid.Columns>
                            <DataGridTextColumn Binding="{Binding Path=codigo}" Header="Código" />
                            <DataGridTextColumn Binding="{Binding Path=descricao}" Header="Descrição" />
                        </DataGrid.Columns>

                    </DataGrid>

                    <TextBlock Text="Contatos" Canvas.Left="113" Canvas.Top="354"/>

                    <TextBlock Text="E-mail:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="378" Canvas.Left="68"/>
                    <TextBox Name="textEmpEmail" VerticalAlignment="Top" HorizontalAlignment="Left" Width="348" MinHeight="22" Height="15" Canvas.Left="114" Canvas.Top="375"/>
                    <TextBlock Text="Observações:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="485" Canvas.Top="378"/>
                    <TextBox Name="textEmpObs1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="386" MinHeight="22" Height="15" Canvas.Left="560" Canvas.Top="375" FontWeight="Normal"/>
                    <Button Name="btnAdicionarEmails" Content="Adicionar" Width="100" Canvas.Left="951" Canvas.Top="372" FontWeight="Bold" TabIndex="-73"/>
                    <DataGrid Name="dataGridEmails" ItemsSource="{Binding}"
                              AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top" Height="100"
                              Canvas.Left="114" Canvas.Top="414" Width="937" FontWeight="Normal" IsReadOnly="True" GridLinesVisibility="All">

                        <DataGrid.Columns>
                            <DataGridTextColumn Binding="{Binding Path=email}" Header="E-mail (s)" />
                            <DataGridTextColumn Binding="{Binding Path=obs}" Header="Observação" />
                        </DataGrid.Columns>

                    </DataGrid>

                    <TextBlock Text="Prefixo (99):" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Top="520" Canvas.Left="46"/>
                    <TextBox Name="textEmpPrefixo" VerticalAlignment="Top" HorizontalAlignment="Left" Width="100" MinHeight="22" Height="15" Canvas.Left="113" Canvas.Top="517"/>
                    <TextBlock Text="Telefones:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="243" Canvas.Top="520"/>
                    <TextBox Name="textEmpTelefones" VerticalAlignment="Top" HorizontalAlignment="Left" Width="160" MinHeight="22" Height="15" Canvas.Left="302" Canvas.Top="517"/>
                    <TextBlock Text="Observações:" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="Normal" Canvas.Left="485" Canvas.Top="520"/>
                    <TextBox Name="textEmpObs2" VerticalAlignment="Top" HorizontalAlignment="Left" Width="386" MinHeight="22" Height="15" Canvas.Left="560" Canvas.Top="517"/>
                    <Button Name="btnAdicionarTelefones" Content="Adicionar" Width="100" Canvas.Left="951" Canvas.Top="515" FontWeight="Bold" TabIndex="-69"/>

                    <DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top"
                              ItemsSource="{Binding}" Name="dataGridTelefones" Height="100" Canvas.Left="114" Canvas.Top="557"
                              Width="937" FontWeight="Normal" GridLinesVisibility="All" IsReadOnly="True">

                        <DataGrid.Columns>

                            <DataGridTextColumn Binding="{Binding Path=prefixo}" Header="Prefixo2" />
                            <DataGridTextColumn Binding="{Binding Path=telefone}" Header="Telefone2" />
                            <DataGridTextColumn Binding="{Binding Path=obs}" Header="Observação2" />
                        </DataGrid.Columns>

                    </DataGrid>

                </Canvas>
            </ScrollViewer>
        </TabItem>

    </TabControl>

    <WindowsFormsHost VerticalAlignment="Top" HorizontalAlignment="Left" Name="wfhSample" Grid.Row="0" Height="50" Width="186" Margin="862,10,0,0">
        <WindowsFormsHost.Child>
            <wf:PictureBox x:Name="picLetras"/>
        </WindowsFormsHost.Child>
    </WindowsFormsHost>
    <Image x:Name="imgCarregaCaptcha" HorizontalAlignment="Left" Height="16" Margin="1051,15,0,0" VerticalAlignment="Top" Width="17" />
    <TextBlock Name="labelCaptcha" Text="Digite os caracteres acima e pressione Enter:" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="0" Foreground="Red" Margin="862,65,0,0"/>
    <TextBox Name="textCaracteres" VerticalAlignment="Top" HorizontalAlignment="Left" MinHeight="22" Height="15" Width="260" Margin="862,86,0,0"/>

    <Rectangle Fill="#E8E8E8" Height="33" VerticalAlignment="Bottom" Width="auto" Margin="0,0,0,-2" />
    <Button x:Name="btnSalvarEmpresa" Content="Salvar (F9)" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="100" Margin="198,0,0,2"/>
</Grid>

Answer: A pergunta é um tanto ampla, não tem um problema específico mas vou tentar ajudar, ainda que de forma genérica.
O WPF realmente tem uma série de detalhes que se não forem observados gerará problemas de performance. O mecanismo é complexo e não é fácil entender todas implicações. Além disto os defaults não são ideias para gerar boa performance.
Eu não possuo conhecimento específico mas existe bastante material sobre o assunto, vou listar alguns. Você precisará ler todas, procurar novas fontes, estudar muito o assunto e perfilar bastante até chegar em um bom resultado.
A primeira coisa que precisa conhecer é a ferramenta de análise de performance do WPF. Outra ferramenta.
Esse artigo começa dar uma boa explicação sobre o problema.
Aqui tem dicas para melhorar a performance.
Outras maneiras que ajudam melhorar a performance.
Mais uma lista de dicas.
Considerações importantes de como melhorar a inicialização.
Um dos artigos que mais gosto sobre o assunto.
Mais um artigo interessante.
O fato de usar o MVVM não ajuda nada, pode até atrapalhar em alguns casos, mas nada significativo. Claro que se usar um padrão ruim ou fizer sem padrão algum pode atrapalhar.
Comment: Mto obrigado bigown

Melhor desempenho em um sistema em WPF


Why are django-q scheduled tasks delayed randomly?

Question: I'm finding that django-q is not executing tasks I schedule on time. There can be delays of several seconds to almost a minute.
I schedule a task like so:
from django.utils import timezone
from django_q.models import Schedule

def schedule_auction_deadlines(self):
    now = timezone.now()
    if self.deadline:
        name = "end_phase_%d" % self.id
        Schedule.objects.filter(name=name).delete()
        if now < self.deadline:
            Schedule.objects.create(name=name, func="myapp.views.end_phase", args=str(self.id), next_run=self.deadline, schedule_type=Schedule.ONCE)

And here is my configuration in the settings.py file:
Q_CLUSTER = {
    'name': 'myproj',
    'label': 'Django Q',
    'timeout': 30,
    'catch_up': True,
    'guard_cycle': 1,
    'redis': os.environ.get('REDIS_URL', 'redis://localhost:6379'),
}

From the docs it seemed like guard_cycle might be relevant, but I've already got it set at the minimum setting.
What could be causing these delays?
Answer:
I'm finding that django-q is not executing tasks I schedule on time. There can be delays of several seconds to almost a minute.

According to the docs, the scheduler is only checked every thirty seconds, so it's not surprising if it takes 30-40 seconds.

From the docs it seemed like guard_cycle might be relevant, but I've already got it set at the minimum setting.

Guard cycle actually defaults to 0.5, so you have it set higher than the default. But the scheduler interval is implemented a little strangely, because setting a lower guard time can actually increase the amount of time between scheduler checks.
The important code is in Sentinel.guard:
def guard(self):
    logger.info(
        _(
            f"{current_process().name} guarding cluster {humanize(self.cluster_id.hex)}"
        )
    )
    self.start_event.set()
    Stat(self).save()
    logger.info(_(f"Q Cluster {humanize(self.cluster_id.hex)} running."))
    counter = 0
    cycle = Conf.GUARD_CYCLE  # guard loop sleep in seconds
    # Guard loop. Runs at least once
    while not self.stop_event.is_set() or not counter:
        # Check Workers
        [...]
        # Check Monitor
        [...]
        # Check Pusher
        [...]
        # Call scheduler once a minute (or so)
        counter += cycle
        if counter >= 30 and Conf.SCHEDULER:
            counter = 0
            scheduler(broker=self.broker)
        # Save current status
        Stat(self).save()
        sleep(cycle)
    self.stop()

So the scheduler is not called every time through the loop. It is only called every time counter is greater than 30, and counter counts up by guard_cycle each time. If you set guard_cycle to 0.001, the guard would only call the scheduler once every 30,000 times through the loop, which would take much more than 30 seconds, due to all the other work the guard does in checking the health of the cluster.
Since the scheduler interval is hard-coded, I don't see what you could do besides modify Django Q or call the scheduler yourself. The docs don't say anything about how to do this.


Bootstrap 4 - container class and rounded corners?

Question: How can I have achieve a div which has a container class from Bootstrap but also has rounded corners?

Approver:

When I use the above code, my corners still appear to be square however Bootstrap 4 documentation states that the "rounded" class should take care of rounded corners?
Comment: Shame that people upvote the answer so much and not the question.
Answer: As per the documentation, The rounded class in bootstrap does the following:
.rounded {
    border-radius:.25rem!important
}

You should be able to use it on a container.
However, keep in mind that unless the background color is of a different color than the container (or unless it has a differently colored border), it won't be visible.
Here's a snippet:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

  This rounded container has no background color.

  This rounded container has a background color.

  This rounded container has no background color, but it has a black border.

Answer: I arrived here trying to add rounded corners to a grid of images. For anyone doing the same:

or

Answer: You can use css aspect-ratio property:
aspect-ratio: 1 / 1;

Source


Flask Application Alternative File Structure (app.py, templates folder)

Question: I am building a simple flask application where the file structure is

project/

app.py
templates/
static/

css/

style.css

js/

code.js

With this structure the below code works completely fine.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def root():
    return(render_template('html/index.html'))
if(__name__ == '__main__'):
    app.run(debug=True)

But I want to keep all my python code (in this case app.py) to be inside a package called server/ and then if required create some sub-packages inside that package (server/).
With that, the project file structure would be like below

project/

server

app.py

templates/
static/

css/

style.css

js/

code.js

But with this file structure I want to know what the routing path needs to be, so that I can link my html file in the template/html folder.
@app.route('/')
def root():
    return(render_template('html/index.html'))

Answer: Provide a relative or an absolute path when initializing the Flask object:
app = Flask(__name__, template_folder="../templates")


Does the meaning of $dx^2$ in $(\frac{dy}{dx^2})$ and $(\frac{d^2y}{dx^2})$ differ

Question: Am I right in thinking that in $\frac{dy}{dx^2}$ (The derivative of y with respect to $x^2$), $dx^2$ means $d(x^2)$, while in $\frac{d^2y}{dx^2}$, $dx^2$ means $(dx)^2$?
That what is on top of the bar($\frac{ }{ }$) determines the meaning of $dx^2$?
Comment: $dx^2$ means $d(d(x))$, not $d(x^2)$. So both $dx^2$ are same I think.
Comment: @AnikBhowmick - if your interpretation were correct then $\frac{dy}{dx^2}$ might not be meaningful
Comment: Indeed "$\frac{dy}{dx^2}$" looks particularly confusing.  Write "$\frac{dy}{dz}$ where $z=x^2$" instead
Answer: You seem to have encountered a case of rather confusing notation.
If $y=y(x^2)$ is a function of $x^2$, you can of course differentiate it with respect to the argument. However, you should write that as
$$\frac{\text{d} y}{\text{d}\!\left(x^2\right)}\quad \text{or} \quad \frac{\text{d} y(x^2)}{\text{d}\!\left(x^2\right)}\quad \text{or} \quad \frac{\text{d}}{\text{d}\!\left(x^2\right)} \, y(x^2) $$
precisely to avoid the confusion you mentioned. Writing just $\text d x^2$  in the denominator is bound to lead to misunderstandings, in particular if the argument of the function is not given and you would assume it to be $y(x)$.
On the other hand, in $\frac{\text d^2y}{\text d x^2}$, you should not think of numertaor and denominator as separate entities, but rather consider the expression as
$$\frac{\text d}{\text d x}\left(\frac{\text d}{\text d x}\,y\right)=\left(\frac{\text d}{\text d x}\right)^2 y\,,$$
i.e. the square of the derivative operator $\frac{\text d}{\text d x}$ acting of the funtion $y$, which presumably is intended as $y(x)$.


on the continuity of matrix norms

Question: Consider $f:\mathbb R^{n\times n}\to \mathbb R$ given by  $f(A)=||A||$. where $A$ is a matrix e $||-||$ is a matrix norm.  On the domain, consider any other matrix norm $||-||'$.

Prove that $f$ is a continuous map, namely that for every $\epsilon>0$ there exists $\delta>0$ such that $abs(||A||-||B||)<\epsilon$ whenever $||A-B||'<\delta$.

This is my proof for the case when $||-||=||-||'$. From the inverse of the triangle inequality we have $abs(||A||-||B||)\le ||A-B||$, so if we choose $\delta=\epsilon$ we get the thesis.
For the general case probably one should use the equivalence between matrix norms but I can't see how.
I would like to know if my partial proof is correct and how to prove the general case. Thank you very much.
Answer: Yes, your proof is correct, so far.
Any two norms on a finite-dimensional vector space are comparable. (Use compactness of the unit sphere and continuity of norm.) Thus you'll have $c>0$ so that $\|X\|\le c\|X\|'$, and this should do it.
Answer: Your argument is correct.
For any other norm, since $\|A-B\|\le C\|A-B\|'$ for some $C>0$ (because any two norms are equivalent), you get
$$
\bigl|\|A\|-\|B\|\bigr|\le \|A-B\|\le C\|A-B\|'<C\delta.
$$
So you can take $\delta=\epsilon/C$.

on the continuity of matrix norms


Converting a pandas multirow dataframe to a single row combining the rows and columns

Question: I have 100 csv files each of which when read by pandas dataframe is like below:

gyrus
GW
WM

FlRt
1.2
1.0

FlLt
1.4
1.0

TlRt
1.3
1.1

TlLt
1.4
1.2

I need to convert programatically this to the form as below

FlRt GM
FlRt WM
FlLt GM
FlLt WM
TlRt GW
TlRt WM
TlLt GM
TlLt WM

1.2.
1.0.
1.4.
1.0.
1.3
1.1
1.4.
1.2.

so that I can merge all the 100 files to form a large single dataframe
Thanks in advance
Answer: Pivot your dataframe:
<code>out = df.set_index('gyrus').stack().to_frame().T
out.columns = out.columns.to_flat_index().str.join(' ')

# Output
print(out)
   FlRt GW  FlRt WM  FlLt GW  FlLt WM  TlRt GW  TlRt WM  TlLt GW  TlLt WM
0      1.2      1.0      1.4      1.0      1.3      1.1      1.4      1.2
</code>
Comment: that solved my problem !!! thanks a ton.


Downloads not showing on iTunes Connect?

Question: I released an update for my app yesterday that hasn't been updated in over a year. I know for a fact that a few of my friends (who did not and never did have the previous version installed) installed my app throughout the day yesterday. But, iTunes connect is showing "0" units for April 4 (yesterday) and the past week for that matter.
I'm asking because I remember the last time I released this app the number of downloads ( or units: this is the same thing right?) showed up accurately the next morning. It also showed the correct units number for another app I recently released. Is there some sort of delay that's new? I just want to make sure nothing is set up incorrectly. I'm also using admob if that matters, and impressions/clicks are showing up fine there.
Thanks!
Answer: You might need to wait one day or two to see the results. There is a delay.
Answer: You can find static on iTunesConnect portal
Select sales & Trends.


Filter out script tags in a view but leave link (from user input)

Question: Users of my site will enter their twitter widget code into a field for their profile:
Tweets by @username

In a view I need to display the link exactly how it was entered, but not display anything in the script tags.
Ive tried making the node field both plain text and filtered html (which allows links). Ive also tried the default view and with 'Strip HTML tags' selected but  allowed. In every instance the link prints out as I want it to. The script tags however are removed but the content is printed as plain text (see below).
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

How can I stop this from showing?
Comment: I find the formatting of the code (2x) in this question hard to read. Can you think of reformatting it a bit so that you don't have to do all that scrolling right? FYI: that "might" be part of the reasons of the 2 downvotes, and after you did such edit, those downvoters "might" want to undo their downvotes ... Just a suggestion ... Pls add an extra comment to "ping" me after you eventually did so, ok?
Answer: I believe, you can use https://drupal.org/project/views_php to add a custom PHP code, where you can manipulate on the data that user has added.
If you are saving this field somewhere and is available as a field in views too, add the field, and select "exclude from display" option. Now, add a custom php code field and take the input from the field above, extract URL from it and return the same.


If a differentiable real function has negative derivative when it intersects the x-axis, then it crosses the x-axis at most once?

Question: $\textbf{Question:}$ Let $f: \mathbf{R}\rightarrow \mathbf{R}$ be a differentiable real function. Suppose we know $f'(x) <0$ whenever $f(x)=0$. Prove that there is at most a unique $x$ such that $f(x)=0$.
To me, the claim seems very intuitive: if there are multiple, say two, intersections with the $x$-axis, $\underline{x}$ and $\overline{x}$, then there would be another point $x_1 \in (\underline{x}, \overline{x})$ such that $f(x_1)>0$, which would then lead to another point $x_2 \in (\underline{x}, x_1)$, such that $f(x_2)=0$ and $f'(x_2) >0$, a contradiction.
However, I have a hard time making these arguments formal. I tried intermediate value theorem and mean value theorem, but I couldn't get anywhere. Appreciate any help and guidance!
Answer: If there are two such points, say $x_1$ and $x_2$, then you can apply the MVT across those two points, meaning that $\exists c \in (x_1, x_2)$ such that $f'(c) = \frac{f(x_2) - f(x_1)}{x_2 - x_1}$.
Is there a problem with that statement though?
Comment: That's where I'm stuck... I don't see a problem with that statement, since $f(c)\ne 0$ so $f'(c)$ can be anything?
Comment: You don't need anything about f(c). What's f(x_2)-f(x_1)?
Comment: $f(x_2)-f(x_1)=0$ which implies $f'(c) =0$. But I don't think this is a contradiction, because we only require $f'$ to be negative when $f=0$.
Comment: Arg, I think I misread your question, so my answer is, indeed, completely useless.
Answer: If there are two points, $x_1\lt x_2$ where $f(x)=0, f'(x)\lt 0$, just above $x_1$ we have $f(x) \lt 0$ while just below $x_2$ we have $f(x) \gt 0$.  Then the intermediate value theorem tells you there is a point where $f(x)=0$ crossing from negative to positive, so $f'(x) \gt 0$, or staying at $0$ so $f'(x)=0$.  To justify the first point, use Taylor's theorem with the error term to show you can get close enough to the root for the first derivative to dominate any other term.
Answer: Let's suppose $f(a) =f(b) =0$ with $a<b$. Since $f'(a) <0$  there is an interval $(a, a+h]$ with $a+h<b$ where $f$ is negative. Let $c$ be first zero of $f$ in $[a+h, b] $.
We have thus found two consecutive roots $a, c$ of $f$ such that $a<c$ and $f$ does not vanish in $(a, c) $. By intermediate value theorem it maintains a constant sign there and is thus negative in $(a, c) $. But this clearly contradicts $f'(c) <0$ as $f'(c) <0$ implies an interval of type $[c-k, c) $ where $f$ is positive.
Comment: @Paramananda Singh You may not find a first root or two consecutive root because the set of zeroes of $f$ may be dense like $\mathbb Q$.
Comment: @KishalaySarkar: well do you see why I have mentioned that $f$ is negative on $(a, a+h] $? This ensures that $a$ is an isolated zero and there is next one. If $D$ is the set of zeroes of $f$ and $D$ has some limit point $p$ then $p$ is also a zero of $f$ and $f'(p) =0$. Here the crucial thing is that $f'$ does not vanish at roots of $f$ and that allows us to have isolated zeroes.
Comment: @KishalaySarkar: you may try to view it in this manner. Let $A$ be the set of zeroes of $f$ in $[a+h, b] $. Then $b\in A$ so that $A$ is non-empty, bounded and closed. It follows $A$ has a minimal element.
Comment: Oh...sorry..I did not see very thoroughly...
Comment: @KishalaySarkar: no need for sorry! Once in a while we may lose track of minor details. And anyway I had not mentioned the full details and thought that it would be obvious. But now the comments should help clear these things for future readers.


Python algorithm to generate set of teams where players are with other given players an equal number of times

Question: I'm looking to write a python programme that takes as input n (a number of players) and splits them into two teams of equal size for a number w (weeks) such that each player is with any other given player an equal amount of the time.
e.g. 6 players over 4 weeks generates the 4 team pairings ((1,2,3)(4,5,6) , (1,3,5),(2,4,6) , (1,5,6),(2,3,4) , (1,4,6),(2,3,5)) such that 1 is with 2 as equally as possible as 1 is with 5 or any other pair of players.
There is no distinction between the first and second team and both teams are always of equal size.
Comment: An algorithm should be language agnostic.
Answer: basically what I did is used a library called itertools to calculate all permutations of teams and just checked whether they have been picked already or not. If you have any questions just ask.

list_of_players = ["Mark", "Willy", "Josh", "Rob"]
N = len(list_of_players)
good = []
all = []
for perm in list(permutations(list_of_players)):
    if sorted(perm[:N//2]) not in all and sorted(perm[N // 2:]) not in all:
        good.append(tuple([sorted(perm[:N // 2]), sorted(perm[N // 2:])]))
        all.append(sorted(perm[:N // 2]))
        all.append(sorted(perm[N // 2:]))

for i in range(len(good)):
    print("week:",i+1,good[i])

Output:
week: 1 (['Mark', 'Willy'], ['Josh', 'Rob'])
week: 2 (['Josh', 'Mark'], ['Rob', 'Willy'])
week: 3 (['Mark', 'Rob'], ['Josh', 'Willy'])


Pass views filter from URL

Question: How do you pass a filter value by url in drupal 8?
On my website I have a view with a select to filter the results. This result is based on taxonomy term.
I have 4 options, All, badkamerrenovatie, elektriciteit and verwarming.
How can I set the filter by url so that I directly have a filtered list if people click on a link related to the taxonomy term. For example if people are on page elektriciteit and click trough to realisatie they see the filtered list and don't have to choose from the select.
Answer: This can be done using Contextual Filters under Advanced Settings of View Edit Page. You can add URL parameters as filters in it. This link will help you in detail
Thanks
Comment: Ok. What url structure I need to use then when the filter is set to get the correct result? for ex. /realisaties?badkamerrenovatie or /realisaties%badkamerrenovatie ...
Comment: This link will help you how to pass url parameters: https://drupal.stackexchange.com/questions/65525/how-to-pass-views-contextual-filter-via-url

Pass views filter from URL