JJWT / Jackson alter the ObjectMapper used

Question: For a project I am working on, I am required to use Spring Security and JSON Webtokens as provided by the library io.jsonwebtoken (jjwt). One of the claims I am required to add to my generated token is the following entity (simplified to illustrate the problem):
@Entity
public class MyEntity {
    private String name;
    private LocalDateTime ldt;
}

This works, but the resulting webtoken is serialized as following:
{
  "sub": "firstname.lastname@example.com",
  "exp": 1523659655,
  "entity": {
    "name": testname,
    "ldt": {
      "hour": 0,
      "minute": 37,
      "dayOfMonth": 12,
      "dayOfWeek": "THURSDAY",
      "dayOfYear": 102,
      "year": 2018,
      "month": "APRIL",
      "monthValue": 4,
      "second": 38,
      "nano": 569000000,
      "chronology": {
        "calendarType": "iso8601",
        "id": "ISO"
      }
    }
  }
}

This might not seem like a problem, but it is in fact a problem when later on I am required to map it to an instance of MyEntity again. After some reading online I figured that I need to change the configuration of the ObjectMapper, to change the configuration options (toggle the WRITE_DATES_AS_TIMESTAMPS-flag to false). However, I cannot alter the configuration of the ObjectMapper used by jjwt as it's constructed like this (source of jjwt):
public class DefaultJwtBuilder implements JwtBuilder {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    ...
}

Another option I found online was to put the following line in my application.properties file:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

Yet to no avail, the ObjectMapper used by jjwt seems to ignore these properties.
What would I do to accomplish my goal?
Answer: Jjwt documentation states that (from version 0.10.0 and on) you can inject your own ObjectMapper with a specific compile dependency and implementing the injection as follows:
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.10.5</version>
    <scope>compile</scope>
</dependency>

... then add the mapper to the JwtBuilder:
ObjectMapper objectMapper = getMyObjectMapper(); //implement me
String jws = Jwts.builder()
    .serializeToJsonWith(new JacksonSerializer(objectMapper))
    // ... etc ...

as documented here
Comment: For those wondering how to implement the `getMyObjectMapper()`, this depends on how you manage dependency injection. If you're using plain old Java, a `return new ObjectMapper();` would do (with desired configuration); if you're using Spring, maybe that method returns an autowired instance. That's beyond the point of this question.
Answer: I fixed it by overriding the DefaultJwtBuilder, like this:
public class CustomJwtBuilder extends DefaultJwtBuilder {
    private static final ObjectMapper mapper = new Jackson2ObjectMapperBuilder()
        .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .modulesToInstall(new JavaTimeModule())
        .build();

    @Override
    protected byte[] toJson(Object object) throws JsonProcessingException {
        return mapper.writeValueAsBytes(object);
    }
}

And then creating the token like this
String token = new CustomJwtBuilder()
            .setSubject(..)
            .setExpiration(...)
            .compact();

Comment: I understand this answer was provided before JJWT 0.10.0 was released, but after 0.10.0, tete's answer on this page is the recommended solution.  JJWT users should follow that one.  Cheers!
Comment: I know, I said "I understand this answer was provided before JJWT 0.10.0 was released" :).  But thanks for updating the answer! ;)
Comment: @LesHazlewood I have accepted that answer; it was not possible yet when I originally asked the question.
Answer: Normally It happens when the compiler Unable to discover any JSON Serializer implementations on the classpath. Include the following jjwt jackson dependancy and rebuild the project. It solved my issue.
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.10.5</version>
    <scope>compile</scope>
</dependency>


Fastest sum over margins in N-dimensional array: apply(X, MARGIN=c(1,2), sum)

Question: I have a 4-dimensional array and I need to compute the sum over two of its dimensions. I see that apply is surprisingly slow.
I have tried the compiler library, but speed barely improves:
library(compiler)

X <- array(2, dim=c(1000,20,10,125))

suma <- function(X){
  apply(X, MARGIN=c(1,2), sum)
}

suma.cmp <- cmpfun(suma)

benchmark(suma.cmp(X), suma(X), replications = 50)

#       test replications elapsed relative user.self sys.self user.child
#1 suma.cmp(X)           50  24.616    1.000    24.164    0.424          0
#2     suma(X)           50  24.892    1.011    24.440    0.416          0

I would give Rcpp a try, but RcppArmadillo has no 4-dimensional arrays as far as I know.
How can I make this computation (apply(X, MARGIN=c(1,2), sum)) as fast as possible?
Answer: rowSums is about 15x faster. It pretty quickly goes to C, so I think it will be difficult to improve on it.
microbenchmark(
  apply = suma(X),
  rowsum = rowSums(X, dims = 2),
  times = 10
)
# Unit: milliseconds
#    expr       min        lq      mean    median        uq       max neval cld
#   apply 692.14893 818.67450 828.66410 829.47926 874.23754 885.36019    10   b
#  rowsum  48.39865  49.85822  51.37486  51.09379  52.04339  56.29224    10  a

identical(rowSums(X, dims = 2), suma(X))
# [1] TRUE

Comment: No. See the documentation in `?rowSums`: *"dims: For row\*, the sum or mean is over dimensions dims+1, ...; for col\* it is over dimensions 1:dims."* You **can** use `aperm` to permute the dimensions, making whatever dimensions you want to sum over contiguous.
Comment: Thanks @Gregor. Can we sum over non-contiguous dimensions? `apply(X, MARGIN=c(1,3), sum)`


problema ao executar php

Question: Olá, estou com o seguinte problema:
Eu criei um input e os valores que forem digitados nele, ao ser pressionado um botão devem ser mandados para um array no meu ".php".
O problema é que além de não estar capturando os valores, quando eu aperto o botão ele simplesmente me redireciona para o arquivo ".php" e mostra na tela todo o código que está dentro dele.
Se alguém puder me ajudar eu agradeço.
Meu HTML:
    <!DOCTYPE html>

        <title>Menu</title>
        <link rel="stylesheet" type="text/css" href="stile.css">

Dados

                <form action="sistema.php" method="post">

                        <input type="text" name="dados" value="" />

                        <input type="submit" id="botaoE" value="submit me!" />

                </form>

e o PHP:
    <?php

        if(isset($_POST["dados"]))
        {
            $valor = $_POST["dados"];

            echo $valor;
        }
    ?>

Desde já agradeço.
Comment: Isso deve acontecer porque você não está utilizando um servidor HTTP com suporte a linguagem PHP. Você precisará do Apache, Nginx ou semelhante para tal. Está utilizando algum destes?
Comment: Era realmente esse o problema, havia esquecido que para conseguir utilizar a linguagem php precisaria estar com o Apache ativo. Obrigado.
Answer: Baixe um ambiente de desenvolvimento de PHP, por exemplo o XAMPP segue o link para download: https://www.apachefriends.org/pt_br/download.html

problema ao executar php


Use Frobenius' method to find two independent solutions to the ODE $4tx''(t)+2x'(t)+x(t)=0$

Question: It is known that $t=0$ is a regular singular point of
$4tx''(t)+2x'(t)+x(t)=0$.
By Frobenius' method, show that two independent solutions of the ODE are given by
$x_1(t)=\sum_{k=0}^\infty \frac{(-1)^k}{(2k)!}t^k$ and $x_2(t)=\sqrt{t}\sum_{k=0}^\infty$$\frac{(-1)^k}{(2k+1)!}t^k$
--
So far I have used the Frobenius ansatz $x(t)=\sum_{k=0}^\infty a_kt^{k+r}$ which implies
$x'(t)=\sum_{k=0}^\infty (k+r)a_kt^{k+r-1}$ and
$x''(t)=\sum_{k=0}^\infty (k+r-1)(k+r)a_kt^{k+r-2}$
Substituting into the ODE gives
$4\sum_{k=0}^\infty (k+r-1)(k+r)a_kt^{k+r-1}+2\sum_{k=0}^\infty (k+r)a_kt^{k+r-1}+\sum_{k=0}^\infty a_kt^{k+r}=0$
We can then change the summation index to make all of the powers of $t$ in each summation equal to $k+r-1$:
$4\sum_{k=0}^\infty (k+r-1)(k+r)a_kt^{k+r-1}+2\sum_{k=0}^\infty (k+r)a_kt^{k+r-1}+\sum_{k=1}^\infty a_{k-1}t^{k+r-1}=0$
Which we can combine to make:
$4(r-\frac{1}{2})ra_0t^{r-1}+\sum_{k=1}^\infty t^{k+r-1}(a_k(4(k+r-\frac{1}{2})(k+r))+a_{k-1})$
It is here that I am unsure of what to do. I believe I need to find the indicial equation? Any help would be much appreciated!
Answer: $$\color {blue}{4(r-\frac{1}{2})ra_0t^{r-1}}+\sum_{k=1}^\infty t^{k+r-1}(a_k(4(k+r-\frac{1}{2})(k+r))+a_{k-1})=0$$
Yes you need to find the indicial equation. Take the coefficient of the lowest power of $t$. You should get for all $t$:
$$t^ {r-1} (4ra_0(r-1)+2ra_0)=0$$
$$2ra_0(2r-1)=0$$
$$r(2r-1)=0$$
$$\implies r=0,r=\frac 12$$
What you have done is correct. Now you have the values of $r$ you can continue.
Next step: you have  to find the recurrence relation and deduce, if it is possible, a recurrence formula and find the series solution.
Comment: You're welcome. Oh you have two case depending on r....Plug the values of r and see if you find a pattern @mathemagic
Comment: By the way I checked tje solution you posted didnt you miss a t inside the series ? @mathemagic
Comment: For $r=0$ and $r=1/2$ you get the same recurrence formula you have after that to split into cosine and sin function...Even and Od power of t...@mathemagic . I did the calculation from you recurrence formula and I get the correct answer. you are close to finich this problem.
Comment: Note that an important thing that your recurrence is valid for $k \ge 1$ @mathemagic
Comment: Thank you very much for your advice. I have now obtained the recurrence relation: $a_k=\frac{-a_{k-1}}{2(2k+2r-1)(k+r)}$. How would I transfer this into finding the formula, and ultimately the series solutions?
Comment: My bad! Very sorry, I'll edit it to avoid confusion from any other readers. Thanks for pointing this out!
Comment: I have found the patterns now, and have got my two formulae: $a_m=\frac{(-1)^ma_0}{(2m)!}$ for $r=0$ and $a_m=\frac{(-1)^ma_0}{(2m+1)!}$ for $r=\frac{1}{2}$, how do I know that the values of $a_0$ are $1$ and $\sqrt{t}$ respectively? Thanks!
Comment: Good job @mathemagic ...$a_0$ is a constant. You need inital conditions for that and you are not given any intial conditions. Keep it that way..
Comment: Thanks. The question says the two independent solutions are $x_1(t)=\sum_{k=0}^\infty \frac{(-1)^k}{(2k)!}t^k$ and $x_2(t)=\sqrt{t}\sum_{k=0}^\infty \frac{(-1)^k}{(2k+1)!}t^k$ but where they have a $1$ and a $\sqrt{t}$ I have $a_0$. Am I missing something or is it just that the constant can be set to whatever you like?
Comment: we add two constants for $x(t)=c_1x_1+c_2x_2$ with differential equations thats the rule. . @mathemagic  Dont' forget to multiply you series by $t^r$ I mean $t^0$ and $t^{1/2}$ for the other series
Comment: I see it now! I need to substitute these back into the original ansatz and I will get the coefficients they are looking for as the $t^r$ terms can be brought outside the summation! Thank you for all your help, I appreciate it a lot :)
Comment: You are welcome @mathemagic One series is from the recurrence formula for $r=1/2$ multiply that series by $\sqrt t$ Because with frobenius method the series is of the form $t^r \sum a_nt^n$
Comment: I think I still get an $a_0$ out at the front of the summation though, whereas their answers do not. This is the last piece of the puzzle I think!
Comment: It's a constant it dosent matter @mathemagic For a differnetial equation that is linear if $e^t$ is a solution then $2e^t$ is also a solution and also $c_1e^t$
Comment: I see, so it is absorbed into the other constants you mentioned earlier! Thank you and stay safe!
Comment: Yes these are constants. Thank you stay safe too. Take care. @mathemagic
Answer: To find the indicial equation, you begin by putting it in standard form: $$x'' + (1/2t)x' + (1/4t)x = x'' + p(t)x' + q(t)x = 0$$
The indicial equation is $$r(r-1) + p_0r + q_0 = 0$$ where $$ p_0 = \lim_{t \to 0}t \,p(t) \\ q_0 = \lim_{t \to 0} t^2 \, q(t) $$


Find if the frequency of two events is significantly different using Binomial test

Question: I am trying to understand how to apply the Binomial test to the following problem:
From the first box, we retrieved 10 rotten tomatoes, from the second none. Use the binomial test to test if rotten tomatoes is significantly more frequent in the first box.
In classical examples it is necessary to provide the probability of events and number of experiments. Two questions I have so far:

do we have enough data;

(in the case they are enough ...) how to apply Binomial test to find an answer?
Comment: You need to randomly select assuming both boxes contain a large number of tomatoes.  Then you need to know $n_1$ the number of tomatoes drawn from the first box and $n_2$ the number of tomatoes drawn from the second box.
Comment: Ok in our case we have a large number of tomatoes, $n_1 = 10$ and $n_2 = 0$. What should I do next?
Comment: If $n_2$ is 0 you can't say anything because you haven't sampled from the second box.  You are confusing the sample sizes with the number of rotten tomatoes.  Let $x_1$ represent the number of rotten tomatoes found in the sample from box 1 and $x_2$ the number found in the sample from box 2. In your case $x_1$=10 and $x_2$=0.  Given that you counted how many good tomatoes were in each sample you would know $n_1$ and n$.2$. Given that information you can then do a two sample binomial test to conclude whether or not box 1 has more rotten tomatoes than box 2.
Answer: Let $X_1\sim \mathcal{Binom}(n_1, p_1), \quad X_2\sim\mathcal{Binom}(n_2, p_2)$. You observed $X_1=10, X_2=0$. You didn't tell us $n_1, n_2$.
Assuming you know $n_1, n_2$, you have enough data for a binomial test of  $H_0\colon p_1=p_2$. How to do the test are discussed in multiple posts on this site:

Exact two sample proportions binomial test in R (and some strange p-values)

Test if two binomial distributions are statistically different from each other

Finding a confidence interval for difference of proportions


How to pass data into the template in Framework7?

Question: I trying to pass data that is fetched from the server to a popup.I tried doing something like this but its not working.Please help-
{
  path:'/merchant/:id',
  beforeEnter: function (routeTo, routeFrom, resolve, reject) {
    console.log(routeTo.params.id);
    Meteor.call('getOne',routeTo.params.id,(error,result) => {
      if (result) {
        resolve(
          {
            popup: {
              el:document.querySelector('#sample-popup')
            }
          },
          // Custom template context
          {
            context: {
              users: result,
            },
          }
        )
      }
    });
  } ,
},

Answer: According to the docs, you use resolve callback wrong !
You can also read this understand how to achieve this
Comment: Can u please help me this.I'm still not getting what is wrong
Comment: You can't pass `popup` into resolve function. For example, move the html for the popup to another file and add ` componentUrl: 'path-to-popup-file.html'` in `resolve()`


Values and index operations between multidimensional numpy arrays

Question: (I have no idea how to name that question. So feel free to edit)
I have the following arrays :

3D array containing value for [z, y, x]
3D array containing altitude for [z, y, x]
2D array containing maximum_altitude for [y, x]

z, y, x have the same length for the 3 arrays.
I would like a new 2D output containing value_at_max_altitude for [y, x]
The algorithm should be something like
find z where altitude[z, y, x] > max_altitude[y, x]
value_at_max_altitude[y, x] = value[z, y, x]

How would you do that with numpy?
edit:
Here is the solution I have actually. But I was wondering if it is possible to use numpy internal functions to avoid loop:
# get index of Z for first value != False
z = np.argmax(altitude >= max_altitude, axis=0)

# z shape is [x, y]
ny, nx = z.shape

# initialize empty array
value_at_max_altitude = np.empty([ny, nx])

# fill value_at_max_altitude
for y in range(ny):
   for x in range(nx):
     value_at_max_altitude[y, x] = value[z[y, x], y, x]

Comment: if you can share some data I'll give it a go :)
Comment: What about `where altitude[z, y, x] <= max_altitude[y, x]`?
Comment: Just to be clear, does 3D mean it represents data in 3d space, which would be an array with `n` rows and 3 columns?  Or is the array shape a 3 element tuple (a real numpy 3d array)?
Comment: 3D array? or Nx3 D array? 2nding @Yuca: this question requires example data
Comment: @kevinkayaks maybe somebody with amazing abstraction capabilities can figure it out, I'm just acknowledging my limitations lol
Answer: If I understand your question, you are trying to do something like the following.  Because you didn't provide example data, I'm not sure, but I think this matches the solution using loops that you already have.
import numpy as np

# Generate example data
nz, ny, nx = 7, 5, 3
value = np.random.uniform(size=(nz, ny, nx))
altitude = np.random.uniform(size=(nz, ny, nx))
max_altitude = np.random.uniform(size=(ny, nx))

# Do the indexing
z = np.argmax(altitude >= max_altitude, axis=0)
value_at_max_altitude = value[(z, *np.ogrid[:ny, :nx])]

It seems like you are just trying to index into your value array with an array z of indices.  In that case, you just have to generate arrays with the corresponding x and y indices which is what I did with np.ogrid.  The obvious way would be to use mgrid but this would generate two arrays of shape (ny, nx).  Using ogrid yields arrays of shape (ny, 1) and (1, nx), respectively, in this case.  They are still able to index into the array because Numpy broadcasts during indexing of arrays with arrays.  This is probably only important if you have nx and ny very large.


What's the difference between FQDNs and Hostnames

Question: First of all, I wanna say that I know how DNS Servers work and also I know about the records in a DNS Zone File!
I'm not an expert but I have some knowledge about them. I'm confused! why?! because I don't know what's the exact difference between hostnames and FQDNs.
I know that some thing like my.example.com. is a FQDN. somebody told me it's a FQDN because of the existance of "dot" at the end of it.
I think the final dot at the end of it reffers to the root dns servers in the world, right?
Is my.example.com a hostname? (note that it's doesn't have any final dots!)
maybe "my" is the hostname?!
Actually i'm confused!
What's the difference between a hostname and a FQDN, guys?!
Sorry, My english isn't very good. excuse me if I made a mistake.
Thanks in advance.
Comment: A host name is part of a FQDN. For example, in `www.example.com`, the `www` is the host name, and `example.com` is the domain name.
Answer: I am pasting the answer for your knoledge. This has been already answered at serverfault.

Your hostname is the name of your computer.
Your fully qualified domain name is your hostname plus the domain your company uses often ending in .local.
So if the name of your computer is bob, and your company's domain is contoso.local, your computer's fully qualified domain name is bob.contoso.local
Hostname: bob
Domain: contoso.com
FQDN: bob.contoso.com
In the case of a domain like contoso.local I did not use an "external" internet domain name. This name doesn't have to be the only way that you address the server. If you make it available by its IP address you can use DNS or that IP address to allow external users to access it.
LINK:  What is the difference between a hostname and a fully qualified domain name?

Try to find answers yourself first instead of raising a question.


Partial ordered sets and supremum.

Question: Let $A,B$ subsets of a partial ordered set $(X,\succeq)$, such that $A\subseteq B$. Suppose that $sup(B)$ exists, Do $sup(A)$ exists?
I could prove that all upper bound of $B$ is an upper bound of $A$ I wanted to prove that $sup(A)$ exists by the supremum axiom, but I don't know if $X$ is complete. Is there a counterexample pf $sup(B)$ exists but $sup(A)$ does not?
Answer: Let $X=[0,1]\cap\Bbb Q$ with the usual order. Let $B=X$ and $A=\left[0,\sqrt2-1\right)\cap\Bbb Q$. Then $\sup B=1$, but $A$ has no supremum in $X$, because $\sqrt2-1$ is irrational.

Partial ordered sets and supremum.


Select com LIKE e POST

Question: Olá
Eu estou tentando utilizar um LIKE em um SELECT, os dados viram via GET, mas não funciona, oque pode estar errado ?
$nome = $_GET['nome'];

$row=$db->prepare("SELECT * FROM cadastro WHERE nome LIKE '%$nome'%");

Obrigado
Comment: Já tentou colocar o ultimo % dentro das aspas simples?
Comment: Agora deu certo. Obrigado KillerJack
Answer: Amigo tenta usar um filtro no GET para evitar inject.
Tenta assim:
$nome = addslashes(filter_input(INPUT_GET, 'nome', FILTER_SANITIZE_SPECIAL_CHARS));

$row=$db->prepare("SELECT * FROM cadastro WHERE nome LIKE '%$nome%'"); // Primeiro o %, depois a aspa simples

Para facilitar, posta o erro que esta retornando no seu php.
Comment: Olá amigo. Não tem erro algum na tela nem no console do Google Chrome
Comment: Bom vc esta usando o metodo `GET` certo. Com ele vc tem que passar o nome pela URL, se for usar um formulário vc tem que usar o método `POST`.
Comment: Olá Hugo. Obrigado, mas já esta resolvido.
Comment: Posta como resolveu o problema, pois isso pode ajudar outras pessoas.
Comment: +1 pelo escape dos caracteres especiais. A molecada tem que aprender isso desde cedo pra ficar no sangue.
Comment: Eu resolvi o problema, seguindo o conselho do KillerJack, alterei a posição das aspas simples.

Select com LIKE e POST


postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

Question: I have a Postgres db 9.1 running on AWS EC2, with ubuntu 12.04.
I messed a lot with the instance (i.e installed all kinds of postgres X.X before i settled on 9.1).
Now after a month working on that db, I discovered that if I restart my instance postgres doesn't load correctly, its status says "Running clusters". this will last forever until I
sudo service postgresql restart

from terminal, and then it works again.
How do I add this line, to ubuntu startup so that each time it loads, it will restart this service, and hopefully solve my problem?
Also any other solution which might solve this.
Comment: If you came here by google (like me) looking for the command to restart postgresql, in my case it was service postgresql-9.3 restart
Comment: I made Albert's comment a Question and Answer: https://stackoverflow.com/questions/52610485/how-to-restart-postgresql-in-ubuntu-18-04/52610486
Comment: Came just to get that restart command,
got what I want, thanks
Answer: On Ubuntu 18.04:
sudo systemctl restart postgresql.service
Comment: You need to provide the cluster version as well: sudo systemctl start postgresql-9.5.service
Comment: @Aarvy strangely, on Ubuntu 20 with Postrges 13, the version isn't needed for systemctl
Answer: The below command worked for me
sudo service postgresql restart

Comment: Worked for me on Ubuntu 22.04, via WSL 2 on Windows
Answer: ENABLE is what you are looking for
USAGE:
type this command once and then you are good to go. Your service will start automaticaly at boot up
 sudo systemctl enable postgresql

DISABLE exists as well ofc
Some DOC: freedesktop man systemctl
Comment: maybe i think this is for enable....
Comment: @CHAVDAMEET the question was **How do I add this line, to ubuntu startup so that each time it loads, it will restart this service, and hopefully solve my problem?**
Answer: I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local, which is executed about last in init phase.
Comment: thanks, but either that rc.local is not running, or the command executed before whatever postgres is doing, or the db overrides it somehow, il look into the logs for info, but off the bat that does not work.
Comment: Maybe there is a race condition, so rc.local gets executed before the regular postgres start process is finished, probably due to the error. Maybe you can add a sleep before the restart and see if that is a valid work around.
Comment: thanks the rc was the right directions, i found the solution in the rcX files. which govern the startup order
Answer: restart postgresql
$ sudo service postgresql restart

Answer: for ubuntu startup so that each time it loads, it will restart this service of Postgres on startup so that you won't have to restart it all the time
sudo update-rc.d postgresql enable


Migrate from SBS 2011 to 2008 Standard

Question: I have a customer who is running a Windows Domain with a Windows Small Business Server 2011.
Now I want to "update" (or downgrade?) to a 2008 R2 Domain.
For two reasons.

The customer has nearly reached the SBS user limit
The customer now has a XEN-Server for virtualisation and I want to seperate the services (Exchange, WSUS, Active-Directory) to different virtual machines.

Is there a recommended migration path?
Is this even possible?
Answer: Well, I would absolutely not attempt to migrate an SBS 2011 to Server 2008, even if it wasn't a Domain Controller.  So, don't try that.
But, what your customer wants can be done.  Just don't try to do it directly.
Basically, you want to add a second Domain Controller to the domain, and then get rid of the SBS server as a Domain Controller.
(Before following the below instructions, it's a good idea to make sure you have a current backup of the Domain Controller.  Always a good idea, just saying it explicitly.)

Check the Forest and Domain Functional Levels.  By default, SBS 2011 creates and uses a 2003 Domain and Forest Functional Level.  There's no 2011 Functional Level, so you're not actually migrating/downgrading the domain.  I'd link how to do this, but I have no freaking idea how to check your Functional Levels on an SBS server.
Get a second server and install a version of Windows that is at least the same as the lowest Functional Level.  If you plan on installing Server 2008 R2, you can even skip step 1.
Join it to your domain.
Use DCPromo to make it a Domain Controller, making sure it's a Global Catalog.
Transfer all the FSMO roles to your new Domain Controller.
Sixth, demote your SBS Domain Controller.  (Again, I'd link to this or explain how, but I have no freaking clue.)
Done!!

Optional, but additional advisable steps:

Format the disk on the server that had SBS 2011.  Install the same version of Windows you just got done installing.  Follow steps 1 through 4 above to make it a Domain Controller.  Now you have 2 Domain Controllers.  You should never have only one Domain Controller, and always have at least 2.
Raise the Functional Level of your domain and forest.
Contact HopelessN00b and offer him a cut of what you get paid for this job.  Seriously, he's a good guy to know, and would really appreciate this. :D
Comment: Optional step #3 is cheap. lmao!! Good laughs.
Comment: Step 6 info [here](http://blog.thefullcircle.com/2011/08/removing-sbs-2008-step-3-remove-from-domain-dcpromo/). Basically using `DCPROMO` will transfer the roles and do the demotion for you!
Answer: You cannot "Downgrade" or "Upgrade" SBS to Standard.  There is no downgrade path or transition path.
I would also encourage anyone who has NOT ever done this to NOT try to offer advice on how to do it.
I agree, a FULL backup of the SBS server (ANY system) before a major change should be considered MANDATORY.
You need to buy a copy (or more) of 2008 R2 Standard and if you use Exchange 2010, you'll need a copy of that as well in order to migrate away from SBS (or wait a month or so and get the license for 2012).  Both Exchange and Windows will require ALL NEW CALs.  Because of this, and the timing of your migration, I would wait if you could until the 2012 CALs are released (They may already be released - Server 2012 is RTM and should be available via volume license (meaning the CALs should be as well) within a month or so).  CALs are backward compatible (downgrade rights permit them to grant access to prior versions of server, so even if you don't move to 2012 right away, you can get the CALs right away to be legal and ensure you don't have to buy them over again. (Exchange 2013 isn't due out for a while yet, so either get the CALs with Software Assurance (SA) so you can upgrade at no additional charge (SA costs about 50% more than non-SA versions and is in many ways a "prepaid" upgrade license since upgrades are largely no longer sold by Microsoft)
Forget about checking the Forest Functional levels - if you're installing 2008 R2 or 2012 it's just not important. What you should be doing is a DCDIAG /C /E /V on the server to ensure AD is healthy.  Fix anything you cannot explain and verify is normal.  Once AD is healthy, add the new domain controller by joining the system to the domain and running DCPROMO.
DO Make sure upon completion that the DC is working properly and is also a GC (Global Catalog).  DO NOT TRANSFER THE FSMO ROLES YET! Instead, Run another DCDIAG check to make sure everything is working well.  Not so much a problem in my experience going from 2008 R2 based systems to other 2008 R2 based systems, I HAVE seen repeated issues where the new DC doesn't properly start replicating with the old and you need to reset the BurFlags Registry entry.  You may not have to, but a DCDIAG should confirm the new DC is working appropriately and then you can proceed.
Understand, you have 21 days to complete this migration once you transfer the FSMO roles, so DON'T DO IT until you have done other transfers of data, Exchange, etc to ensure you have the most possible time.  (If you fail to complete the migration in 21 days, your SBS server starts shutting down every hour or two.  THERE IS NO WORK AROUND THIS and a call to Microsoft won't help, so MAKE SURE you are ready!
Once everything and everyone has been migrated off, you can transfer the FSMO roles.  Once transferred, UNINSTALL Exchange from the SBS system and PAY ATTENTION to the notes and warnings as you do.  Once Exchange is uninstalled, run DCPROMO and demote it.  Once demoted, remove it from the network.  The SBS License is DEAD.  SBS MUST be the FSMO Master DC and cannot exist in a network with more than 75 CALs and without holding the FSMO roles as a DC.  Yes, it's wasted money at this point... but it was a fairly cheap option (by comparison) to use insteda of the full products when you first got it.
Further, there is NO NEED to raise the functional level of the domain or forest UNLESS you have a need to do so (such as to use new features of Active Directory or other software you install requires it.  You can if you like, but it's not a requirement.  (When raising the functional levels, you CANNOT go back (generally).  2012 and I THINK 2008 R2 DO permit certain downgrades of functional levels if you haven't used the newer features of the newer functional levels.
Separating the services on separate servers is logical and efficient but USUALLY not cost effective.  While I would pull off Exchange (especially if you have to leave SBS because you eclipse the 75 CAL limit (it's NOT a user limit - it's a CAL limit), then I'd probably keep WSUS and AD on the same server as both are relatively lightweight in a small environment and potentially costly to run on separate servers.  Also keep in mind Server 2012 Standard offers TWO virtual licenses for the price of one copy of the server.  AND there are no software restrictions (you can cluster, for example - the only difference between the two higher versions of 2012 (Standard and Datacenter) is in terms of licensing of VMs - Datacenter allows unlimited VMs and Standard just two).
In conclusion, if you don't have experience doing this, I wouldn't cheap out and do it myself.  HIRE a professional who does have experience doing this.  Or learn it in a test environment first.  Otherwise, you may wind up paying even more in later consultant fees or lost productivity or higher licensing costs (or all three) later because you didn't know what you were doing.

Migrate from SBS 2011 to 2008 Standard


C# Delegate Use Object field's value without reference

Question: I have a delegate that I define at runtime. I want it to check if a dictionary contains a particular key. One of the delegate parameters is a ref to the dictionary, so the dictionary is always the latest version (not a frozen copy).
However the key to lookup is an object field, but I don't want to pass it a ref to that object. I just want to grab the field value and use it as if it were a constant (frozen copy).
This is the exact code snippet. I pass in a ref to the netController, which allows me to check something is there using ContainsID(). The ID parameter comes from the msg object, but I just want to use the value without the reference to the container object.
Func<netController, bool> resolveFunc = delegate (netController nc)
{
    return nc.ObjectRegister.ContainsID(msg.parentObjectID);
};

nc is in scope in this delegate, but msg is not. Is this do-able, or does everything need to be passed in as a parameter?
Note: I say dictionary, but its actually a dictionary-like object. ContainsID() is a wrapper for ContainsKey(). Don't worry about this part.
Answer: This is called an implicit capture of a variable by delegate, and it is definitely possible.
As long as msg is in scope outside the line that creates your delegate, C# would capture it, and let you use it inside your code:
Func<Controller,bool> MakeChecker(Message msg) {
    return nc => nc.ObjectRegister.ContainsID(msg.parentObjectID);
}

Above method captures msg implicitly from the context that creates the delegate, rather than passing it as a delegate parameter. I used lambda syntax in place of anonymous delegate syntax:
Func<Controller,bool> MakeChecker(Message msg) {
    return delegate (netController nc) {
        return nc.ObjectRegister.ContainsID(msg.parentObjectID);
    }
}

How do I store this into a delegate?

Like this:
Message msg = ...
Func<Controller,bool> myChecker = MakeChecker(msg);

Comment: @Oliver I didn't realize you're on .NET 2.5. Lambda syntax has not been introduced until .NET 3.5. Please see the edit for an equivalent anonymous delegate syntax.
Comment: I'm a bit confused by that syntax, shouldn't there be an assignment somewhere? How do I store this into a delegate?
Comment: Am I being thick or is it still missing something? ```Func MakeChecker(Message msg) {
    return nc => nc.ObjectRegister.ContainsID(msg.parentObjectID);
}``` doesn't complile for me. I'm using .net 2.5, sorry I forgot to mention.

Message is a type which is not valid in the context.
Expected ; or =
Return statement is trying to return from the containing main function (and causing issues).


Would an invalid certificate cause an 0x8004010F sync error?

Question: We just migrated from Exchange 2003 to 2007 which was a combo primary AD/DNS server and it has not gone smoothly.  We are now down to getting a new certificate (a bureaucratic process thats out of my hands) and users getting the 0x8004010F sync issue.  We are only using Outlook 2007 as our email client and the sync error appears exactly as so:
9:21:44 Synchronizer Version 12.0.6562
9:21:44 Synchronizing Mailbox '<User>'
9:21:44 Done
9:21:44 Microsoft Exchange offline address book
9:21:44     0X8004010F

Now, I have read a number of technet articles on this issue anywhere from adding an A record in the DNS for autodiscover.domain.com to syncing the old OAD to the new OAD.  In otherwords, theres lots of thing to try, but trial and error at this point might be hazardous to ther server's health and I am trying to narrow down the list of things to try.  What has me thinking that the sync error could be related to the certificate is an event error message that says the following:

Microsoft Exchange could not find a certificate that contains the
  domain name mail.ccufl.org in the personal store on the local
  computer. Therefore, it is unable to support the STARTTLS SMTP verb
  for the connector Internet Mail with a FQDN parameter of
  mail.ccufl.org. If the connector's FQDN is not specified, the
  computer's FQDN is used. Verify the connector configuration and the
  installed certificates to make sure that there is a certificate with a
  domain name for that FQDN. If this certificate exists, run
  Enable-ExchangeCertificate -Services SMTP to make sure that the
  Microsoft Exchange Transport service has access to the certificate
  key.

I am not fully clear on how the Exchange Transport Service is related to Syncronization, but my hunch is that it probably not related to there not being a valid certificate.  So to recap, would an invalid certificate cause an 0x8004010F sync error?
Answer: The default Exchange transport certificate is actually self-signed and then stored in Active Directory. Have you manually removed or renewed/replaced any certificates from the server's store recently? Could it have expired?
Run
Get-ExchangeCertificate | fl

to give you a list of all certificates on the server. At least one of them should have 'SMTP' listed next to its services, and it should be self signed.
The quickest way of re-generating the default transport certificate and storing it in Active Directory is to use New-ExchangeCertificate
Comment: Everything seems fine.  Got three certs listed and all show a status valid and two look to be self signing with SMTP as a sevice.  Though, I am trying to stop the syncing errors.
Answer: Found where my problem was.  The mailbox database client settings didn't have an offline mailbox set to anything.  Found it

Server Configuration -> Mailbox -> Database Management -> Open your Database Properties -> Client Settings Tab -> Check you have an offline address book set

So my answer is no, an invalid cert will not cuase sync issues of this nature.


Linear relationship assumption with dummy variable

Question: This question I think was already asked here but I can't fully understand the answer.
I have a number of ordinal predictors that I'm transforming into dummy variables and I'm wondering whether the hierarchical multiple regression linear relationship assumption (linear relationship between each predictor and the outcome variable - also the composite and outcome) needs to be met for each dummy variable?
Comment: How do you transform ordinal variables into dummies keeping the ordinal relationship?
Comment: @Aksakal - my plan wasn't to try to maintain the ordinal relationship as by dummy coding them they become either an instance or not (0 or 1). For example, I have one ordinal variable that has three 'groups' (low, med, high) so I create two dummy variables and keep one of the groups (for me it'll be the 'low' one) as the reference group which the other two groups get compared to in the analysis (at least that's my understanding).
Comment: This setup also inherently allows for the fourth state: med and high at the same time.
Answer: There's nothing to check!
Linearity is automatically met for binary (/dummy) variables.
However you set them up, the IV (x) takes only two values (say 0 and 1 but it doesn't actually matter in any substantive way as long as they're any two distinct values). If the DV (y) has a different mean at those two values, the coefficient measures that difference, and that difference corresponds precisely to the term entering the model linearly -- the slope on a 0/1 variable is the mean difference.
If the values differ by something other than 1, then the slope will change but the resulting mean change will be the coefficient times the change in the dummy (that is, the linear model always picks up exactly the mean difference).
Comment: @aksakal I know he's talking about ordinal variables he converted to dummies but the question was specifically about linearity assumption for the dummy variables: "...needs to be met for each dummy variable". As the question currently stands I think it is really this simple. There's no assumption about linearity for the ordinal variable and (at least to my reading) the OP didn't ask about that.
Comment: He's talking about ordinal predictors which he transforms into dummies. For instance ordinal Mood variable with values Down, Neutral and High would become MoodDown and MoodNeutral dummies, but then the ordinal relationship is lost. So, it's not as simple as you seem to suggest
Comment: Thanks Glen_b that's saved me a lot of reading around trying to work out something that didn't need to be worked out.


Using external JavaScript files in a WinForms/WPF WebBrowser control

Question: I found a cool feature on a website, implemented in JavaScript, I'd like to use it as is in my desktop application (for personal use).
During my experiments I managed to generate custom HTML on the fly, feed it to the browser using webBrowser1.DocumentText = [my generated HTML]
I've managed to put some inline JavaScript into the HTML, and hook it up via a ScriptManager so that I can call the JavaScript from my C# code, pass a value to it, and get a return value.
But the feature I'm trying to use is a bit more complicated: it's no less than 10 JavaScript files. 2 of them are referenced directly in the web page  the usual way
The other 8 are loaded in one of the scripts:
var elem = document.createElement("script");
            elem.type = "text/javascript";
            elem.src = "/js/" + filename;
            document.body.appendChild(elem);

These 8 files are in fact data files, even though the data is represented in JavaScript. They're pretty large, over 1MB each. Stuffing it all into the HTML file seems quite stupid. Also, the script that loads the data creates a "file map" and further refers to the data based on which file it's in:
  var fileMap = [
                        [/[\u0020-\u00ff]/, 'file1.js'],
                        [/[\u3000-\u30ff]/, 'file2.js'],
                        [/[\u4e00-\u5dff]/, 'file3.js'],
...

I don't want to resort to modifying the JavaScript, because it's not exactly my strong point. So the browser needs to "see" the js files in order to be able to use them. I thought of creating the file structure locally, and navigating the browser there. But I don't want any loose files in my solution. I'd like to have everything embedded if possible. And I doubt I can get the browser to navigate to an embedded resource, and see other embedded resources as files. Any idea how I could get around this?
EDIT:
I've tried to do it with local files. No luck. I get the HTML to load properly, but when I try to invoke a JavaScript call, nothing happens. I tried pointing the browser to those js files, to make sure they're there. They are. I tried an  element with src attribute pointing to an image in the same subfolder as the script files. It gets rendered. It's as if external js files refuse to load.
Answer: I had a similar need as your scenario and I addressed it using two key points embedded in two other Stack Overflow answers. As noted by SLaks' answer  here the first key is using the syntax file:/// as the prefix for an absolute path to external files. The second is using .Replace("\\", "/") for an absolute file path as listed in Adam Plocher's answer and one of his follow-up comments here.
In short, the final output for each external file in an HTML page will look something like:
<link href="file:///c:/users/david/myApp/styles/site.css" rel="stylesheet" type="text/css">

or

Using the format in the samples above in my HTML file resulted in the WebBrowser control loading external CSS, image or script files.
The details and solving the scenario in the question
In the womd's answer in the first referenced SO answer above he used the method System.IO.File.ReadAllText() to load script files and embedded the text of the script files into the  tag. As you indicated in your question loading script files directly into the HTML page is not what you're looking to do.
The solution below involves using the same System.IO.File.ReadAllText() method but loads the text of the HTML page instead. The premise works similar to the Razor View Engine in ASP.NET.
The main idea in the solution below involves adding a temporary string in an HTML page that will be loaded into the WebBrowser control and then replacing this temporary string in a C# method in my app just before the HTML page is set to be loaded into the WebBrowser control.
Here are the basic steps to my solution:

Add a temporary string for each external reference in the HTML file.
Declare a variable for the absolute path in a script tag within the HTML file. This step is not necessary unless you're going to use the absolute path elsewhere within your JavaScript code. Your scenario involves delay loading external script files via JavaScript code so this step was necessary.
Modify the src property in the JavaScript code that delay loads the other script files with the absolute path variable.
Add a method in your app to loads the HTML page file as a text string and then replaces all temporary string instances with an absolute path containing the prefix 'file:///'. The absolute path should have forward slashes.
Set the 'DocumentText' property on the WebBrowser control to the updated HTML.
Set the 'Copy to Output Directory' of each external file in your project to 'Copy always' or 'Copy if newer'. This step may not be necessary if you have a fixed location to your external files and that location is not within the build or publish directory used by Visual Studio.

The following are the details for each step. I added a lot of detail that you can skip. I was verbose to reduce any confusion since the steps make changes to several places in the project.
1. Using a temporary string
I used the string "/ReplaceWithAbsolutePath/" but you can use any distinct text. Each reference to an external file in the HTML page looks like:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>
    <link href="/ReplaceWithAbsolutePath/styles/site.css" rel="stylesheet" type="text/css">

My web page

2. Declare absolute path variable
Note in the above HTML page I listed a
    public string GetUpdatedHtmlWithAbsolutePaths(string tempPathString, string htmlFilename)
    {
        // Get the directory as the application
        // stackoverflow.com/questions/674857/should-i-use-appdomain-currentdomain-basedirectory-or-system-environment-current
        // Note that the 'BaseDirectory' property will return a string with trailing backslashes ('\\')
        string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
        // Replace '//' with '/' in the appDirectory string
        appDirectory = appDirectory.Replace("\\", "/");
        // Read all of the HTML text from the HTML page file
        string html = System.IO.File.ReadAllText(appDirectory + @"\" + htmlFilename);
        // Replace all '/ReplaceWithAbsolutePath/' strings within the HTML text with
        // the absolute path on the local machine
        html = html.Replace(tempPathString, "file:///" + appDirectory);
        return html;
    }

5. Set the DocumentText property of the WebBrowser control
I added the initialization of the WebBrowser control in the form load event handler but you can, of course, add the line that sets the DocumentText property wherever you initialize your WebBrowser control.
    private void Form1_Load(object sender, EventArgs e)
    {
        // Set the document text of the web browser control with the updated HTML
        webBrowser1.DocumentText = GetUpdatedHtmlWithAbsolutePaths("HTMLPage1.html");
    }

6. Set the 'Copy to Output Directory' of each external file
Take a look at the answer posted by Matthew Watson in this Stack Overflow question if you want your external files included in your solution/project file structure.

You can add files to your project and select their properties: "Build
  Action" as "Content" and "Copy to output directory" as "Copy Always"
  or Copy if Newer (the latter is preferable because otherwise the
  project rebuilds fully every time you build it).
Then those files will be copied to your output folder.
This is better than using a post build step because Visual Studio will
  know that the files are part of the project. (That affects things like
  ClickOnce applications which need to know what files to add to the
  clickonce data.)

In short, add the external file to your project. You can add the external to any subfolder in your project. (In Visual Studio 2013 or 2015 -- I don't have VS2012) Right-click on the external file in the Solution Explorer and select Properties from the context menu. The Properties pane will be displayed. In the Properties pane change the setting for 'Copy to Output Directory' to 'Copy always' or 'Copy if newer'.

Use View Source to verify absolute path strings
Run your project and it should load your external files in the WebBrowser control. Assuming you have not set the property wbChartContainer.IsWebBrowserContextMenuEnabled = false; in code or in the Properties pane for WebBrowser control you can right-click on the WebBrowser control when your form is running. Click 'View Source' from the context menu and check the paths to your external resources in the View Source window.


Three Point Field Goal Point of Release

Question: Does the point of release have to on/behind the three-point line to make a successful 3-pt field goal?
Or can one release the ball from anywhere in mid-air, provided their last step was outside the circle? (Imagine a lay-up from outisde the circle)
I expect that the rules on this are the same for FIBA and NBA.
Answer: NBA rules from http://www.nba.com/analysis/rules_5.html say

c. A successful field goal attempt from the area outside the
  three-point field goal line shall count three points.
  (1) The shooter must have at least one foot on the floor outside the three-point field
  goal line prior to the attempt.
  (2) The shooter may not be touching the floor on or inside the three-point field goal line.
(3) The shooter may contact the three-point field goal line, or land in the
  two-point field goal area, after the ball is released.
  (Emphasis mine)

So, as long as your last step was outside the arc, you may release at any location while in the air, at least in the NBA.  It's the rule I was taught when doing intramural refereeing at college, so I expect, yes, it's the same everywhere.
Comment: Yep.  Examples: https://www.youtube.com/watch?v=fuJI3XjZCnQ

Three Point Field Goal Point of Release


Adding contacter's email to reply field in contact form email

Question: In Drupal 7, when someone used our contact form, we would receive an email and could click "reply" in the email we received and have their email be in the "to" field. Since upgrading to Drupal 8, our own email shows up in the "to" field when replying to people who sent us an email through the contact box. Can anyone shed some light on how I can get the contacter's email to show up in the "to" field?
Can I set a "reply-to" field in the email to get this to work? I am using the core contact module, not webform but I am open to using the webform module if it can allow me to fix this.
Answer: You can do that with the Webform module. For a better explanation check out this: https://www.ostraining.com/blog/drupal/how-to-create-a-contact-form/


How can I prevent an absolute div from showing on mobile?

Question: I have a div box with an absolute position fixed to the left side of a page.  It looks great on PC's and is doing its job of being unobtrusive to the user.  However, when the page is loaded from a mobile device, the left side of the screen is no longer way off to the side, it is on the edge of the content so this absolute box now covers a little bit of the content on the left.  My goal is to only show this one specific div box to PC's, while preventing it from loading on mobile devices.
CSS:
.harry {
float: left;
padding: 5px 0 0 0;
margin: 0;
position: absolute;
left: 0px;
top: 100px;
z-index: 999999;
}

HTML

<big>

</big>

Answer: One way is to just set a CSS3 media query, and hide that div when a mobile device is detected:
@media screen and (max-device-width: 480px) {
  .harry {
    display: none;
  }
}

Comment: Worked perfectly (except I increased 480px to 800px to make sure it doesn't show on high rez phones/tablets)


Is there a way to make nice "flow maps" or "line area" graphs in R?

Question: I'm trying to find a way to recreate graphs like these directly in R (as opposed to manually drawing them with Inkscape after I've done the analysis in R):
   and
The first one seems like it should be straight forward, but I'm not able to find anything that fits my needs... the second one is much more complicated, but also seems like it should be doable.
This post Graph flow chart of transition from states gets me about as close (it's kind of awesome already, except I don't necessarily have a square matrix, and I'd like to designate a start/end location for my lines with control over thickness and alpha based on my own data)...
Is it possible to do this using ggplot (or maybe something else like lattice, if it looks nice)?
Comment: Possibly: http://blog.revolutionanalytics.com/2013/02/visualizing-networks-in-r-arc-diagrams-and-hive-plots.html and http://drunks-and-lampposts.com/2013/01/03/lazy-d3-on-some-astronomical-data/
Comment: For the left one ..probably [this](http://stackoverflow.com/questions/16112162/graph-flow-chart-of-transition-from-states/16113802#16113802)
Comment: @Tyler - really like the arcdiagram package - thanks for pointing me to it!
Comment: @agstudy - yep, that's the one I linked to in my question. Trouble is, it requires a square matrix (can't have 7 items on the left and only 1 item on the right... have to be equal).
Answer: Here is an example to get started on the left graph using base graphics (there are xspline functions for grid graphics as well if you want to use those, I don't know how to incorporate them with ggplot2, but lattice probably would not be too hard):
plot.new()
par(mar=c(0,0,0,0)+.1)
plot.window(xlim=c(0,3), ylim=c(0,8))
xspline( c(1,1.25,1.75,2), c(7,7,4,4), s=1, lwd=32.8/4.5, border="#0000ff88", lend=1)
xspline( c(1,1.25,1.75,2), c(6,6,4,4), s=1, lwd=19.7/4.5, border="#0000ff88", lend=1 )
xspline( c(1,1.25,1.75,2), c(5,5,4,4), s=1, lwd=16.5/4.5, border="#0000ff88", lend=1 )
xspline( c(1,1.25,1.75,2), c(4,4,4,4), s=1, lwd=13.8/4.5, border="#0000ff88", lend=1 )
xspline( c(1,1.25,1.75,2), c(3,3,4,4), s=1, lwd= 7.9/4.5, border="#0000ff88", lend=1 )
xspline( c(1,1.25,1.75,2), c(2,2,4,4), s=1, lwd= 4.8/4.5, border="#0000ff88", lend=1 )
xspline( c(1,1.25,1.75,2), c(1,1,4,4), s=1, lwd= 4.5/4.5, border="#0000ff88", lend=1 )

text( rep(0.75, 7), 7:1, LETTERS[1:7] )
text( 2.25, 4, 'Tie strength')

And some starting code for the right graph using a little different approach:
plot.new()
par(mar=rep(0.1,4))
plot.window(xlim=c(0,7), ylim=c(-1,7))
text( 3+0.05, 0:6, 0:6, adj=0 )
text( 4-0.05, 0:6, 0:6, adj=1 )
lines( c(3,3),c(0-strheight("0"), 6+strheight("6")) )
lines( c(4,4),c(0-strheight("0"), 6+strheight("6")) )

xspline( c(3,1,3), c(0,3,6), s= -1, lwd=1, border="#00ff0055", lend=1 )
xspline( c(3,1.25,3), c(0,2.5,5), s= -1, lwd=4, border="#00ff0055", lend=1 )
xspline( c(4,4.5,4), c(5,5.5,6), s= -1, lwd=5, border="#ff000055", lend=1 )

You can modify the control points, colors, etc. to get closer to what you want.  Many of the pieces could then be wrapped into a function to automate some of the placing.
Comment: Great - this def gets me started! Much appreciated.


join two tables with views?

Question: I have two content types: one for invoices, and the other for donations.
Each content type contain two fields, one for "User Name" (which is a user reference type) and the other is the "Amount($)" (an integer type).
I am trying to create a table with the Views module that returns 3 columns: user name, total donation (the sum for all the donation for the same user), and invoice sum (the sum of all the amount paid for the same user).
I have two users (Ahmed and Taha). Ahmed made 3 donations ($50, $30 and $70) and paid 2 invoices ($30, $30); Taha made 1 donation ($60), and paid 3 invoices ($30, $30, $30).
What I am trying to achieve with the Views module is something like the following.

    *----------------*------------------------*-------------------------*
    |   Username     | Total Donations        | Total Subscriptions     |
    *----------------*------------------------*-------------------------*
    |   Ahmed        |     $150               |      $60                |
    *----------------*------------------------*-------------------------*
    |   Taha         |     $60                |       $90               |
    *----------------*------------------------*-------------------------*

or Something like:

    *----------------*------------------------*-------------------------*
    |   Username     | Donations              | Subscriptions           |
    *----------------*------------------------*-------------------------*
    |   Ahmed        |     $50                |      $30                |
    *----------------*------------------------*-------------------------*
    |   Ahmed        |     $30                |      $30                |
    *----------------*------------------------*-------------------------*
    |   Ahmed        |     $70                |       ---               |
    *----------------*------------------------*-------------------------*
    |   Taha         |     $60                |       $30               |
    *----------------*------------------------*-------------------------*
    |   Taha         |     ---                |       $30               |
    *----------------*------------------------*-------------------------*
    |   Taha         |     ---                |       $30               |
    *----------------*------------------------*-------------------------*
Comment: they told me to use relationships that is build with views but i cant figure out yet how.
Comment: Hi and welcome to Drupal Answers! In order to get the best experience here, you may want to consider editing and re-wording your question. Currently, you are explaining what you are trying to do, but you never really ask a specific question. Also, it is very helpful to explain the steps you have take thus far, how the result you have is different from what you intended and also which versions you are using of Drupal and/or relevant modules.
Comment: thanks sheena_d for reply, the question how can achieve that table using views for each row (i have 3 column) a "user name", their Sum of paid Invoices and the Sum of their Total donations. i am using the latest stable version of drupal and views and reference. i am sorry for my poor English please if there is anything unclear tell me and i will try to clear it
Answer: To add Joins to your views using the Views UI you will need to open the Advanced settings and visit Relationships. (See graphic)

Assuming the user is the author ($node->uid) of the donation's and subscription's payment types you should be able to use the "Content: Author" field to accomplish this join.

This should allow you to build the second table from your question.  To see results displayed in a similar format to your first table you will need to use aggregation.  'Use Aggregation' can be found under the Advanced menu.

Once use aggregation is enabled you will see a new link below your fields called "Aggregation settings."
Select SUM on the field you want to display the totals for and you should see something similar to your first table.

Lastly, while you are getting aquanted with the Views module I recommend turning on the "Show the SQL query" feature in Views settings.  This can be found at admin/structure/views/settings
This will show you the SQL views is generating which can be useful while debugging or learning the Views UI.

join two tables with views?


Load a custom block and render with subset of data

Question: I am loading a block programmatically in a theme preprocess function, and trying to render that block in twig using without to remove some fields. However, the block is still printed in full.
This is the code I am using.
function my_preprocess_node(&$variables) {
    $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
    $variables['my_block'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($my_block);
}

The template code is the following one.
{{ my_block|without('field_1', 'field_2') }}

I also noticed while debugging, that while the result in twig of my_block is a render array, it does not include the keys I'm expecting (the problem, I assume?).
This is the dump() output.
array(3) {
  '#cache' =>
  array(4) {
    'keys' =>
    array(3) {
      [0] =>
      string(11) "entity_view"
      [1] =>
      string(5) "block"
      [2] =>
      string(17) "my_site_footer"
    }
    'contexts' =>
    array(3) {
      [0] =>
      string(28) "languages:language_interface"
      [1] =>
      string(17) "my_theme_section"
      [2] =>
      string(14) "my_theme_site"
    }
    'tags' =>
    array(2) {
      [0] =>
      string(10) "block_view"
      [1] =>
      string(36) "config:block.block.my_block"
    }
    'max-age' =>
    int(-1)
  }
  '#weight' =>
  int(0)
  '#lazy_builder' =>
  array(2) {
    [0] =>
    string(42) "Drupal\block\BlockViewBuilder::lazyBuilder"
    [1] =>
    array(3) {
      [0] =>
      string(17) "my_site_footer"
      [1] =>
      string(4) "full"
      [2] =>
      NULL
    }
  }
}

Comment: The block is not rendered in the node template. You can theme the block only in a block template, which you'll find in the twig debug output.
Answer: One way to do this is with a new view mode for blocks. You can add one at /admin/structure/display-modes/view/add (Manage > Structure > Display Modes > View Modes > Add new view mode). Then, you have two options, 1. go to your custom block type and configure this view mode display to only have the fields you want, or 2. create a template file with a name like block--BLOCK-TYPE--MY-NEW-VIEW-MODE.html.twig, then remove the fields you don't want to print like you were trying to do in the node template. (Replace BLOCK-TYPE with your block type's machine name, and MY-NEW-VIEW-MODE with the machine name of the new view mode you created. Convert all underscores in these machine names to dashes.) After you've done this you can update your preprocess hook's view() call like ->view($my_block, 'MY_NEW_VIEW_MODE')(keep the underscores in the machine name of your view mode here). This will make your preprocess hook look like:
function my_preprocess_node(&$variables) {
  $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
  $variables['my_block'] = \Drupal::entityManager()
    ->getViewBuilder('block')
    ->view($my_block, 'MY_NEW_VIEW_MODE);
}

Lastly, because you add your block to the variables array with the my_block key, update your node's twig template to simply be:
{{ my_block }}


if $d|n$ then $\phi(dn)=d\phi(n)$

Question: I'm working in the following Euler's theorem exercise:

if $d|n$ then $\phi(dn)=d\phi(n)$

Hints for a shorter and simpler, imo, approach:
I'm based on:
$$n=\prod_{i=1}^k p_i^{a_i}\;,\;\;p_i\;\;\text{primes}\;\;,\;\;a_i\in\Bbb N\implies \phi(n)=n\prod_{i=1}^k\left(1-\frac1{p_i}\right)$$
So now:
$$d\mid n\implies n= xd\;,\;\;x\in\Bbb N\implies\; \phi(x)=x\prod_{i=1}^k\left(1-\frac1{p_i}\right)$$
I'm not sure this is the right way, how should I involve that $d$ so I would be able to show the requested property? Any help will be really appreciated.
Comment: Show that $\phi(dn)/(dn)=\phi(n)/n$. Prime factors of $dn$ and that of $n$ are identical.
Comment: More generic https://math.stackexchange.com/questions/114841/proof-of-a-formula-involving-eulers-totient-function-varphi-mn-varphi
Answer: Hint:
If the highest exponent of prime $p$ that divides $n,d$ be $N,D;N\ge D\ge0,N>0$
$\phi(p^{N+D})=?$
For $d\phi(n),$
$p^D\cdot p^{N-1}(p-1)=\phi(p^{N+D})$
This holds true for all prime that divide $n$
See
What's the proof that the Euler totient function is multiplicative?
Answer: Here is a proof that I'm copypasting from my old homework. It proves a bit more (see Theorem 3) and does not use the explicit formula for $\phi$ through the prime factorization.
Let $\phi$ denote Euler's totient function.

Lemma 1. Let $m$ and $k$ be positive integers. Let $s\in\mathbb{Z}$.
(a) We have
  \begin{align}
&  \left(  \text{the number of integers among }ms+1,\ ms+2,\ \ldots
,\ ms+m\text{ that are coprime to }m\right)  \nonumber\\
&  =\phi\left(  m\right)  .
\label{darij1.p11.claim1}
\tag{1}
\end{align}
(b) Let $x\in\left\{  1,2,\ldots,m\right\}  $. The integer $ms+x$ is
  coprime to $m$ if and only if $x$ is coprime to $m$.

Proof of Lemma 1. (b) If $d$ is a common divisor of $ms+x$ and $m$, then
$d$ must also divide $x$ (since $d\mid ms+x$ and $d\mid m$, so that
\begin{equation}
x=\underbrace{\left(  ms+x\right)  }_{\substack{\equiv0\mod
d\\\text{(since }d\mid ms+x\text{)}}}-\underbrace{m}_{\substack{\equiv
0\mod d\\\text{(since }d\mid m\text{)}}}s\equiv
0-0s=0\mod d,
\end{equation}
so that $d\mid x$), and thus $d$ must be a common divisor of $x$ and $m$. In
other words, each common divisor of $ms+x$ and $m$ must be a common divisor of
$x$ and $m$.
If $d$ is a common divisor of $x$ and $m$, then $d$ must also divide $ms+x$
(since $d\mid x$ and $d\mid m$, so that
\begin{equation}
\underbrace{m}_{\substack{\equiv0\mod d\\\text{(since }d\mid
m\text{)}}}s+\underbrace{x}_{\substack{\equiv0\mod
d\\\text{(since }d\mid x\text{)}}}\equiv0s+0=0\mod d,
\end{equation}
so that $d\mid ms+x$), and thus $d$ must be a common divisor of $ms+x$ and
$m$. In other words, each common divisor of $x$ and $m$ must be a common
divisor of $ms+x$ and $m$.
We have thus shown that:

Each common divisor of $ms+x$ and $m$ must be a common divisor of $x$ and
$m$.
Each common divisor of $x$ and $m$ must be a common divisor of $ms+x$ and
$m$.

Combining these two statements, we conclude that the common divisors of $ms+x$
and $m$ are exactly the common divisors of $x$ and $m$. Thus, the greatest
common divisor of $ms+x$ and $m$ is the greatest common divisor of $x$ and
$m$. In other words, $\gcd\left(  ms+x,m\right)  =\gcd\left(  x,m\right)  $.
Now, we have the following equivalence of statements:
\begin{align*}
\left(  ms+x\text{ is coprime to }m\right)  \   & \Longleftrightarrow\ \left(
\underbrace{\gcd\left(  ms+x,m\right)  }_{=\gcd\left(  x,m\right)  }=1\right)
\\
& \Longleftrightarrow\ \left(  \gcd\left(  x,m\right)  =1\right)
\ \Longleftrightarrow\ \left(  x\text{ is coprime to }m\right)  .
\end{align*}
This proves Lemma 1 (b).
(a) We have
\begin{align*}
&  \left(  \text{the number of integers among }ms+1,\ ms+2,\ \ldots
,\ ms+m\text{ that are coprime to }m\right)  \\
&  =\left\vert \left\{  x\in\left\{  1,2,\ldots,m\right\}  \ \mid
\ \underbrace{ms+x\text{ is coprime to }m}_{\substack{\text{this is equivalent
to}\\x\text{ being coprime to }m\\\text{(by Lemma 1 (b))}}}\right\}
\right\vert \\
&  =\left\vert \left\{  x\in\left\{  1,2,\ldots,m\right\}  \ \mid\ x\text{ is
coprime to }m\right\}  \right\vert \\
&  =\left(  \text{the number of integers among }1,\ 2,\ \ldots,\ m\text{ that
are coprime to }m\right)  \\
&  =\left(  \text{the number of }x\in\left\{  1,2,\ldots,m\right\}  \text{
that are coprime to }m\right)  \\
&  =\phi\left(  m\right)
\end{align*}
(since $\phi\left(  m\right)  $ is defined as the number of $x\in\left\{
1,2,\ldots,m\right\}  $ that are coprime to $m$). This proves Lemma 1 (a).
$\blacksquare$

Lemma 2. Let $m$ and $k$ be positive integers. Then, the number of
  positive integers $\leq mk$ that are coprime to $m$ is $k\phi\left(  m\right)
$.

Proof of Lemma 2. We have
\begin{align*}
&  \left(  \text{the number of positive integers }\leq mk\text{ that are
coprime to }m\right)  \\
&  =\left(  \text{the number of integers among }1,\ 2,\ \ldots,\ mk\text{ that
are coprime to }m\right)  \\
&  =\sum_{s=0}^{k-1}\underbrace{\left(  \text{the number of integers among
}ms+1,\ ms+2,\ \ldots,\ ms+m\text{ that are coprime to }m\right)
}_{\substack{=\phi\left(  m\right)  \\\text{(by \eqref{darij1.p11.claim1})}}}\\
&  \qquad\qquad\left(
\begin{array}
[c]{c}
\text{since each of the integers }1,\ 2,\ \ldots,\ mk\text{ belongs to exactly
one}\\
\text{of the }k\text{ lists }\left(  1,\ 2,\ \ldots,\ m\right)  ,\ \left(
m+1,\ m+2,\ \ldots,\ 2m\right)  ,\ \ldots,\\
\left(  m\left(  k-1\right)  +1,\ m\left(  k-1\right)  +2,\ \ldots
,\ mk\right)  \text{; in other words, each}\\
\text{of the integers }1,\ 2,\ \ldots,\ mk\text{ belongs to exactly one of the
}k\\
\text{lists }\left(  ms+1,\ ms+2,\ \ldots,\ ms+m\right)  \text{ with }
s\in\left\{  0,1,\ldots,k-1\right\}
\end{array}
\right)  \\
&  =\sum_{s=0}^{k-1}\phi\left(  m\right)  =k\phi\left(  m\right)  .
\end{align*}
This proves Lemma 2. $\blacksquare$

Theorem 3. Let $m$ and $n$ be two positive integers. Assume that every
  prime that divides $n$ also divides $m$. Then:
(a) For every integer $x$, we have the following logical equivalence:
  \begin{equation}
\left(  x\text{ is coprime to }m\right)  \Longleftrightarrow\left(  x\text{ is
coprime to }mn\right)  .
\label{darij1.p12.c1}
\tag{2}
\end{equation}
(b) We have $\phi\left(  nm\right)  =n\phi\left(  m\right)  $.

Proof of Theorem 3. (a) Let $x$ be an integer.
Proof of the $\Longrightarrow$ direction of \eqref{darij1.p12.c1}:
Assume
that $x$ is coprime to $m$. Thus, $\gcd\left(  x,m\right)  =1$. Hence, no
prime can divide both $m$ and $x$. Now, we shall prove that $x$ is coprime to
$mn$. Indeed, assume the contrary. That is, $x$ is not coprime to $mn$; thus,
$\gcd\left(  x,mn\right)  >1$. Hence, there exists a prime $p$ which divides
$\gcd\left(  x,mn\right)  $. Consider this $p$. Then, $p\mid\gcd\left(
x,mn\right)  \mid mn$. Since $p$ is a prime, this yields that we have $p\mid
m$ or $p\mid n$. If we had $p\mid m$, then the prime $p$ would divide both $m$
and $x$ (because $p\mid m$ and $p\mid\gcd\left(  x,mn\right)  \mid x$); this
would contradict the fact that no prime can divide both $m$ and $x$. Hence, we
cannot have $p\mid m$. Thus, we must have $p\mid n$ (since we have $p\mid m$
or $p\mid n$). Since $p$ is a prime, we thus conclude that $p\mid m$ (due to
our assumption that every prime that divides $n$ also divides $m$). This
contradicts the fact that we cannot have $p\mid m$. This contradiction shows
that our assumption was false. Hence, we have shown that $x$ is coprime to
$mn$. The $\Longrightarrow$ direction of \eqref{darij1.p12.c1} is thus proven.
Proof of the $\Longleftarrow$ direction of \eqref{darij1.p12.c1}:
Assume
that $x$ is coprime to $mn$. Thus, $\gcd\left(  x,mn\right)  =1$. Now, we
shall prove that $x$ is coprime to $m$. Indeed, assume the contrary. That is,
$x$ is not coprime to $m$; thus, $\gcd\left(  x,m\right)  >1$. Hence, there
exists a prime $p$ which divides $\gcd\left(  x,m\right)  $. Consider this
$p$. Then, $p\mid\gcd\left(  x,m\right)  \mid x$ and $p\mid\gcd\left(
x,m\right)  \mid m\mid mn$. Hence, $p$ is a common divisor of the numbers $x$
and $mn$, and therefore divides their greatest common divisor. In other words,
$p\mid\gcd\left(  x,mn\right)  =1$. So we have $p\mid1$. This is absurd, since
$p$ is a prime. This contradiction shows that our assumption was false. Hence,
we have shown that $x$ is coprime to $m$. The $\Longleftarrow$ direction of
\eqref{darij1.p12.c1} is thus proven.
Now, with both directions of \eqref{darij1.p12.c1} being proven, the proof of
\eqref{darij1.p12.c1} is complete. In other words, Theorem 3 (a) is proven.
(b) Lemma 2 (applied to $k=n$) yields that the number of positive integers
$\leq mn$ that are coprime to $m$ is $n\phi\left(  m\right)  $. Thus,
\begin{align*}
n\phi\left(  m\right)   &  =\left(  \text{the number of positive integers
}\leq mn\text{ that are coprime to }m\right)  \\
&  =\left(  \text{the number of }x\in\left\{  1,2,\ldots,mn\right\}  \text{
such that }\underbrace{x\text{ is coprime to }m}
_{\substack{\Longleftrightarrow\left(  x\text{ is coprime to }mn\right)
\\\text{(due to \eqref{darij1.p12.c1})}}}\right)  \\
&  =\left(  \text{the number of }x\in\left\{  1,2,\ldots,mn\right\}  \text{
such that }x\text{ is coprime to }mn\right)  \\
&  =\phi\left(  mn\right)
\end{align*}
(since $\phi\left(  mn\right)  $ is defined as the number of $x\in\left\{
1,2,\ldots,mn\right\}  $ such that $x$ is coprime to $mn$). This proves Theorem
3 (b). $\blacksquare$

Corollary 4. Let $m$ and $n$ be two positive integers such that $n\mid m$.
  Then, $\phi\left(  nm\right)  =n\phi\left(  m\right)  $.

Proof of Corollary 4. Every prime that divides $n$ also divides $m$ (since
$n\mid m$). Hence, Theorem 3 (b) yields $\phi\left(  nm\right)
=n\phi\left(  m\right)  $. This proves Corollary 4. $\blacksquare$
Corollary 4 is your question (with $d$ and $n$ renamed as $n$ and $m$).

if $d|n$ then $\phi(dn)=d\phi(n)$


issues getting apache to serve phpmyadmin from subdomain

Question: After years of using managed servers I'm finally getting my feet wet with setting up a webserver (using rackspace cloud).  Here is how I have things setup:
Server A (hosted with servint.com, manages DNS for example.com)
Server B (rackspace cloud server, I want to serve apps for example.com from here)
I've added an A record on Server A for app.example.com to point to Server B's ip address.  This works great!  Now I also have phpMyAdmin installed on Server B.  If I go to Server B's phpmyadmin URL like  "XX.XX.XX.XX/phpmyadmin", it loads just fine.  What I would like to do is configure another A record on Server A like "phpadmin.example.com" which will point to Server B.  I have not yet set up a VirtualHost for that server name, so I get the default sites-enabled.
How do I tell apache that "phpadmin.example.com" should load "phpadmin.example.com/phpmyadmin"?  A job for mod rewrite?  Something in the default virtual host?
Any help is much appreciated!
Answer: Once you have setup the apache virtual server, just make the directory it forwards to the directory phpMyAdmin lives in.
General Apache Virtual Server Config:
<code>DocumentRoot "/usr/share/phpmyadmin"
ServerName phpmyadmin.example.tld
<Directory "/usr/share/phpmyadmin">
allow from all
Options +Indexes
</Directory>
</code>
Hope this helps and DFTBA. :)
Comment: As a note, with this configuration, all you would need to do is visit http://phpmyadmin.example.tld/ and it would load phpmyadmin.  You may want to configure htdigest authentication to give two layers of password checking. Or change the allow from all, to only allow ips you come from, and deny all others.
Comment: Indeed; since phpMyAdmin allows access to well, databases; securing them is a must. As a side note; make sure to also remove MySQL access to the outside world if you only have the single server doing the tasks. This can be achieved w/ IPTables.
Comment: Thanks for the input!  I'm going to give this a shot when I get off work :) For some reason I didn't think I would need another virtual host, but now I don't know why I was thinking that.  Maybe because it was 2 am...  I did set up iptables in accordance with this video (http://www.youtube.com/watch?v=JZepJ2Vx5-U), so I think I'm good there?  (found out about UFW later on).  Agree about the extra security, I'll enable that as well.  On a side note, I actually had to look up DFTBA and can say, I NEVER DO.


C# Check orientation of second screen

Question: I have written a code which rotates my 3rd display.
Now I want to check first, in which orientation the display currently is.
I wrote the following code:
<code>    int scrRectHeight = Screen.PrimaryScreen.Bounds.Height;
    int scrRectWidth = Screen.PrimaryScreen.Bounds.Width;

    if (scrRectHeight > scrRectWidth)
    {
        Display.Rotate(3, Display.Orientations.DEGREES_CW_90;
    }
    else
    {
        Display.Rotate(3, Display.Orientations.DEGREES_CW_180;
    }
</code>
This works fine, but it only works for the primary display. I can't find a definition to change it to a second display. How can I change it, or is there another method? Thanks!
Comment: Consider to not use PrimaryScreen if you meant to look at the properties of the second screen, Screen.AllScreens[1].
Comment: @HansPassant I didn't understand how to use AllScreens. It's so simple! Thanks
Comment: @HansPassant Could you add it as an answer so I can mark it?
Comment: I have a hard time identifying the brain-bug in this code.  Just share what you discovered in your own post and mark it as the answer.
Comment: [Using SetWindowPos with multiple monitors](https://stackoverflow.com/questions/53012896/c-sharp-user32-using-setwindowpos-with-multiple-monitors?answertab=active#tab-top)
Answer: There is not "SecondaryScreen" property.
Try this instead:
<code>int secondRectHeight = Screen.AllScreens[1].Bounds.Height;
int secondRectWidth = Screen.AllScreens[1].Bounds.Width;

if (secondRectHeight > secondRectWidth)
{
    Display.Rotate(3, Display.Orientations.DEGREES_CW_90;
}
else
{
    Display.Rotate(3, Display.Orientations.DEGREES_CW_180;
}
</code>
Comment: Thanks, But this is to complicated. Look at Hans Passant comment.
Comment: Updated the sample.

C# Check orientation of second screen


Determining the PMF of an internet service provider using 50 modems to serve 1000 customers.

Question: I have the exact same question as the person who asked this question: Determining the probability mass function of an internet service provider using 50 modems to serve 1000 customers.
but I couldn't comment on the provided answer (low reputation). But I don't think the one single answer to the post answers why we need to sum over all the possibilities, if there are $\geq$ 50 customers who needs a connection we need to sum from $50, ..., 1000$:
$$
P(X = 50) = \sum_{k=50}^{1000} {1000 \choose k} 0.01^k (0.99)^{1000 - k}
$$
Could somebody elaborate more on as to why we need to do the summation?
Because for when $k < 50$, this is not the case:
$$
P(X = k) = {1000 \choose k} 0.01^k (0.99)^{1000 - k}, \hspace{2 cm} k = 0..49
$$
which I don't fully understand why.
Answer: The problem is ambiguously stated. The assumption there is "customer in need of a connection is assigned to an unused device if available". With that clarification the first customer uses any 1 modem, second any other modem (and two are used) and with $k\leq 49$ it's a matter of k successes in a Binomial distrubution with probability p and 1000 trials.
With 50 or more customers there are no unused modems, X=50 for 50 successes (50 customers), 51 successes (51 customers) and so on, the probabilities need to be summed. We can also say $P(X=50)=1-\sum_{c=0}^{49}P(c\ customers\ need\ a\ connection)$, but with these values the sum will round up to 1 with low precision.
If customers could be assigned to the same modem with unused modems available, the problem is more interesting.
Comment: Thanks that clarified it!


How to use URL as a filter in view module?

Question: I asked a question here and now I am going to create a view that the view take the URL and use it as a filter.

and I want to have a the view by a dynamic filter use the URL path and show the result by different type something like sport, economy, etc.
Pathauto: news/[node:news_type]/[node:title]
I want to use [node:news_type] in my filter
Answer: You need to add a Contextual filter under the Advanced pane in your view's edit page.

Look for your field, it would probably be Content: News type then add the field
Under WHEN THE FILTER VALUE IS NOT IN THE URL select Provide default value
Choose Raw value from URL for Type
Choose 2 for Path component
Check Use path alias


A proof that the median is a nonlinear statistical functional

Question: This question is with reference to the top answer (by @StephanKolassa) to this question. Let $F$ and $G$ be CDFs and define $$H(x)=aF(x)+(1-a)G(x)$$ with $a\in [0, 1]$. Now suppose $F$ and $G$ are CDFs corresponding to Gaussian distributions with means $\mu_1$ and $\mu_2$. Also, assume that $T(F)$ is a statistical function that gives median for the CDF $F$. I want to prove that $T$ is not linear. That is: $$T(H) \neq aT(F)+(1-a)T(G)=a\mu_1+(1-a)\mu_2$$.
The answer mentioned above claims that any quantile of a Gaussian mixture is a nonlinear functional. I tried proving this by contradiction as follows. If $m$ is the median of $H$, and if the equality holds, we have: $$m=a\mu_1+(1-a)\mu_2$$. In that case, we will have:
$$aF[a\mu_1+(1-a)\mu_2]+(1-a)G[a\mu_1+(1-a)\mu_2]=\frac{1}{2}$$
However, there doesn't seem to be any way to proceed further from here which will produce a contradiction. Any help is highly appreciated.
Comment: This is a nice question, thank you! I have to admit that I like my answer. I edited my answer to the motivating question to link here.
Comment: [Take a look at this answer](https://stats.stackexchange.com/a/238495/1352), in particular equation (3), which shows the equation the median $m$ would need to satisfy. We need to show that there is no linear function $m=p\mu_A+(1-p)\mu_B$ that works in general. At some point, we will need to make use of the specific form of the normal CDF, which is where things probably get painful.
Comment: @StephanKolassa : I already had a look at it. However, as you said, probably one needs to use a particular form of CDFs. But then, I am wondering how you made the general statement about nonlinearity of quantiles.
Answer: Here is a very simple and almost-rigorous argument.
The medians of the two components are $m_1=\mu_1$ and $m_2=\mu_2$. In particular, they are independent of the components' standard deviations $\sigma_1$ and $\sigma_2$. So any weighted linear combination of the components' medians will also be independent of $\sigma_1$ and $\sigma_2$.
Now, consider our mixture. We can assume $\mu_1<\mu_2$. The median $m$ of the mixture will lie between $m_1=\mu_1$ and $m_2=\mu_2$.
We keep all parameters fixed and reduce $\sigma_1$. This shifts probability mass for our mixture to the left, so $m$ will get smaller. (*) Thus, $m$ is a (non-trivial) function of $\sigma_1$. But above, we have seen that any weighted linear combination of $m_1$ and $m_2$ will be independent of both $\sigma_1$ and $\sigma_2$, a contradiction. Thus, $m$ cannot be a weighted linear combination of $m_1$ and $m_2$.
Of course, it's statement (*) that is intuitively obvious but not yet rigorous. We still need to prove that $m$ is an increasing function of $\sigma_1$ if all other parameters are kept fixed. It may be possible to show that the defining function of $m$ per equation (3) in this earlier answer defines an $m$ that is a differentiable function of $\sigma_1$, then do some implicit differentiation (where we still probably need to argue that we can differentiate under the integral for the improper integral $\int_{-\infty}^m$) and finally find that $\frac{dm}{d\sigma_1}>0$.
Alternatively, it would be easy to take specific normals, say $N(0,\sigma_1^2)$ and $N(2,1)$ with equal weights. For $\sigma_1=1$, we have a symmetric situation, so $m=1$. We note that the $N(2,1)$ has probability mass of $0.067$ to the left of $0.5$ (R: pnorm(0.5,2,1)), so if we reduce $\sigma_1$ far enough that the mass of the $N(0,\sigma_1^2)$ to the left of $0.5$ is large enough, we can estimate that the new median $m'$ of the mixture with $\sigma_1\ll1$ definitely satisfies $m'<0.5$. For this, we just need to trust quantiles, or tables.


Improve fit by trend adjustment

Question: I have data of daily observations for 35 years and I have modeled data for the same period. The coefficient of determination ($R^2$) between them is zero (no correlation at all!).
I want to correct the bias of modeled data, particularly adjust the trend of the modeled data to improve the coefficient of determination. Can anyone please suggest any statistical technique to do that?
The data is daily rainfall for a selected area and the observation is from 1970-2004.... I got also climate model data for rainfall for the same area for historical and future period and I want to correct the data on a historical basis and then implement the parameter of that correction for future data..... but most bias correction such as quantile mapping correct the mean error and percent of bias not trend of data ... so I'm looking for method the can adjust trend of modeled data (bias correction)
Comment: Are you saying that the correlation between the actual values and the fitted values is zero? That would be strange. Or what kind of "modeled values" (if not fitted values) do you have? Also, if there is a linear trend in the data, you may include a variable that is linearly increasing with time, something like $(1,2,\dotsc,...T)$ where $T$ is your sample size. If the trend has some other shape, you could do an analogous trick.
Comment: Hi, yes r2=0 and the modeled data is rainfall data from projected climate model (not my model) and I have observed data for same period I want a bias correction technique to correct trend (improve r2)
Comment: What kind of bias correction are you talking about? Also, if the modeled data is uncorrelated with the real data, that sounds like a very bad starting point...
Comment: The data is daily rainfall for a selected area and the observation is from 1970-2004.... I got also climate model data for rainfall for the same area for historical and future period and I want to correct the data on a historical basis and then implement the parameter of that correction for future data..... but most bias correction such as quantile mapping correct the mean error and percent of bias not trend of data ... so I'm looking for method the can adjust trend of modeled data
Comment: Could you update your post with the details you have already included in the comments, and also write more about the model you are using? It is difficult to help you given the current level of details.
Answer: If you are talking about a constant bias, I think that what you intend to do is impossible. Zero correlation means that the slope of the regression line between the two datasets is zero; changing the offset (+-constant bias correction) cannot correct the slope.
If you are talking about a slow-varying bias (i.e. trend, drift, smooth signal, etc.), you may want to investigate detrending techniques. First, you should guess what kind of trend you have, it can be a linear drift, a seasonal component (common in Earth science datasets), etc.. You can try moving average with different window sizes to reveal hidden trends; if you are familiar with signal processing you can take a look to wavelet decomposition.
Hope that helps.

Improve fit by trend adjustment


How to clean a smelly flute?

Question: I've been playing the flute for a while, an noticed that my flute headjoint is smelling a little funky. How do I clean it, and is it safe to wash the headjoint (after removing the cork)?
P.S. - I have a silver-plated nickel flute.
Comment: No, that question refers to just cleaning the inside of the flute. My question is not how to clean, but deodorise the inside of the flute.
Comment: The accepted answer is about cleaning your flute so I can't see why it isn't a duplicate of the one linked.
Comment: There is no accepted answer and the questionis for how to clean the flute. I know how to clean it, but my question is how to deoderise it. This information is not given in the answers of that question.
Comment: The answer you accepted is about just cleaning a flute which is the same thing the other answers go over.
Answer: There are plenty of tutorials for cleaning instruments online, for example:

Taylor Music's "Piccolo / Flute Cleaning Instructions"
UNLV School of Music's "Instrument Hygiene"
Jennifer Cluff's "How to Clean a Flute"

In summary though, a cloth and a small amount of rubbing alcohol should be enough to clean your flute once the cork is removed. If rubbing alcohol does not work, it might be worth taking your flute to someone who cleans and repairs instruments like flutes professionally (similar to having a guitar set up or a piano retuned). Getting a professional to give it a thorough clean is almost always worth it, and they may offer some professional advice on instrument maintenance for the future if you ask.

How to clean a smelly flute?


Beginner question - chords in the Japanese InSen scale

Question: I'm a beginner but I've been learning music theory and practicing on a MIDI keyboard and FL Studio DAW.    Just as I was learning basic chords and chord progressions in western music I was introduced to the Japanese In Sen scale, one of several pentatonic scales common in Japanese music.  I quite enjoy it and writing little compositions in it, and as I've been listening to koto music I often hear them accompanying the main melody line with chords.
I want to learn about how to construct pleasant-sounding chords for such a scale with its wide intervals.   In the western scales the chords and progressions that I've been learning are all diatonic for whatever scale I'm using.   Should all the notes in the chords I use with the InSen scale come from that scale?   Are there suggested formulas or sets of intervals that I can apply to creating chords in the InSen or other similar scales?  Is there any concept of "leading chords" that applies to this kind of music?
NOTE:  I may have the "In" and "In Sen" scales confused - in different texts I see the terms used a little differently, but the gist of the question remains -  how to construct chords in pentatonic scales with wide/irregular intervals.
Comment: Can you give examples of such music? The Wikipedia page for the Insen scale suggests that people use other "compatible" chords that may have notes outside the Insen scale, but so that the chords don't clash with the scale notes, which are used for "soloing". https://en.wikipedia.org/wiki/Insen_scale
Comment: _Can you give examples of such music?_    A well known traditional piece of music that's often played in the InSen scale is "Sakura"
Comment: I meant, an example of a recording of a full arrangement, with backing chords and everything. The Wikipedia page suggests that some people do it by using chords and notes from outside the pentatonic scale, but so that the chords are compatible with the pentatonic scale. Example chords are given on the Wikipedia page. By the way, I think Sakura uses the Hirajoshi scale, not Insen.
Comment: Btw, Sakura starts (4/4) a a b__ |a a b__ |a b c b |a ba f__ |e c e f |e ec b__ |  (that last note's a seventh below the first note) So it's a Phrygian pentatonic of some kind.
Comment: @OldBrixtonian - And Sakura with a starting note of A ends with "Mi ni yu kan" playing back as D E F A | BA F E__ |. Thus piiperi's statement that it uses Hirajoshi.
Comment: Wikipedia says the in scale is also known as the Sakura scale [link](https://en.wikipedia.org/wiki/In_scale)       ...but anyway, getting back to the topic, does anyone know anything about how chords are constructed for any of the common Japanese 5-note scales (In, InSen, Yo, Hirajoshi, etc)?   Doing web searches it's easy to find all kinds of advice about chords and chord progressions in western music, but even though I hear lots of chord accompaniment on traditional koto pieces I can't seem to find any information about chords in those scales.
Comment: Actually, I found one, and it says it's in the In Scale, to boot, although I'm really interested in learning the basic principles of constructing pleasing chords in any of these Japanese pentatonic scales with their wide and irregular intervals.  [link](https://www.youtube.com/watch?v=h_ng-KcfI-s)      As I said, there's tons of advice on the web about constructing chord accompaniment in western heptatonic scales, but I've found little for Japanese pentatonic ones.
Comment: Can you post a link to a recording of a traditional koto piece that has the kind of chord accompaniment you want to create.
Comment: @piiperi Reinstate Monica  What was wrong with the link I provided?
Comment: Oh that one, sorry. Forget about the pentatonic stuff for a second and look at it as just a song in G minor. Transcribe it and look at what notes and chords they're using. In a few places they're even playing a Cm chord loud and clear. C is not in the D, Eb, G, A, Bb five-note set. Is that cheating, or just a traditional thing to do every now and then? I don't know. How many different three-note chords can you make from the note set? Four-note chords? Put one of the chord notes in the bass. You'll get things like Ebmaj7-5 and Gm add2 /D. Or play _all_ the notes with one of them in the bass.
Comment: Check this out, OP: https://ianring.com/musictheory/scales/1187
Answer: Here's my beginner answer, based on only common sense, not knowledge of Japanese music, except what I could quickly find on English web pages.
How to make chords from a scale - by combining notes from the scale. And I'll assume one of the notes is a bass note, so for "chord progression" purposes we'll differentiate between chords containing the same notes depending on what the lowest note is.
As far as I can tell, applying ad-hoc combinatorics, here are all 3-note chords in the Hira-choshi or Hirajoshi pentatonic scale (meaning "regular tuning" according to this web page), 1:D, 2:Eb, 3:G, 4:A, 5:Bb.

Here are 4-note chords:

And finally, 5-note chords:

So, how to select which chord to use? My Western musical common sense tells me to look at them as chords in a Gm key context. Chords with D in the bass work as some kind of D or /D chords. Chords with A in the bass work like stuff in Gm works when it has A in the bass. Etc. For example:

1-3-5 is Gm/D in Western chord naming
3-5-1 is Gm
2-3-4 is Eb-5
2-3-5-1 is Ebmaj7
2-3-4-1 is Ebmaj7-5
3-4-5-1 is Gm add2
1-3-4-5 is Gm add2 /D
1-2-3-4 is something like Dsus4 add b2. Works like a Dsus4 but with an oriental twist.
4-1-2-3 is a bit like Cm6add2/A, but with the C omitted.

So, combine notes from the scale and use the chords like you would use them in songs in the key of Gm.
Which of them sound nice? Pretty much all of them, IMO. Something like 3-4-5 i.e. G-A-Bb in tight voicing feels a bit pointless, but if you spread out the voicing to different octaves, it's an awesome chord. Does it sound Japanese? Beats me - you should ask someone who knows Japanese traditional music.
Answer: If you are expecting to build chords in thirds on each scale degree, it will not work as it does for a major scale, because pentatonic scales use steps larger than whole and half steps.
That isn't necessarily a problem. You just need to re-orient (no pun intended) your thinking about harmony away from stuff like I V vi IV.
One approach is to use drone notes. You can hold primary tones like the first, fourth, or fifth scale degrees in the bass. Those basses could be harmonized with octaves or fifths. Most of the accompaniment could be a tonic drone with auxiliary shifts away to fit the melody. For the In scale on E you could try an octave on E with auxiliaries of A with a perfect fifth E above or F with perfect fith C above.
Another approach is closer to diatonic harmony. Use major/minor triads where available, incomplete triads to get around "missing" scale tones, or simply use chords that "fill in" the missing tones. Consider the In scale on E. There is no G in the scale so you could omit the third on a tonic chord. Chords Am and F can harmonize all tones of the scale except B. If you "fill in" the scale with D and G just for the accompaniment (sort of makes a phrygian scale) you could then use chords like Dm (a bVII chord which is popular for accompanying folk tunes.) Below is an example of Sakura that takes this approach...

Look at https://imslp.org/wiki/Cherry_Blossom_(Takaori%2C_Sh%C5%ABichi) for another example of accompaniment for Sakura.
Another approach is a bit more "modern." It's sort of like the drone note idea and could also incorporate a bit of "filling in" the scale like the second approach. Instead of using triads use chords built of fourths or fifths like B E A or A E B. Those two qu(ar/in)tal chords can accompany the beginning of the first line of Sakura and then the ending of that line could be Dm to F/C.
You can experiment with other idea of course (no reason to avoid tone clusters or other experimental things.) But, keeping the accompaniment mostly tonic with brief auxiliary moves away is a safe approach. Especially if music has a folk tune feel like Sakura.
Answer: Traditional Japanese music has no chords.  It is monophonic (or more accurately heterophonic - several instruments may play the same line simultaneously but with different ornamentation).
Putting chords to traditional Japanese music would be a modern 'Western' addition.  Of course you can do that, but you're not going to find guidance on it from any traditional Japanese music theory; you'll have to find the guidance from Western music theory.
Comment: OP gave this link https://www.youtube.com/watch?v=h_ng-KcfI-s It indeed does have chords, and pretty ones too. There's a clear bassline that's not a constant single-note drone, and combined with the rest of the notes it can easily be seen as a chord progression. If you can link to a source that explains how that song isn't proper traditional Japanese music, it would be interesting.