Lilypond with LaTeX

Question: Can someone ELI5 the process? I've tried reading the guide from
http://lilypond.org/doc/v2.18/Documentation/usage/an-example-of-a-musicological-document
but it doesn't seem to work. I am on Windows 10, and I have Lilypond 2.18.2 installed. That's everything I've done so far.
Here's what I've tried.
In a text editor, I copy and pasted the code
\documentclass[a4paper]{article}

\begin{document}

Documents for \verb+lilypond-book+ may freely mix music and text.
For example,

\begin{lilypond}
\relative c' {
  c2 e2 \tuplet 3/2 { f8 a b } a2 e4
}
\end{lilypond}

Options are put in brackets.

\begin{lilypond}[fragment,quote,staffsize=26,verbatim]
  c'4 f16
\end{lilypond}

Larger examples can be put into a separate file, and introduced with
\verb+\lilypondfile+.

\end{document}

Then I saved the file as lilybook.lytex
Then I pressed Start, and type in DOS. Something called a command prompt shows up, and I click it. Then I type in after C:\Users\[name]>, starting with a space,
lilypond-book --output=out --pdf lilybook.lytex

Then, it shows
'lilypond-book' is not recognized as an internal or external command, operable program or batch file.

So clearly there's something I did wrong or am missing. I am very confused, and I would like to finish a paper. Please help. Thank you.
Comment: This might be better suited for [TeX.SE](http://tex.stackexchange.com).
Comment: @Richard I disagree. Lots of people use LaTeX on Windows, but most of them will never have used Lilypond.
Comment: @leftaroundabout Fair enough. I just know there are several questions on TeX.SE regarding `lilypond-book` that have been addressed.
Answer: The installation instructions will have told you how to set the system PATH to include the LilyPond executables.  Have you done this?
After that has been done, obviously you also need the latex.exe of a TeX distribution in your system PATH.  The usual way for that is to install TeXlive these days.
Then you want to use the Windows command line, not DOS (Windows is 32bit or more, DOS is 16bit).
Comment: No, I use Frescobaldi (an outside program) to operate lilypond. How would I go about doing whatever that is? I use MikTeX distribution, so I don't know about latex.exe either. How do I get to the windows command line?
Comment: @Ilyankor I haven't used Windows in a while, but I would try it in the PowerShell console. You may also want to search if Frescobaldi doesn't have support for Lilypond books. — Generally speaking though, I _would_ recommend you do this kind of stuff on a Linux-based OS, not on Windows. You can easily install one in a virtual machine, without needing to compromise your Windows installation.
Comment: @Ilyankor Read "Running on the command-line" on the right side of the page [http://lilypond.org/windows.html](http://lilypond.org/windows.html).
Answer: To mix LaTeX and Lilypond is a - let's say - long work to do. I suggest, to do it the same way I do it. I first create snippets (what lilypond2latex also does) and insert them manually.
I have this lilypond header:
\version "2.18.2"

systemhoehe = 10

\paper{
  annotate-spacing = ##f
  indent=0\mm
  short-indent = 0\mm
  paper-width = 150\mm
  paper-height = 50\pt
  oddFooterMarkup=##f
  evenFooterMarkup=##f
  oddHeaderMarkup=##f
  evenHeaderMarkup = ##f
  bookTitleMarkup = ##f
  scoreTitleMarkup = ##f
  print-page-number = ##f

  left-margin = 0
  right-margin = 0
  top-margin = -5\pt
  bottom-margin = 0
  top-system-spacing.basic-distance = 15\pt
  markup-system-spacing.basic-distance = 0\pt
  top-markup-spacing.basic-distance = 0\pt
  system-system-spacing.basic-distance = 200\pt

}

\score{
  \layout {
    \context {
      \Score
      \remove "Bar_number_engraver"
      \override SpacingSpanner.base-shortest-duration = #(ly:make-moment 1/20)
    }
  }

  \new Staff <<
    \new Voice{
      \relative c'{ \key d \major \partial 4 a4 d2 e4( g) fis fis8 e d4 e
      }

    }>>
}

This will create snippets which you can insert with
\includegraphics[width = \linewidth, page = 1]{./someDir/song.pdf}

You can check out my package in alpha version github. I created it for covering that problem (mixing LaTeX and lilypond) and for reusing songs.
Comment: Wow, this looks great! Can you include a PDF of the compiled Demoprojekt in the repo for us to check out?
Comment: @Richard Yes. I just didn't do it, because I'm trained to save space. Just did it. Should appear in a few minutes.
Answer: This code is not for windows, but rather a Mac- or Linux-based system. You will either have to get a Mac/Linux/GNU system, or install a virtual machine to use the code and program.
The giveaway is the Processing code, the second line has "GNU", which is a different type of Unix/Linux.
Additionally, this question would better be suited in StackOverflow.SE or TeX.SE.
Comment: GNU does in this case not refer to any operating system (what's usually called "Linux" is indeed a GNU OS, but Mac OSX is not), but simply to the fact that Lilypond itself is a GNU project. And GNU programs can normally be run just fine on Windows, though I haven't used Lilypond on Windows myself.
Comment: @leftaroundabout Thank you! From a quick google search, I assumed, because of all the text saying "GNU NOT LINUX", they were separate programs.
Comment: @icedtea yeah, it's a bit weird – GNU was originally supposed to be just an OS, however the project only developed lots of great helper programs but never really got the _OS kernel_ working. This gap was then filled by Linus Thorvalds, separately. In the end ever more programs were added to GNU, and it came to be that we have "Linux operating systems" supported by a "GNU ecosystem".
Comment: That's at least how the FSF / GNU people like to phrase it. And it's pretty accurate as far as early Linux OSs are concerned. However, most modern Linux distributions contain lots of free software that's neither part of GNU nor of Linux.
Comment: @leftaroundabout So basically, Linux just filled the OS kernel gap, and everything else is GNU?
Comment: This answer is absolutely incorrect, both lilypond or lilypondbook work absolutely fine on Windows. As I have pointed out to the OP at [StackOverflow](https://stackoverflow.com/a/53510140/2679297), it is just a matter of installing and configuring them properly. Though not all GNU applications can be installed on Windows, LilyPond is one of those which are certainly available for Windows.
Comment: @gilbertohasnofb However, the code would not work in the Windows command line. You would have to use a third-party command line, and I'm going to reserve that for StackOverflow.SE. As I pointed out, **the code is not for windows.** Everything is perfectly fine with this claim.
Comment: @icedtea what are you talking about? The solution did not involve any third-party command line. The OP had not followed all the instructions installing lilypondbook, which is why there was a problem. I pointed him to the correct installation, he did so and, voila, it works on Window's default command prompt. You are spreading misinformation.
Answer: Guessing that the installation was incomplete somehow...
Replacing folder with wherever lily pond was installed:
c:\folder\lilypond-book --output=out --pdf lilybook.lytex
The path may end up on your system for example C:\Program Files (x86)\LillyPond\usr\bin\lillypond-book or C:\Program Files (x86)\LillyPond\usr\bin\lillypond-book.exe
Answer: I would process the lilypond seperately, it will create a pdf file.  I would convert the pdf into a graphic (cut and paste the music into ms paint or gimp (even better!)), then insert the graphic into LaTeX.
Comment: LaTeX can include pdf pages directly with `\includegraphics[width=0.5\linewidth, page=3]{myfile}`. pdflatex can do it and lualatex also. Advantage: You include it as a vector graphic, which is always razor sharp and never blurry.

Lilypond with LaTeX


How can I set up an a SQLite memory database to improve PHPUnit test speeds?

Question: I'm trying to speed up a functional Drupal test.
Given a test...
...
  public function the_front_page_loads_for_anonymous_users() {
    $this->config('system.site')
      ->set('page.front', '/node')
      ->save(TRUE);

    $this->drupalGet('<front>');

    $assert = $this->assertSession();
    $assert->pageTextContains('Welcome to Drupal');
    $assert->pageTextContains('No front page content has been created yet.');
  }

This test runs really slow against my database ... 2+ mins.
If I use a test sqlite database, it drops to around 1.6 mins
<env name="SIMPLETEST_DB" value="sqlite://localhost/logs/test.sqlite"/>
If I use a in-memory database, <env name="SIMPLETEST_DB" value="sqlite://localhost/:memory:"/>, Drupal detects no database and runs install.php
How can I set up an sqlite memory database to improve test speeds?
Answer: On Linux, we use sqlite://localhost/dev/shm/test.sqlite where /dev/shm is memory mapped
Comment: OK ... unfortunately I'm on a work PC, which runs Win10 and I have been unable to get hardware virtualization working which prevents me from using WSL2.
Comment: Thank you for sharing your approach though. I appreciate it. Hopefully, next upgrade cycle, I can implment a Docker or WSL2 solution. I'll be sure your try out your method. :)


Time series analysis: Determine if trend is deterministic fluctuating/stable or stochastic

Question: I am analysing sales data of certain products and need to determine if the demand trend is  deterministic fluctuating or deterministic stable or stochastic.
How do I do that in R / what approach is usually applied to do so?
Quarterly values would be for example:
2424,3030,3207,2943,2631,2863,2711,2837,2839,2876,3075,2886,2520,3136,3235,3071,2923,3237,
3054,3321,2856,3389,3092,3325
Answer: Trends can be of the form
$$y(t)=a+bt+ct^2$$  OR
$$y(t)=y(t-1)+\theta_0$$ OR
$$Y(t)=a+b x_1+ c x_2$$
etc  where $x_1=1,2,3,4....t$ and $x_2=0,0,0,0,0,1,2,3,4$ thus one trend applies to observations $1-5$ and a second trend applies to observations $6$ to $t$.
if you wish you can post your data
EDIT after data was posted:
A plot of the ACF suggests that the series is stationary thus no trend is required. . This led directly to an AR(2) model /(2,0,0)(0,0,0) with a seasonal pulse reflecting consistent first quarter effect.  . The residual plot shows little structure thus randomness can be reasonably accepted. . This is confirmed by the ACF of the residuals  . The Actual/Fit/Forecast nicely summarizes the results
Comment: @Whuber I should have added that the actual data is useful to empirically identify which of these states of nature is most  applicable  thus answering the question by example as there is no theoretical answer as far as I know.
Comment: $\TeX$ formatting is no more difficult than what you originally wrote and is *much* more readable. You can accomplish this yourself by enclosing math expressions in dollar signs (shift-4 on most keyboards).  Doubling the dollar signs will produce centered paragraph-style expressions.  BTW, how does this post answer the question?
Comment: I added some example data.
Comment: Re your analysis: many people, upon seeing no significant autocorrelation, would proceed to test for trend by regressing the values against time and would likely include a seasonal dummy. The result is highly significant (F(4,19)=10.06, p=0.00015); the diagnostic tests are decent; and its forecasts will be substantially greater than yours. Although that does not exactly contradict your results--these are two different procedures with different assumptions, after all--it would be interesting to consider why these two methods produce such different results.
Comment: The problem with using an ad hoc model (not based upon sound analytics )  is that if the series has a level shift you will falsely assign trend rather than a simple (permanent) movement of the mean to a new level.Notice that the seasonal dummy for the first quarter was found automatically thus proxying the human eye.
Answer: Generally, in observational data it is difficult to distinguish the trend-stationary series from random walk. You called them deterministic and stochastic.
The trend-stationary process is $x_t=\beta_0+\beta_tt+\varepsilon_t$, while RW is $x_t=x_{t-1}+\beta_0+\varepsilon_t$.
Consider a very well researched time series such as GDP. The economists are still debating whether it's trend-stationary or RW, e.g. see this paper on German GDP. You can also see how they try to determine if the series is RW or not.
Comment: What would I do then, I need to justify what approach (heuristic approach for trend-stationary, stochastic for RW) I should use to determine future order quantities?
Comment: @MartinZotter, one thing is to look at what others do, e.g. that paper on German GDP. However the best approach is to come up with a good theory explaining the underlying phenomenon. For example, we have a theory for radioactive decay, and when we process its data we know which model to fit (exponential growth).


probability with replacement ("at least" scenario)

Question: I am trying to improve my stat skills from a book (Freedman et al, 2007, Statistics) that gives an exercise, I cannot get my head around.
It goes like this:

There are $5$ green balls and $1$ red ball in a box. We draw four times randomly with replacement. What is the probability that we draw at least two red balls?

My guess would be:
$(1/6)^2 + (1/6)^3 + (1/6)^4$, because the probability of at least $2$ red balls out of $4$ draws must be equal to drawing two or three or four times a red ball. Hence I would use the addition rule, which gives $0.03 = 3$ percent
However, the book says it is $13$ percent, and gives the following explanation,
$$\frac{150+20+1}{1296}$$
Why is this so?
My attempt to trace back the terms:
I can possibly see how it got the first and third term in the fraction: The first could be $(5/6)^2 = 25/36$, which is the probability of drawing two green balls; and the third could be $(1/6)^4 = 1/1296$, which is the probability of drawing four red balls. I have no idea though where they could possibly get the $20$ from.
Thanks
Comment: The logic is correct.  The terms are wrong.   See Mark's answer.
Answer: The probability of getting exactly 2 red balls is
$$
\left(\frac16\right)^2\left(\frac56\right)^2\binom{4}{2} = \frac{25}{1296}\cdot 6
$$
where the binomial coefficient is just the number of ways you can select which two picks, out of the four, got red balls.
The probability of getting exactly 3 red balls is
$$
\left(\frac16\right)^3\left(\frac56\right)^1\binom{4}{1} = \frac{5}{1296}\cdot 4
$$
where the binomial coefficient is just the number of ways you can select which one pick, out of the four, got a red ball.  That is where the $20$ comes from.
Can you take it from here?
Comment: Yes, the probablity of getting exactly 4 red balls is:
(1/6)^4 x 4!/(4! 0!) = 1/1296
I forgot the binomial formula, thank you!


sample space and observational units

Question: In stat courses the concept of observational unit is fundamental. When sampling from a population, each element in the sample is called an observational unit (sometimes referred to as an individual). So a sample of size 10 contains 10 observational units (even it the sampling is done with replacement). Each observational unit can have various attributes or variables associated with it. For example, sampling a bunch of cpus from a cpu manufacturing process, each cpu has a clock speed, a physical length, a weight, etc. Sometimes the sample space for this experiment is written as the set of possible weights, or the set of possible lengths, etc. However it seems more accurate to say that the sample space is the set of observational units and that each of the aforementioned variables are random variables which map from the set of observational units to that particular variable's values.
I am stuck however and I don't see how to carry this framework over to an experiment of rolling a single die, or tossing two coins. For example, what are the observational units when I toss two coins? Shouldn't there be 4 of them so that I can get a sample space with the same cardinality as {HH, HT, TH, TT}? Any pointers on this would be appreciated.
Answer: For the CPU example, the sample space is composed of all possible draws of a cpu. Each CPU has some probability of being drawn, which may not be uniform. For example, let $\omega_i$ represent drawing CPU $i$, then our sample space $\Omega$ can be represented as $\{ \omega_1,\omega_2,...,\omega_n\}$ and we can say $P(\omega_i)=p_i$ is the probability of drawing that CPU. Now, as you said, we have a number of random variables $W(\omega), S(\omega), L(\omega)$ etc. that map these units to numbers. What we are doing is mapping the "fundamental" outcome (drawing a cpu) with a derived outcome (measured weight, length, etc). Note there that the actual randomness comes from the sampling process, not the cpus themselves (which supposedly have fixed weights, lengths, etc).
Contrast this with the coin and die examples. Here, the randomness is inherent in the object itself, so our sampling process is not over objects but observations or outcomes of a single object. Hence, the equivalent of, say, the (deterministic) length of a randomly chosen cpu is the actual observed value of the die or coin.
Fundamentally, both sample spaces focus on the random elements of an experiment (cpu's or coins/die values), but that doesn't always imply the sample space consists of different objects. A single object can supply all outcomes for a sample space. As an aside, we could model the cpu experiment as repeated observations of a single cpu that has random length, weight, speed. In this case it would be an exact analog to a die or coin. Mathematically, they are equivalent, but physically, one is wrong.
Comment: The advantage of the observational unit approach is that we can map from the unit to a derived outcome or variable. When we toss two coins we can map to a variety of derived variables as well (eg. number of runs, number of heads, etc.) so perhaps I can say that the observational units are the "primary outcomes" by which I just mean  {HH, HT, TH, TT}. Then I can say, in the same way that I sample from the  population of cpus, I am sampling from this set. Does this work?
Comment: however, I would not know how to define primary outcomes
Comment: @matt makes sense to me :-)

sample space and observational units


FILTER row level records based on config table entry and user sessions in Snowflake

Question: I am trying to do below
I have created one config table like below

Now I want to create a view using this config table and the with specific user who is selecting this view, the user should see only those value for which user is allowed as per config table.
SELECT * FROM MAINTABLE INNER JOIN CONFIG_ACCESS
ON MAINTABLE.ALLOWED_EMPID = CONFIG_ACCESS.ALLOWED_EMPID
AND MAINTABLE.ALLOWED_DEPTID= CONFIG_ACCESS.ALLOWED_DEPTID
AND MAINTABLE.ALLOWED_COUNTRY= CONFIG_ACCESS.ALLOWED_COUNTRY

Here with this "AND", nothing returns.
Ideally, it should dynamically set the INNER JOIN condition based on user logged in.
Like if user : firstname.lastname@example.com is logged into snowflake , for him the join would be with "ALLOWED_EMPID".
if the user is email@example.com , for him the join would be with "ALLOWED_DEPTID".
I am trying to code as below
SET USERID=CURRENT_USER();
--SELECT $USERID
SET JOIN_COL =
(SELECT CASE
    WHEN ALLOWED_EMPID <> 'NA' THEN 'ALLOWED_EMPID'
    WHEN ALLOWED_DEPTID <> 'NA' THEN 'ALLOWED_DEPTID'
    WHEN ALLOWED_COUNTRY <> 'NA' THEN 'ALLOWED_COUNTRY'
END
FROM CONFIG_ACCESS AS CONFIG_ACCESS WHERE CONFIG_ACCESS.USERID = $USERID);

--SELECT $JOIN_COL -- DEPT01

SELECT distinct T0.DEPT01 FROM  MAINTABLE  AS T0
inner join CONFIG_ACCESS AS T1 ON T0.DEPT01 = T1.$JOIN_COL

But it errors out
SQL compilation error: syntax error line 2 at position 54 unexpected 'ON'.

Is there a way to dynamically do this?
Comment: Hi - it looks like you are trying to achieve ROW based access control i.e. limit which rows a user can see in a table, rather than limit whether a user can query a table at all. RBAC is commonly used to mean ROLE based access control, hence my confusion. Can you confirm that you are trying to implement ROW based access control? If you are, have you read Snowflake's documentation on the subject, which has lots of examples: https://docs.snowflake.com/en/user-guide/security-row-intro.html
Comment: Yes, i am trying to limit the rows from a view based on the condition provided in config table. I have gone through the documentation. But here my requirement is based on user the filter will change, it can be EMPID or DEPTID or COUNTRY. Hence dynamically the join should take place
Answer: It sounds like you want Using Secure Views with Snowflake Access Control


Rational distances in triangle

Question: Given triangle with sides of length $3, 4$ and $5$ prove that if $P$ is a point inside the triangle, then  rationality of sum of distances from the point $P$ to the vertices implies rationality of sum of distances from the point $P$ to the sides of the triangle. Any hints?
Answer: Attempt to solve:

Let $A(3;0); B(0;4); C(0;0); P(x;y)$.
Let $S_1=PA+PB+PC=\sqrt{(x-3)^2+y^2}+\sqrt{x^2+(y-4)^2}+\sqrt{x^2+y^2} \in Q$
Let $d(P;l) - $ distance from a point $P(x_0;y_0)$ to a line $l:ax+by+c=0$. Then
$$d(P;l)=\frac{|ax_0+by_0+c|}{\sqrt{a^2+b^2}}$$
$$AB: \frac x3+ \frac y4=1$$
$$AB:4x+3y=12$$
$$d(P;AB)=\frac{|4x+3y-12|}{5}$$
$$S_2=x+y+\frac{|4x+3y-12|}{5} \in Q?$$

Rational distances in triangle


Views, how to construct multiple joins

Question: I have a node activity with fields referencing the node location and a node sport_type. As in, for each activity I need to add a location and a sport type.
On the other hand I also have a node admin with references to location and sport_type. As in, I can create an admin for each sport_type and each location.
How can I create a view which results in the admin when an activity nid is given?
In SQL I would write something like:
SELECT  admin.name
FROM    admin
JOIN    activity ON activity.location_id = admin.location_id
        AND activity.sport_type_id = admin.sport_type_id
WHERE   activity.nid = :nid

I try to create a similar query using the ui of views, where the activity_id would be passed in through the url path. I don't know how to implement the join though... Any tips? (Using Drupal 7)
Answer: What you're looking for is often called "siblings".
When sharing the same Taxonomy terms there are Contextual filters Has taxonomy term that can be used and this can work in a lot of cases.
But there are cases even with shared Taxonomy that needs to go a different route (possibly when using Aggregation or Multilingual sites). That second "sibling" route is also what you need to use when the connection is done through an Entity Reference field that isn't Taxonomy, like it is in your case.
The solution is done with the help of two Relationships and one Contextual filter.

Create the Content type Views showing Admin nodes. You first add the Relationship for your ER Location field, this introduces info about the referenced node into the Views. In your case this is the info about Location node referenced from Admin nodes.
Then you add the reverse Relationship to the first one, it will use the first Relationship by default, this is where the matching happens. The second Relationship introduces info about the content that is using that ER field. In your case this is all the Activity nodes that point to the same Location.
Add the Contextual filter for Node ID and make it use the second Relationship. Set it the usual way, default value and ID from URL, validate against Activity Content type.
If this is a Block Display set it to display in a theme region on Activity nodes and adjust its Contextual filter settings. Now when you visit an Activity node you will see listed all the Admin nodes that share the same Location ER.

Repeat the procedure for the second ER field Sport type. You will have 4 Relationships and 2 Contextual filters in the end. Don't build everything at once, test step by step and build it all for only one ER field first.
When building for the second ER field you can use the keyword all in Views Preview to "shortcircuit" the first Contextual filter so you can test the second one directly, without interference from the first one (you enter values into Preview separated with / for each Contextual filter you have, for example all/34 to bypass the first Contextual, all/all to bypass both Contextuals, or 34/34 to test for the Activity node with the NID 34).
This answer has a bit more details for a similar example:  Entity Reference widget selctor in view referring same reference

Views, how to construct multiple joins


Pass the data from CPU to GPU without explicitly passing it as a parameter

Question: Is it possible to pass the data from CPU to GPU without explicitly passing it as a parameter?
I don't want to pass it as a parameter primarily for syntax sugar reasons - I have about 20 constant parameters I need to pass, and also because I successively invoke two kernels with (almost) same parameters.
I want something along the lines of
__constant__ int* blah;

__global__ myKernel(...){
    ... i want to use blah inside ...
}

int main(){
    ...
    cudaMalloc(...allocate blah...)
    cudaMemcpy(copy my array from CPU to blah)

}

Comment: Why not instead pack your parameters up into a structure? Laundering parameters through global variables should be avoided.
Answer: cudaMemcpyToSymbol seems to be the function you're looking for. It works similarly to cudaMemcpy, but with an additional 'offset' argument which looks like it'll make it easier to copy across 2D arrays.
(I'm hesitant to provide code, since I'm unable to test it - but see this thread and this post for reference.)
Answer: use __device__ to apply global variables. It's similar to the way of using __constant__
Answer: You can take some approaches. It depends on how you are going to use that data.

If your pattern access is constant and threads within a block read the same location, use __constant__ memory to broadcast the read requests.
If your pattern access is related to the neighbors of a given position, or with random access (not coalesced), then I'll recommend use texture memory
If you need read/write data and know the size of your array define it as __device__ blah[size] in your kernel.

In example:
__constant__ int c_blah[65536]; // constant memory
__device__ int g_blah[1048576]; // global memory

__global__ myKernel() {
    // ... i want to use blah inside ...
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    // get data from constant memory
    int c = c_blah[idx];
    // get data from global memory
    int g = g_blah[idx];
    // get data from texture memory
    int t = tex1Dfetch(ref, idx);
    // operate
    g_blah[idx] = c + g + t;
}

int main() {
    // declare array in host
    int c_h_blah[65536]; // and initialize it as you want
    // copy from host to constant memory
    cudaMemcpyToSymbol(c_blah, c_h_blah, 65536*sizeof(int), 0, cudaMemcpyHostToDevice);
    // declare other array in host
    int g_h_blah[1048576]; // and initialize it as you want
    // declare one more array in host
    int t_h_blah[1048576]; // and initialize it as you want
    // declare a texture reference
    texture<int, 1, cudaReadModeElementType> tref;
    // bind the texture to the array
    cudaBindTexture(0,tref,t_h_blah, 1048576*sizeof(int));
    // call your kernel
    mykernel<<<dimGrid, dimBlock>>>();
    // copy result from GPU to CPU memory
    cudaMemcpy(g_h_blah, g_blah, 1048576*sizeof(int), cudaMemcpyDeviceToHost);
}

You can use three arrays in the kernel without pass any parameter to the kernel. Note this is only an example of use and not an optimized use of the memory hierarchy, i.e.: Use the constant memory in this way is not recommended.
Hope this help.
Comment: yes, that will work, although it will generate compiler warnings on compute 1.x targets.
Comment: Approach 3 won't work. `__device__` declarations inside a function body is illegal in CUDA.
Comment: @talonmies But we can declare the \__device__ at the global scope of the file, can't we?
Comment: Thanks, but is it possible to do that if I don't know the size of c_blah in advance? As in - I know in advance before the kernel launch, but I don't know it at the compile time.

Doing __constant__ float* c_blah, followed by cudaMalloc() and cudaMemcpyToSymbol does not seem to work too well.
Comment: @cheshire You can not allocate device memory dynamically. You need to define your device pointer int *c_blah and allocate the memory for it in the CPU.
Comment: Regarding to the previous comment. You can not allocate device memory dinamically in a kernel. Of course you can do it in the host, as you already tried with cudaMalloc() and cudaMemcpyToSymbol.


Add TransformGroup to a FramworkElement when rendering WPF to a PNG

Question: I've got an app that turns some XAML Usercontrols into PNGs - this has worked really well up to now, unfortunately I now need to double the size of the images.
My method (that doesn't work!) was to add a ScaleTransform to the visual element after I've loaded it ...
This line is the new line at the top of the SaveUsingEncoder method.
visual.RenderTransform = GetScaleTransform(2);
The PNG is the new size (3000 x 2000) - but the XAML is Rendered at 1500x1000 in the centre of the image.
Can anyone assist please?
<code>    private void Load(string filename)
    {
        var stream = new FileStream(filename), FileMode.Open);
        var frameworkElement = (FrameworkElement)(XamlReader.Load(stream));

        var scale = 2;

        var encoder = new PngBitmapEncoder();
        var availableSize = new Size(1500 * scale, 1000 * scale);

        frameworkElement.Measure(availableSize);
        frameworkElement.Arrange(new Rect(availableSize));
        name = name.Replace(" ", "-");
        SaveUsingEncoder(frameworkElement, string.Format(@"{0}.png", name), encoder, availableSize);
    }

    private TransformGroup GetScaleTransform(int scale)
    {
        var myScaleTransform = new ScaleTransform {ScaleY = scale, ScaleX = scale};
        var myTransformGroup = new TransformGroup();
        myTransformGroup.Children.Add(myScaleTransform);
        return myTransformGroup;
    }

    private void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder, Size size)
    {
        visual.RenderTransform = GetScaleTransform(2);
        var bitmap = new RenderTargetBitmap(
            (int) size.Width,
            (int) size.Height,
            96,
            96,
            PixelFormats.Pbgra32);
        bitmap.Render(visual);

        var frame = BitmapFrame.Create(bitmap);
        encoder.Frames.Add(frame);

        using (var stream = File.Create(fileName))
        {
            encoder.Save(stream);
        }
    }
</code>
Comment: What happens if you call visual.[UpdateLayout](http://msdn.microsoft.com/en-us/library/system.windows.uielement.updatelayout.aspx) just before rendering into the RenderTargetBitmap?
Answer: Called visual.UpdateLayout before rendering into the RenderTargetBitmap
(Thanks to Clemens for this answer - but he put it as a comment!)


Add this share not working in ajax call

Question: I was using add this share plugin.I am creating dynamic data url from ajax call.
My code was:
addthis.init();
$('.addthis_sharing_toolbox').attr('data-url',dta);

My problem current page url only sharing. I need to send my custom url. Any answer will be appreciated.
Comment: Is the value of data-url non-empty?
Comment: is it meant to be `dta` and not `data`?
Comment: Whats in `dta`? And why do not use `$('.addthis_sharing_toolbox').data('url');`?
Answer: First, make sure the variable dta has the URL you'd like to use. Then, follow the instructions on this page to update the URL and title that are shared: http://support.addthis.com/customer/portal/articles/1692927-using-dashboard-configuration-tools-dynamically
Specifically, call the addthis.layers.refresh() function.

Add this share not working in ajax call


If two matrices are similar are their submatrices again similar?

Question: I am struggling a bit with the following: if we have two similar matrices and we delete one column and one row in both of them are they again similar?
Thanks!
Answer: Try to think about $\begin{pmatrix} a & 0 \\ 0 & b \end{pmatrix}$ and  $\begin{pmatrix} b & 0 \\ 0 & a \end{pmatrix}$.


Run time validation in UItextField

Question: I want to have runtime validation on my UITextField, i.e. when user starts entering data, it should validate and pop up error message if not correct. How do I implement this feature ?
textfieldDidChange or textFieldShouldEndEditing  can be of any help ?
Any tutorial ?
Comment: Do you want to know what is the method to get the user input dynamically or do you want to know how get a connection failed message ?
Comment: I want to know which property can notify me wth value of text input at every key press, so I can validate it.
Comment: Per the UITextFieldDelegate protocol reference, the `textField:shouldChangeCharactersInRange:replacementString:` method is called "whenever the user types a new character in the text field or deletes an existing character."
Answer: You can implement the textField:shouldChangeCharactersInRange:replacementString: method on your text field's delegate, rejecting any characters that are invalid for your textfield. See the UITextFieldDelegate protocol reference for more information.
For example, if you only want to allow entry of decimal numbers, you could use:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}

This won't actually pop up an error message if the input is incorrect; instead, it will prevent entry of characters that are incorrect.
If you do want to allow the user to type invalid characters, and them give them an error, you could implement this in the textFieldShouldEndEditing: method of your delegate.
Comment: I am doing some thing like this. In one requirement, I will allow only numbers between -100 to 100 with 2 numbers after decimal. So I want to put a validation on textfield where I can validate input if user enters 123 rather than checking at "Submit".
Comment: I was thinking of utilizing UITextViewTextDidChangeNotification, but couldn't find muh info.
Comment: `UITextViewTextDidChangeNotification` is for UITextViews, not UITextFields. `UITextFieldTextDidChangeNotification` is the equivalent notification for UITextFields.
Answer: This is a better solution since it allows backspaces.
Taken from :Hugo Larcher's blog
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSCharacterSet *nonNumberSet;
if (textField == self.priceField) //allow decimals
    nonNumberSet=[[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
else
    nonNumberSet=[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];

// allow backspace
if (range.length > 0 && [string length] == 0) {
    return YES;
}
// do not allow . at the beggining
if (range.location == 0 && [string isEqualToString:@"."]) {
    return NO;
}
// set the text field value manually
NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string];
newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""];
textField.text = newValue;
    // return NO because we're manually setting the value
    return NO;
}

Run time validation in UItextField


How to display pagination on twig template

Question: This is how the pagination on the controller works
<code> /**
     *@Route("/rating/{page}",name="testing")
     */
    public function pagesAction($page,Request $request)
    {
        // retrieve GET variables
        $pageNumber = $request->query->get('pageNumber');
        $pageSize = $request->query->get('pageSize');

                $em = $this->getDoctrine()->getManager();
                $qb = $em->createQueryBuilder();

                $results = $qb->add('select', 'p')
                    ->add('from', 'GabrielUploadBundle:Post p')
                    ->add('where', 'p.upvotes > 100')
                    ->add('orderBy', 'p.createdAt ASC')
                    ->setMaxResults($pageSize)
                    ->setFirstResult($pageSize * ($pageNumber - 1))
                    ->getQuery();

                return $this->render('GabrielLayoutBundle:Worldpage:content_loop.html.twig',array('posts'=>$results->getResult()));
    }
</code>
now I only have to pass the pageNumber and pageSize for the URL (it works so far)

/rating/front?pageNumber=1&pageSize=3

All I need to know is how to display the results like this

I've been struggling with this step since I don't know how to calculate the number of results and how to get the "next " and previous buttons to work
Answer: Please take a look at KnpLabs/KnpPaginatorBundle.
It's one of the TOP 10% most used bundles out there.
The bundle provides overrideable default templates for rendering the pagination buttons and is very easy to integrate into your project.
If you don't want to use the bundle ... it's source code is definitely a good place to look for inspiration.

Your current implementation lacks a second upfront query to get the total number of posts.
Without knowing the total number of posts ... you won't be able to determine the number of buttons to show.


How do open subsets of X/G look like?

Question: Let $G$ act continuously on $X$, where $X$ is a topological space.
So I wonder about how open subsets look like in $X/G$.
The action $a$ is defined as $a(g,x)=g.x$.
Comment: Could you be more specific? Subsets of $X / G$ are, by definition, collections of orbits of the $G$-action on $X$, but presumably you want something more?
Comment: it depends on $X$ and $G$. If you have, for example, $X=\Bbb{R}^2$ and $G:=SO(2)$ the group of orthogonal $2\times 2$ matrices $\begin{pmatrix} \cos(t) & \sin(t) \\-\sin(t) & \cos(t) \end{pmatrix}$, then $\Bbb{R}^2/SO(2)$ is the circle with radius $||x||$ for $x \in \Bbb{R}^2$ (and is homeomorphic to $[0,\infty)$)
Answer: The quotient space topology in the space of orbits $X/G$ is induced by the topology in $X$ via the projection $\pi \colon X \to X/G$ where $\pi(x) = Gx$. More specifically a subset $U \subset X/G$ is open if and only if $\pi^{-1} U$ is open.
Another way of saying this is that a set $\mathcal{O}$ of orbits is open if and only if $\bigcup \mathcal{O}$ is open in $X$.
Answer: The open sets of $X/G$ are precisely images of $G$-invariant open subsets of $X$, or if you want, images of saturated open subsets of $X$. This works for any quotient topology where the map $f\colon X \to Y$ is surjective. Note however that in the case of spaces of orbits $X/G$ the map $X\to X/G$ is moreover open, that is, the image of an open subset of $X$ is open, equivalently, the saturation of an open subset $U$ of $X$, being $\cup_{g\in G} g\cdot U$, is also open.
Equivalently, you can think in terms of closed subsets: the closed ones of $X/G$ are images of saturated($G$-invariant) closed subsets of $G$. In this case, the map $X\to X/G$ may not be closed, but it surely is if say $G$ is finite.
Comment: How could you come up with that the map is moreover open?
Comment: For open $U$ in $X$ we have $f^{-1}(f(U)) = \cup_{g \in G} g\cdot U$  open, so $f(U)$ is.

How do open subsets of X/G look like?


How can I get an intuition about Copula?

Question: I am really struggling with getting an intuition about copulas. I have red many articles and I am stuck at what is the concept/idea behind it.  For example if I have two random variables X and Y and I want to use copula to come up with their joint CDF. Suppose that both X and Y are normally distributed and I want to know what their joint CDF is. How does copula help me do that? Where does inverse transform theory come in?  Also what if they have different distributions? (let's say one is normally distributed and the other one is student's t distributed).
Answer: Copula allows you to work with individual marginal CDF for each random variable (RV), instead of dealing with the joint distribution of all RVs at one time.
This is achieved by creating a joint CDF on a series of Uniform [0,1] RVs, where each Uniform RV is essentially the CDF of the underlying original RV. Note a function (including CDF) of an RV is still an RV. By doing this, an otherwise complex joint CDF of whatever distributions is transferred to a much simpler presentation of uniform RV and original marginal RV.
I feel the key to understand this is the probability integral transform, which shows why a CDF follows Uniform [0,1]. See https://en.wikipedia.org/wiki/Probability_integral_transform. I found this a little hard to appreciate, so I drew a chart below. I am not 100% sure so any comments are welcome.


Estou tentando conectar o mysql no php?

Question: Boa tarde
estou tentando conetctar o mysql no php, pois esta gerando o seguinte erro " Call to undefined function mysql_conect()", alguem por favor poderia me ajudar
Comment: Sobre pedir pro OP dar accept, [já foi discutido no meta](http://meta.pt.stackoverflow.com/questions/1425/). Agora, pedir accept por um "praticamente comentário" acho mais forçado ainda...
Comment: mysql_connect() parece que faltou 1 n.
Comment: @RogersCorrêa, o destino deste tipo de perguntas é a remoção/delete/evaporação, levando *upvotes* e *accepts* com ela. É melhor focar em perguntas de qualidade. Mendigar *accepts* não é elegante, não... confira o meta post linkado pelo Bacco.
Comment: cara valeu nao tinha visto muito obrigado deu certo
Comment: Só vou colocar como resposta depois você coloca como certa. Clicando no V transparente, aí ele fica verde! Valeu!
Comment: Esta pergunta parece ser descontextualizada porque é sobre um erro de digitação no código-fonte, e dificilmente será útil para futuros visitantes.
Comment: Mas ele precisava de ajuda :P
Answer: Faltou um n, em vez de conect seria connect mysql_connect(blabla);, além diso devo avisar que em futuras versões do PHP (3anos?) seu código deixará de funcionar, e se você estiver trabalhando para um cliente, isso vai ser ruim, visto que mysql_connect foi descontinuado (será removido no futuro), além disso ele é mais mais inseguro.
Sugiro que comece a usar mysqli ou PDO, links de tutoriais básicos:

http://blog.thiagobelem.net/guia-pratico-de-mysqli-no-php/ (mysqli)
http://www.rafaelwendel.com/2011/12/tutorial-pdo-php-data-object/ (PDO)

Espero ter ajudado.

Estou tentando conectar o mysql no php?


For random variables, show that $\limsup\limits_nX_n<\infty\Longrightarrow \sup_n X_n<\infty$

Question:
Why is the following true ?
$$\limsup\limits_nX_n<\infty\Longrightarrow \sup_n X_n<\infty$$
where, $X_n's$ are random variables.

If we consider only finitely many $X_n$, say $n\in\{1,...,m\}$ then every $X_n$ must have a finite output, since they're random variables, so if we also have $\limsup\limits_nX_n<\infty$, then $X_n$ is finite for all $n$. Is that true ?
Thanks.
EDIT: here is link, where I encountered this problem ($4$th line of the solution).
http://f.666kb.com/i/cr9yzgvnmlryuswod.gif
Comment: This is only true if the index is bounded below - if $n\in\mathbb Z$, for example, it is not true. But if it is a sequence $X_0,X_1,\dots$ then it is true.
Comment: Is $X_i$ allowed to be infinite? If so, that's a bit confusing. Unbounded would be allowed. But $\limsup x_i$ can be finite when $x_1=+\infty$, so your statement is not correct. And even if $x_i$ is finite for each $i$, that doesn't mean $\sup x_i$ is finite for each $x_i$.
Comment: @Thomas Andrews but random variables are real-valued or not ?
Comment: Well, you say it is a random variable, which usually means real-valued or complex-valued, and not infinity, but you also say: "...then $X_n$ is finite for all $n$," which implies you think $X_n$ can take $+\infty$ as a value. Basically, your question is confused.
Answer: If $Y=\limsup X_n$, then there are only finitely many $i$ such that $X_i<Y+1$.
Specifically, let $Y=\limsup X_n$. Let $N$ be the random variable which is the largest $N$ such that $X_i\geq Y+1$, or $N=0$. Then $\sup X_n <\max(X_1,X_2,\dots,X_N,y+1)$.
(As mentioned above, this assumes that the indexes $i$ of $X_i$ are bounded below and integers. If we are dealing with $\dots,X_{-2},X_{-1},X_0,X_1,\dots$, then this is not true. I assume above that the sequence starts $X_1$.)
Comment: Sorry for misunderstanding, I mean natural numbers with $n$. Actually it is a part of an exercise, and it is assumed that $\limsup\limits_nX_n<\infty$ $\text{a.s.}\Longrightarrow \sup_n X_n<\infty$ $\text{a.s.}$, but does it change anything ?
Comment: That is certainly if and only true if, for each $n$, $X_n<\infty$ a.s.
Comment: I edited the question.
Answer: I don't think this is true in general. $\limsup_n X_n<\infty$ means that $\sup_{k\geq n} X_k$ will converge (and decrease down) to  finite number when $n$ large. So this says nothing about $X_n$ for small $n$, some of which may misbehave.
Comment: Unless $X_i$ can be $\infty$, some misbehaving can't make $\sup X_n=\infty$.
Comment: @ Thomas Andrews: the problem in the shaded box doesn't say otherwise so there is a possibility of that.
Comment: "Random variable" almost always assumes a real-valued, occasionally complex values. Don't play games. The $X_i$ can be unbounded, and the above statement is still true.
Comment: @ Thomas Andrews: I'm not playing games. I genuinely thought the question permitted that possiblity. The OP will see our comments here and decide for himself/ herself. Cheers.


Miller-Rabin Primality Testing failure and a subgroup

Question: Let $n$ be composite. I'm trying to figure out if the set $H$ of $a$ such that
1) $a$ is relatively prime to $n$ and
2) the Miller-Rabin test fails to show compositeness of $n$ with $a$
is a subgroup of the multiplicative group mod $n$.
My instinct is no: I am trying to show that the set is not closed. But then again we won't get any factors of $n$ by multiplication because of condition 1).
Update: I've run some experiments and it seems that the number of strong liars relatively prime to n divides the order of the multiplicative group. I wanted to get a contradiction with Lagrange's theorem.
Comment: closure under multiplication will suffice (since this is a finite group); the only possible problem is if $n-1 = 2^rd$, $d$ odd, $a^d\not\equiv 1$, $b^d\not\equiv 1$, and for the *same* $s$, $0\lt s\lt r$, $a^{2^sd}\equiv b^{2^sd}\equiv -1$.
Comment: Have you tried just working out examples with a few small n?
Comment: I checked out 9 as it seemed like the smallest non-trivial example and it did wind up being a subgroup. 1, 2, 4, 5, 7 and 8 are all 'strong liars'. But this is a bad example.
Answer: The strong liars form a subgroup of $(\mathbb{Z}/n\mathbb{Z})^{\times}$ iff $n$ isn't of the form $n=\prod_{j=1}^{k}{p_{j}}^{\alpha_{j}}$, where $k\geq2$, $p_{1},\ldots,p_{j}$ are pairwise different primes such that $p_{j}\equiv 1\pmod4$ and $\alpha_{j}\in\mathbb{N}$, $j\in\{1,\ldots,k\}$. Here's the proof:
For $n=1$ everything's trivial so let's assume $n>1$ and set $n-1=2^{x}y$, where $x,y\in\mathbb{Z}$ and $2\nmid y$. Also let $L(n)$ denote the set of strong liars $\bmod n$, ie
$$L(n)=\big\{a\in(\mathbb{Z}/n\mathbb{Z})^{\times}\colon(\exists t\in\mathbb{Z},0\leq t<x:a^{2^{t}y}=-1)\vee a^y=1\big\}.$$
If $2\mid n$, then
$$L(n)=\big\{a\in(\mathbb{Z}/n\mathbb{Z})^{\times}\colon a^{n-1}=1\big\},$$
which is obviously a subgroup of $(\mathbb{Z}/n\mathbb{Z})^{\times}$.
If $q\mid n$ for some prime $q$ such that $q\equiv3\pmod4$, then $-1$ is quadratic nonresidue $\bmod{q}$, hence also $\bmod{n}$, so it can't be $a^{2^{t}y}=-1$ for $t>0$ and
$$L(n)=\big\{a\in(\mathbb{Z}/n\mathbb{Z})^{\times}\colon a^y=\pm1\big\},$$
which is again a subgroup of $(\mathbb{Z}/n\mathbb{Z})^{\times}$.
If $n=p^\alpha$, where $p$ is a prime such that $p\equiv1\bmod4$ and $\alpha\in\mathbb{N}$ then we have $a^{n-1}-1=(a^{y}-1)\prod_{j=0}^{x-1}(a^{2^{j}y}+1)$, and since at most one of the factors on the RHS of this equation can be $0\bmod p$, we have
$$L(n)=\big\{a\in(\mathbb{Z}/n\mathbb{Z})^{\times}\colon a^{n-1}=1\big\},$$
which is once again a subgroup of $(\mathbb{Z}/n\mathbb{Z})^{\times}$.
Now let $n=\prod_{j=1}^{k}{p_{j}}^{\alpha_{j}}$, where $k\geq2$, $p_{1},\ldots,p_{j}$ are pairwise different primes such that $p_{j}\equiv 1\pmod4$ and $\alpha_{j}\in\mathbb{N}$, $j\in\{1,\ldots,k\}$. Let $G_{j}=(\mathbb{Z}/{p_{j}}^{\alpha_{j}}\mathbb{Z})^{\times}$, $H_{j}={G_{j}}^y$ be the subgroup of $y$-th powers in $G_{j}$ and $K_{j}=\{a\in G_{j}\colon a^{y}=1\}$ be the $y$-torsion subgroup of $G_{j}$. Then $|G_{j}|=\varphi({p_{j}}^{\alpha_{j}})=(p_{j}-1){p_{j}}^{\alpha_{j}-1}$, $|K_{j}|=\gcd(\varphi({p_{j}}^{\alpha_{j}}),y)$ (because $G_{j}$ is cyclic) and $H_{j}\cong G_{j}/K_{j}$, from which it follows that $4\mid|H_{j}|$. $H_{j}$ is cyclic (it's a subgroup of $G_{j})$, so it contains an unique cyclic subgroup of order $4$. For every $j\in\{1,\ldots,k\}$ let's fix $r_{j}\in G_{j}$ such that ${r_{j}}^{y}$ has order $4$ (such elements exist by the above reasoning). By CRT we have $(\mathbb{Z}/n\mathbb{Z})^{\times}\cong\prod_{j=1}^{k}G_{j}$, let $f_{j}\colon(\mathbb{Z}/n\mathbb{Z})^{\times}\to G_{j}$ be the natural projection. Then there exist $a,b\in(\mathbb{Z}/n\mathbb{Z})^{\times}$ such that $f_{1}(a)=r_1$, $f_{1}(b)=-r_1$ and $f_{j}(a)=f_{j}(b)=r_j$ for $j\geq2$. Then for every $j$ it's $f_{j}(a^{2y})=f_{j}(b^{2y})=-1$, hence $a^{2y}=b^{2y}=-1$ and $a,b\in L(n)$ (because $x\geq2$). But $(ab)^{2y}=1$ so it can't be $(ab)^{2^{t}y}=-1$ for $t\geq1$, and also $f_{1}((ab)^{y})=-{r_{1}}^{2y}=1$, $f_{2}((ab)^{y})={r_{2}}^{2y}=-1$, so it's $(ab)^{y}\neq\pm1$, hence $ab\notin L(n)$, which means that $L(n)$ isn't a subgroup of $(\mathbb{Z}/n\mathbb{Z})^{\times}$ in this case.
Concerning the previous post: If $q\mid n$ for some prime $q$ such that $q\equiv 2\text{ or }3\pmod4$ then it's easy to see that there are no primitive Pythagorean triangles with hypotenuse $n$, and if $n=\prod_{j=1}^{k}{p_{j}}^{\alpha_{j}}$, where $p_{1},\ldots,p_{j}$ are pairwise different primes such that $p_{j}\equiv 1\pmod4$ and $\alpha_{j}\in\mathbb{N}$, then it's not difficult to show that there are $2^{k-1}$ different (up to isomorphism) primitive Pythagorean triangles with hypotenuse $n$, so the "bad" $n$'s are really exactly the ones for which there's more than one such triangle. :)
Comment: For what it's worth, this result is stated as Exercise 3.17 in Crandall and Pomerance's book on primes.
Comment: @KCd Thanks, that gives (together with the previous Exercise 3.16) a little bit different perspective. Btw that book looks really interesting :).
Answer: For $n=221$ (this is the example in Wikipedia), the liars are 21, 47, 174 and 200.  Now, 21*47 mod 221 gives 103, which is not in that list.
The sequence of those composite $n$ for which the liars don't form a group seems to be 65, 85, 145, 185, 205, 221, 265, 305, 325, 365, 377, ... which seems to coincide with
"A024409 Hypotenuses of more than one primitive Pythagorean triangle" on OEIS (testet up to 629).
Edit: Of course, I included 1 and -1 before checking for being a group.
Comment: @Arturo: In addition, we need $a b\ne 1$.  Id tried this explicitely:  For $n=221$, we have $d=55,r=2$ and $s=1$ for all four liars, and $21\cdot47\ne1$.  For $n=49,d=3,r=4$, the liars are (18,19,30,31) where $a^d=1$ for 18,30 and $s=1$ for 19,31.  But $19\cdot31=1$, so the group property is not violated.
Comment: Pinging does not work unless I had participated in this particular answer; but thanks for the note and heads up.
Comment: Totally wrong. Set of liars is $\lbrace 1, 21, 47, 103, 118, 174, 200, 220 \rbrace$. So $21 * 47 \equiv 103 \pmod{221}$ is indeed in our set.


Mascara para campo de linha digital de boletos

Question: Alguém saberia informar se existe alguma mascara para a linha digitavel de boletos?
Estou com uma tela onde é exibida a listagem de boletos de um cliente e exibo também a linha digitavel de forma inteira, sem pontos ou separações, visto que este registro vem de um webservice. E no caso de boletos vencidos eu exibo um link para o cliente acessar diretamente o site do banco e digitando a linha digitavel do boleto ele consegue gerar um boleto com uma nova data de vencimento.
No entanto no site do banco a linha digitavel é separada em varios campos, não sendo possivel digitar o numero por inteiro.
Sendo assim, alguem conhece uma biblioteca ou um script que já faz essa conversão?
Comment: Se você tiver a regra (acredito que isso seja padronizado) deve se fácil pq os campos são baseados por comprimento.
Answer: Com o plugin inputmask pode criar a máscara passando apenas o padrão, o 9 significa que apenas números são aceitos.
Html:
<input type="text" id="boleto"/>

javascript:
$("#boleto").inputmask({mask: '99999.99999 99999.999999 99999.999999 9 99999999999999'});

Answer:

var codigo_barras = '00190500954014481606906809350314337370000000100'

function mascaraBoleto(codigoBarras) {
/*
  Posição 01-03 = Identificação do banco (exemplo: 001 = Banco do Brasil)
  Posição 04-04 = Código de moeda (exemplo: 9 = Real)
  Posição 05-09 = 5 primeiras posições do campo livre (posições 20 a 24 do código de barras)
  Posição 10-10 = Dígito verificador do primeiro campo
  Posição 11-20 = 6ª a 15ª posições do campo livre (posições 25 a 34 do código de barras)
  Posição 21-21 = Dígito verificador do segundo campo
  Posição 22-31 = 16ª a 25ª posições do campo livre (posições 35 a 44 do código de barras)
  Posição 32-32 = Dígito verificador do terceiro campo
  Posição 33-33 = Dígito verificador geral (posição 5 do código de barras)
  Posição 34-37 = Fator de vencimento (posições 6 a 9 do código de barras)
  Posição 38-47 = Valor nominal do título (posições 10 a 19 do código de barras)
*/
    if(codigoBarras.length !== 47){
    return codigoBarras;
  }

    let mascaraAjustada = codigoBarras.substring(0,5) + '.' + codigoBarras.substring(5,10)
  + ' ' + codigoBarras.substring(10,15) + '.' + codigoBarras.substring(15,21) + ' '
  + codigoBarras.substring(21,26) + '.' + codigoBarras.substring(26,32) + ' '
  + codigoBarras.substring(32,33) + ' '
  + codigoBarras.substring(33,47)

    return mascaraAjustada;

}

console.log(mascaraBoleto(codigo_barras));
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How to send a email message to specific user role when the site goes to the maintenance mode in drupal 7?

Question: I would like to use emails to communicate with users. So i really want to send a email message for all users(or just a number of users with specific role) when the site goes to the maintenance mode and send another one when the site comes online.
I checked triggers, rules, actions but couldn't find anything to help.
How can I solve this?
Answer: Checkout this module Maintenance mode API .

Maintenance mode API notifies other modules when the site is switched into or from maintenance mode.
This means that other modules can respond to this, for example:
Alerting a list of users when the site goes into or out of maintenance mode

This module provides a hook, hook_change_maintenance_mode which any custom modules can interact
EDIT:
You can create a custom rule set with actions as send emails to your desired users. (An example guide how to create it).
Then invoke the rule set using rules_invoke_event() function inside the hook hook_change_maintenance_mode
Comment: If we do this way how can we deal with email translation and email templates. It's good if we can create somthing like rules or triggers for that because we can have many benefits from email translation & templates.
Comment: you can call the custom ruleset inside the hook hook_change_maintenance_mode, see edits
Comment: Yes. It worked.  **1**. I created two rules (offline and online rule) in my custom module.  **2**. Use the hook_change_maintenance_mode to detect the status and use rules_invoke_event() to call the rule.  **3**. From the rules UI. I just create action like "Send mail to all users of a role" and from that i can use email template or translation.  The **Maintenance mode API module** is the key for that. Thanks


R - Scrape multiple url and wirte each data url in different excel data sheets

Question: I'm trying to scrape different URL and write data in the same Excel's file but in a single page for each URL.
My code is this:
#install.packages("rvest")

library(XLConnect)
library(rvest)
{
 for(i in c("2086","2167","2204")) {
   url<-paste0("https://www.silversanz.com/producto/",i,)

}
 dades<-read_html(url)

 nom<-dades %>% html_nodes("h1.title") %>% html_text() %>% trimws()
 preu<-dades %>% html_nodes("p.price--current") %>% html_text() %>% trimws()

 info<-as.data.frame(cbind(nom,preu))

 writeWorksheetToFile(file="C:/xxx.xxx.xlsx",
                   data=info,
                   sheet= "test",
                   clearSheets=TRUE
 )
}

I have two problems:

This code doesn't work ->
 for(i in c("2086","2167","2204")) {
 url<-paste0("https://www.silversanz.com/producto/",i,)

I don't know how to write one sheet for each url

Thanks in advance :-)
Answer: You have used the brackets in the wrong way. The for-loop that you have written iterates over the numbers and saves the last one in url. Your for-loop instead should contain all of your code:
library(XLConnect)
library(rvest)

for(i in c("2086","2167","2204")) {

   url<-paste0("https://www.silversanz.com/producto/",i)

   dades<-read_html(url)

   nom<-dades %>% html_nodes("h1.title") %>% html_text() %>% trimws()
   preu<-dades %>% html_nodes("p.price--current") %>% html_text() %>% trimws()

   info<-as.data.frame(cbind(nom,preu))

   writeWorksheetToFile(file="C:/xxx.xxx.xlsx",
                     data=info,
                     sheet= i,
                     clearSheets=TRUE)
}

As for the sheet, now that everything is in the loop, just use i as the sheet name in order to have one sheet per url.
Comment: Yeah, succesfull!! Thanks a lot, LyzandeR :-)
Comment: Happy to help :)


Display alias instead of node

Question: I am trying to create a link in page.html.twig that points to an alias. The code {{ url('node/1') }} shows an unexpected error, whereas {{ 'node/1' }} works fine but goes to url website/node/1.
In D7, one can use <?php echo url('node/1'); ?> and be directed to the page with proper alias.
What code can be used in D8 to display correct alias url?
Comment: Great question, hope you don't mind I re-phrased it a bit.
Answer: You can use getAliasByPath function to get the url alias for a path.
Put the below code in THEME_NAME.theme file.
function THEME_NAME_preprocess_page(&$variables) {
  $variables['url_alias'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/1');
}

Finally print the url_alias in your page.html.twig file.
{{ url_alias }}

Comment: I use {{ Drupal::service('path.alias_manager')->getAliasByPath('node/1') }} in page.tpl.twig show unexpected error
Comment: I have edited my answer, also add / before the path (/node/1).
Answer: The twig functions url and path operate on routes and not paths, so you must specify the route name and the necessary parameters.
{{ path('entity.node.canonical', {'node': 1}) }}

Display alias instead of node


Standard Deviations of Multiple Samples

Question: I work in the microelectronics industry, and I commonly work with tools that remove material from the surface of a wafer. Furthermore, we typically measure the amount of material removed from a single wafer at multiple sites on the wafer (usually 10 - 20 sites). From this data, we calculate various statistics. For example, we calculate a within wafer (WIW) mean and standard deviation. This metric is very straightforward, and we just calculate the mean and standard deviation of all the sites measured on a single wafer. However, people in my industry also talk about wafer-to-wafer (WTW) standard deviations, which I don't fully understand. Is it common in statistics to look at standard deviations of two groups/samples? If so, what would be the methods used to calculate this? Does it make sense to calculate the standard deviations of all of the wafer means, or is there some better method?
I hope this question is not too vague. If it is, please let me know and I will try to provide more information.
Answer: You could certainly compute the SD of a set of group means, and this is done with some frequency. More complicated notions related to this also appear, such as, in a mixed model, estimating the SD of a set of per-group random intercepts. But you could also compute the common SD of all the units in several groups, disregarding the existence of the groups. It all depends on what question you're trying to answer. I don't know enough about your subject area to guess what that is.
Comment: I believe that our goal is to reduce the amount of variability in data for sites measured on a given wafer and across multiple wafers. Expressed in a different way, the ideal state would be to remove the exact same amount of material at each site and on each wafer.
Comment: @johncarter All right, but how were you hoping to use these metrics to accomplish that?
Comment: I guess that kind drills down to the essence of my question. I am no stats guru. I ask the question to get a sense of why these metrics are important, and I was curious about the best way to calculate these metrics.
Comment: @johncarter You would have to ask somebody who does these analyses in order to find out why they do it. It may just be tradition. In practice, many data-analytic traditions are just that, tradition, with no special justification beyond inertia.
Comment: @johncarter Although, to be clear, you're asking about what metric to use, not how to calculate the metrics. How to calculate, e.g., the SD of the group means is clear enough.

Standard Deviations of Multiple Samples


Boundary of $\Bbb{R}$

Question: Is the empty set boundary of $\Bbb{R}$ ? If it is, is it the only boundary of $\Bbb{R}$ ?
I think the empty set is the boundary of $\Bbb{R}$ since any neighborhood set in $\Bbb{R}$ includes the empty set. However, I'm not sure. Besides, I have no idea about is there any other boundary or not.
P.S : It is about my Introduction to Real Analysis course. I haven't taken Topology course yet.
Comment: One definition of the boundary is the intersection of the closures of the set and its complement. Since $\emptyset$ is closed, we see that the boundary of $\mathbb{R}$ is $\emptyset$.
Answer: By definition, the boundary of a set $X$ is the complement of its interior in its closure, i.e. $\overline{X} \setminus X_0$. But $\mathbb{R}$ is closed and open, so its interior and closure are both just $\mathbb{R}$. Therefore the boundary is indeed the empty set as you said.
Answer: The boundary of $\mathbb R$ within $\mathbb R$ is empty.  If $\mathbb R$ is embedded in some larger space, such as $\mathbb C$ or $\mathbb R\cup\{\pm\infty\}$, then that changes.
A boundary point is of a set $A$ is a point whose every open neighborhood intersects both $A$ and the complement of $A$.  Complements are relative: one finds the complement of a set $A$ within a set that includes $A$.  If that set is only $A$ and nothing more, then the complement is empty, and no set intersects the empty set. The complement of $\mathbb R$ within $\mathbb R$ is empty; the complement of $\mathbb R$ within $\mathbb C$ is the union of the upper and lower open half-planes.  The boundary of $\mathbb R$ within $\mathbb C$ is $\mathbb R$; the boundary of $\mathbb R$ within $\mathbb R\cup\{\pm\infty\}$ is $\{\pm\infty\}$.
Answer: The boundary any set $A \subseteq \Bbb R$ can be thought of as the set of points for which every neighborhood around them intersects both $A$ and $\Bbb R - A$.
Specifically, we should have for every $\epsilon >0$ that $B(x,\epsilon) \cap A \neq \emptyset$ and $B(x, \epsilon) \cap (\Bbb R - A) \neq \emptyset$.  If $x$ satisfies both of these, $x$ is said to be in the boundary of $A$.
So, let's look at the set of $x$ in $\Bbb R$ that satisfy for every $\epsilon > 0$, $B(x, \epsilon) \cap \Bbb R \neq \emptyset$ and $B(x, \epsilon) \cap (\Bbb R - \Bbb R) \neq \emptyset$.
Notice that for the second piece, we are asking that $B(x, \epsilon) \cap \emptyset \neq \emptyset$.  No $x \in \Bbb R$ can satisfy this, so that's why the boundary of $\Bbb R$ is $\emptyset$, the empty set.

Boundary of $\Bbb{R}$


Irregularly spaced time-series in finance/economics research

Question: In financial econometrics research, it is very common to investigate relationships between financial time series that take the form of daily data. The variable will often be made $I(0)$ by taking the log difference, for example; $\ln(P_t)-\ln(P_{t-1})$.
However, daily data means that there's $5$ data points each week, and Saturday and Sunday are missing. This seems to get no mention in the applied literature that I'm aware of. Here's some closely related questions that I have that come from this observation:

Does this qualify as irregularly spaced data, even though financial markets are closed over the weekend?
If so, what are the consequences for the validity of extant empirical results garnered thus far in the gigantic number of papers that ignore this issue?
Comment: Regarding your first question, this problem is sometimes called *weekend effect*. In my opinion, the answer is context-dependent. For instance, this question makes a lot of sense in the case of stock returns. See for instance [here](https://umdrive.memphis.edu/cjiang/www/teaching/fir8-7710/paper/Stock_Returns_and_weekend_effect.pdf), [here](http://www.jstor.org/stable/2327716), [here](http://www.jstor.org/stable/2328067) and [here](http://www.jstor.org/stable/2327945).  But I am not sure if this effect applies to other contexts.
Comment: @Procrastinator Submit answer it's very good!!
Comment: There is a quantitative finance SE that may be more suited to get meaningfull answers. There are actualy a lot more problems than weekends: nights, bank holidays... etc. which get worse with multiple price sources.
Answer: Full disclosure! I don't know about finance/economy, so sorry in advance for my ignorance. But I find this question wider than finance. Analyzing irregularly sampled data arises in many other fields, such as biology and medicine. One of the shortcomings of classical approaches like Autoregressive Regression (AR) is their weakness in dealing with irregularly sampled data. However this problem can be tackled by Gaussian processes (GPs). It's used for example here or here.
Answer: Traditionally, we don't worry about non trading days and count this as regularly spaced data.  There are however two possible effects that you'd have to worry about.
The first is the effect of time on momentum and interaction with leading indicators.   If you have a lagged variable that is a good leader - let's say it's mean temperature - then some of your data points will be lagged to the next day (Friday -> Thurs) while others are lagged three days (Monday -> Friday).  There's likely to be spurious results because of that.
The second issue is activity that happens when markets are closed.  After hours trading, options pricing, etc.   If those are a factor, you may be better off calculating a regularly spaced time series and interpolating or accounting for non-trading days some other way.
Comment: Just because markets are closed doesn't mean it's regularly spaced. If we think of it as an underlying process that we sample discretely (when markets are opened) but still evolves when markets are closed then it is irregular. I think this continual evolution metaphor is more useful since it is consistent with close to open jumps (all information from closed times being revealed in 1 moment).


moving to a new dedicated server and need advice on the new setup

Question: I currently have a dedicated server that we have outgrown and we are moving to another server.
Our current setup was a 8gb W2008R2 server running a W2008R2 IIS virtual machine using VMWare.
We are moving to a 2 cpu 24 gb server with W2012 R2 on Hyper-V.
On our virtual machine we are running iis 7.5 and sql server. Sql Server seems to want to eat up all the memory so I had to cap it at 2gb, which doesn't seem sufficient.
My question is, when I move the virtual machine to the new server, should I create 2 virtual machines, one for sql server and one for IIS? Or should I leave them both on the same virtual machine? Or even, put the Sql Server on the dedicated server and run the IIS in the vm?
I'd like some input on how this should be done, I've not got the experience needed to make the right call.
Thanks!
Comment: Typically, you'd want to split SQL server to its own server and let it eat all the RAM it wants. Whether it's worth the additional overhead of a second OS and VM depends on your environment, though.
Comment: possible duplicate of [Can you help me with my capacity planning?](http://serverfault.com/questions/384686/can-you-help-me-with-my-capacity-planning)
Comment: Leave a reason for your downvote pls... it doesn't help to resolve the issue or tell me why it's downvoted.
Comment: ok ty I'll go that route ty!
Answer: It depends on your usage.
What is your CPU usage with your current system?
How much of it is IIS?  How much of it is SQL?
What is your memory usage with your current system?
How much of it is IIS?  How much of it is SQL?
Generally speaking, for small operations, combining IIS and SQL servers into one is fine.  However, if you start breaking the 75% mark of your I/O maximums, it'd be about time to split up your servers.  (75% is an arbitrary number, but it's ideal, because it means you're halfway from 50%, which means your system should be rocking, to 100% efficiency, which means your system cannot perform any better than it already is; planning at this stage will be less stressful than planning at 100% efficiency, because by 100%, your systems are already prone to problems and it's easier to tackle a problem proactively than reactively).
If the combined percentages of usages between IIS and SQL are equal to or greater than 75% or the arbitrary Desired Max Usage Percentage, then you should split them up.
Here's a guide (note, I just put it together off the top of my head, so I don't know how accurate the calculations are yet; and this doesn't account for hard drive bottlenecks or network latency.  This also does not take into account poorly written applications that may take up too much resources unnecessarily, which won't change by beefing up a system):

Determine your current latency
Determine how much latency you're willing to accept and change that into an empirical quantitative numeric value.  Example; If you are willing to take a little latency; how much? 100ms? 250ms? 500ms? 1s?
Determine if the latency you're willing to accept will be an average over time (ideally, at a minimum, a full 7 days) or an absolute maximum value (ideally, on the day your experience the most load on your server).
a) If the accepted latency is an average, calculate the average CPU and Memory usage values overtime
b) If the accepted latency is an absolute maximum value, calculate the max CPU and max Memory usage values at the highest load of the day
Determine Current Processing Capability/Memory Capacity
Determine your growth rate percentage per year; if you have no baseline data to compare, arbitrarily assume 10% growth every year or take 1 / (Current_Latency / Desired_Latency) x 100% / Years_System_Was_In_Service, whichever is higher.
Determine the processing power/memory capacity needed to keep your systems under 75% (Desired_Max_Usage_Percentage) utilization for the next Y amount of years, before your next upgrade. Resource_Needed = (Current_Usage_Percentage x Current_Capability) + (1 + (Y_Years x Growth_Percentage)) / Desired_Max_Usage_Percentage
Determine the adjusted value needed to accommodate for desired latency.

Example (CPU) 1:
Current Latency = 1000
Desired Latency = 500
Latency Variable = 1 + (1 / (1000 / 500)) = 1.5
Current_CPU_Usage = 100%
Current_Capability = 2CPU x 3.0GHz = 6.0GHz
Y_Years (to next upgrade) = 3
Growth_Percentage = 10%
Desired_Max_Usage_Percentage = 75%

Minimum Resource = (1 x 6.0) + (1 x (3 x .1))/.75 = 7.73GHz
Adjustment For Latency = 7.73 x 1.5

Result: Upgrade to minimum 7.73GHz
Result to desired latency: 11.60GHz

Example (CPU) 2:
Current Latency = 1000
Desired Latency = 500
Current_CPU_Usage = 70%
Current_Capability = 2CPU x 3.0GHz = 6.0GHz
Y_Years (to next upgrade) = 3
Growth_Percentage = 10%
Desired_Max_Usage_Percentage = 75%

Minimum Resource = (.7 x 6.0) + (1 x (3 x .1))/.75 = 5.93GHz
Adjustment For Latency = 5.93 x 1.5 = 8.90GHz

Result: No need to upgrade
Result to desired latency: 8.90GHz

Example (Memory) 1:
Current Latency = 1000
Desired Latency = 500
Latency Variable = 1 + (1 / (1000 / 500)) = 1.5
Current_Memory_Usage = 100%
Current_Capability = 4GB
Y_Years (to next upgrade) = 3
Growth_Percentage = 10%
Desired_Max_Usage_Percentage = 75%

Minimum Resource = (1 x 4.0) + (1 x (3 x .1))/.75 = 5.73GB
Adjustment For Latency = 5.73 x 1.5 = 8.6GB

Result: Upgrade to minimum 5.73GB
Result to desired latency: 8.6GHz

Example (Memory) 2:
Current Latency = 1000
Desired Latency = 500
Latency Variable = 1 + (1 / (1000 / 500)) = 1.5
Current_Memory_Usage = 50%
Current_Capability = 4GB
Y_Years (to next upgrade) = 3
Growth_Percentage = 10%
Desired_Max_Usage_Percentage = 75%

Minimum Resource = (.5 x 4.0) + (1 x (3 x .1))/.75 =3.73GB
Adjustment For Latency = 3.73 x 1.5 = 5.23GB

Result: No need to upgrade
Result to desired latency: 5.23GB

Note: please take my examples with a grain of salt.
To plan for network capacity, hard disk storage capacity, or hard disk I/O metrics, you'd essentially do similar calculations.
TL:DR; If your CPU or Memory utilization is reaching 100%, you should probably split the IIS and SQL services into their own resources.  However, before doing so, you should consider application/resource tuning, as hardware changes can be expensive, and will not resolve inefficient applications.
Comment: Great answer! I'll jump on these calcs and see what I come  up with. Thanks!


Is $\mu_U(E) := \mu(E\cap U)$ a Radon measure when $U$ is open?

Question: Let $X$ be a LCH space with a Radon measure $\mu$. By definition, Radon measure is a Borel measure, which is finite on compact sets, outer regular on Borel sets, and inner regular on open sets.
Now, let $U \subseteq X$ be open. I want to prove/disprove that $\mu_U(E) := \mu(E\cap U)$ is also Radon. It is easy to prove that $\mu_U$ is finite on compact sets and inner regular on open sets.
At the moment, I am not sure whether this is true/false. I would appreciate if you can help me with proving/disproving this.
Answer: Unfortunately it isn't a Radon measure in general. However, there is a Radon measure which agrees with $\mu_U$ when integrating compactly supported continuous functions (by Riesz representation theorem).
It is possible to remedy this though by using a different definition of Radon. If Radon instead means finite on compact sets and inner regular on Borel sets, then $\mu_E$ is Radon for every Borel set $E$.
Comment: How about general Borel sets? Using outer regularity of $\mu$, there is an open $V$ containing $E\cap U$ s.t. $\mu(V \setminus (E\cap U))$ is small. But $V$ may not contain $E$.
Comment: You are right, I wasn't thinking about it for long enough. Let me fix my answer.


If there are 20 students in a class, in how many ways can a professor give out $4$ A's, $3$ B's ,$4$ C's, and $9$ F's?

Question:
If there are $20$ students in a class, in how many ways can a professor give out $4$ A's, $3$ B's ,$4$ C's, and $9$ F's?

What I did was use the binomial theorem:
$\frac{20!}{4!\cdot 3!\cdot4! \cdot9!} = 1,939,938,000$
Is this a correct way of approaching a problem like this?
Comment: Your answer is correct.  You correctly used the formula for the [permutations of a multiset](https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets).
Answer: Yes.
If you want to convince yourself, beyond a hunch that you have remembered the right formula, place the $20$ students into order - $20!$ ways of doing that. Then give the first four an A, the next three a B, and so on.
Because the four A students could come in any order, you have over-counted by a factor of $4!$. Because the three B students could come in any order, you have over-counted by a factor of $3!$. And so on.
Formulae are all very well, but they all look the same sometimes, so it's good to be able to work the answer out for yourself.


Creating multiple nodes of different content type at once

Question: Can someone tell me if there is a module that will allow a user to create multiple nodes of different content types within one form?  I have a base content type that can have a 1 to many relationship to another content type. I want the user to be able to create the base content type node along with 1 to n nodes for the second content type.
Answer: The module you are looking for is Node Reference Create. Here is a quote about it (from the module's project page):

... is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.
When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.


Language Bar Disappears After Terminating a Shadow Remote Desktop Connection to a User in Windows Server [2012 R2 in my case]

Question: Essentially, the question is the way it is. The bug has been out there for quite a while but it doesn't seem to be a specific way to get rid of it.
I've been able to find some stuff both in Russian and English but no luck there.
https://social.technet.microsoft.com/Forums/ru-RU/a115017f-378e-4a64-83dc-195001d7f182/-shadow-2012-r2?forum=WS8ru#26cfec67-f6e1-42c1-a9d3-68a31053b4ad
https://social.technet.microsoft.com/Forums/windowsserver/en-US/6f738827-70a1-448c-8635-a01e41afca8f/windows-2012r2-language-bar-disappears-after-shadow?forum=winserverTS#147cc3cb-cd5e-452f-afeb-4e4accfb9927
So this happens both when you connect from the server itself or from a computer with respective administrative GPOs applied (and a user is granted with admin rights), it's just as soon as you disconnect feels like the bar wasn't even there. Three things help:
1. You go to the Control Panel -> Language and swap back and forth two (or more) languages displayed there.
2. You add another one to the list.
3. A user relogins to the terminal session.
Feels like this thing presents for the Active Directory as an entity independent on the users connecting to a terminal server or just logging in to an AD account on a specific domain computer.
Maybe it is somehow connected with terminating ctfmon.exe or something connected to language input.
I've tried to screw around with registry attributes
HKEY_CURRENT_USER\Keyboard Layout\Preload
HKEY_CURRENT_USER\Keyboard Layout\Toggle

and this
Control Panel\All Control Panel Items\Language\Advanced settings
"Let me set a different input method for each app window"

No luck there
I would really appreciate some directions here.
Comment: Seems like it immediately shuts down the chosen language — if you change anything — from input method to adding a new language — it "hops" back in. Adding a new language leads to having three languages in the bar, changing input method — only two [apparently].
Answer: I have the same problem but on Server 2016. The most common solution I've found on the web is to create a new string in registry through Regedit in this section:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

with any name and this value:
ctfmon"="c:\Windows\System32\CTFMON.EXE"

and reboot the server.
But this works from time to time and I don't understand why.
If anyone have a better solution I would appreciate it.


Geometric series for values between 0 and 1

Question: I am given that geometric series is defined as the following $1-x+x^2-x^3+x^4$ for values in range $0<x<1$.
I am also told expected value can be calculated by using the following equation: $1/1+x..$
Then i am told i can keep calculating the series until  i am in the error range of the expected value.
Error = |currentSumofGeoSeries+expectedValue|
<code>Given x = 0.5 and error tolerance =  0.001

Term 1 1 0.333333
Term 2 0.5 0.166667
Term 3 0.75 0.0833333
Term 4 0.625 0.0416667
Term 5 0.6875 0.0208333
Term 6 0.65625 0.0104167
Term 7 0.671875 0.00520833
Term 8 0.664063 0.00260417
Term 9 0.667969 0.00130208
Term 10 0.666016 0.000651042
</code>
I am just confused as to how term 1 ...term 2 are calculated. how did they get 1 and 0.333 for term 1? please advice
Comment: The series is given by
$$\sum_{k=1}^\infty (-x)^k \to \frac1{1+x} \text{ iff } |x| < 1$$
Your problem is that the last value of the output is the error of the limit $\frac1{1+\frac12} = \frac23$ compared to the truncated sum.
Answer: The series is given by
$$\sum_{k=1}^\infty (-x)^k \to \frac1{1+x} \text{ iff } |x| < 1$$
Your problem is that the last value of the output is the error of the limit $\frac1{1+\frac12} = \frac23$ compared to the truncated sum.
The output is formatted like this:
$$\text{Term } k \qquad \sum_{j=0}^k (-\frac12)^j \qquad \Bigg| \sum_{j=0}^k (-\frac12)^j - \underbrace{\sum_{j=0}^\infty (-\frac12)^j}_{= \frac23} \Bigg|$$

As per request: calculation of Terms $1$ and $2$:
I denote
$$S_n := \sum_{k=0}^{n-1} (-\frac12)^k$$
The output of your program then gives $S_n$ and $\epsilon_n := |S_n - \frac23|$.
$$S_1 = \sum_{k=0}^{1-1} (-\frac12)^k = (-\frac12)^0 = 1$$
so
$$\epsilon_1 = |1-\frac23| = \frac13$$
. Now for term $2$:
$$S_2 = \sum_{k=0}^{2-1} (-\frac12)^k = (-\frac12)^0 + (-\frac12)^1 = 1 - \frac12 = \frac12$$
so that
$$\epsilon_2 = |\frac12- \frac23| = |-\frac16| = \frac16$$
Comment: i understand how the last term is but can u show perhaps a run through of how first two terms are calculated?
Comment: @user2733436 I have now done that. Is it clear how to proceed?
Comment: what is Sn and En ?
Comment: @user2733436 I have defined $S_n$ to be the truncated sum (called _partial sum_) and $\epsilon_n$ to be the error $|S_n - \frac23|$.
Comment: also can u quickly tell when do u stop calculating ?
Comment: @user2733436 The condition is that $\epsilon_N < 0.001$ (the error is smaller than the tolerance) This happens first for $N=10$


A $k$-regular Graph with girth(G) = g has at least f(k,g) vertices

Question: I absolutely have no idea on how to prove this so any help is welcome.
Let G be a $k$-regular Graph with girth(G) = g. Then G has at least $f(k,g)$ vertices $(k \geq 3, g \geq 3)$ where
$$f(k,g) := \begin{cases} \frac{k(k-1)^r-2}{k-2} \quad \text{if g=2r+1} \\ \frac{2(k-1)^r -2}{k-2} \quad \text{if g=2r}\end{cases}$$
Answer: Have you ever heard of the family tree paradox?
It goes like this: you have two parents. Each of them has two parents, so you have four grandparents. Similarly, you have eight great-grandparents, sixteen great-great-grandparents, and so on: $2^k$ ancestors from $k$ generations ago. A thousand years ago is about thirty generations, so in the year 1017 you had about $2^{30} = 1\,073\,741\,824$ living ancestors. But that's way more than the number of people alive in the world at that time. What gives?
The problem is called pedigree collapse: embarrassingly, if you go far enough back in the family tree, your relationship to your ancestors stops being unique. Maybe your mother's father's father's mother's father's mother is the same person as your father's mother's father's mother's father's mother's father. In graph-theoretic terms, your family tree contains a cycle.
If your family tree has girth $g$, there is a lower bound (in terms of $g$) on how far away that cycle can be. For example, girth $7$ implies that two people with the same grandparent shouldn't have children together: otherwise, one of those children would have two paths up to that shared grandparent, which is a cycle of length $6$. So if your family tree has girth $g \ge 7$, then all $8$ of your great-grandparents are distinct. Counting yourself and everyone up to your grandparents, there are at least $1 + 2 + 4 + 8 = 15$ people in your family tree.
Similarly, if you are in a $d$-regular graph and you build the breadth-first-search tree from one of the vertices, it should have $1 + d + d(d-1) + d(d-1)^2 + \dotsb$ distinct vertices in it, until graph-theoretic pedigree collapse kicks in. A lower bound on girth will tell you that up until a certain point, all of those vertices are distinct, giving you a lower bound on the number of vertices in the graph.
Comment: Wow that was a nice read. Thank you alot


screenshot of my app that contains both UIKit and Camera

Question: I want to take Screen Shot of my Application containing both UIKit and Camera Elements, Actually my application is interior Decoration Application in Iphone. So requirement is when we done with decorating furniture on camera we take screenshot, that contains both UIKit and Camera element.
Comment: possible duplicate of [How to take a screenshot programmatically](http://stackoverflow.com/questions/2200736/how-to-take-a-screenshot-programmatically)
Answer: <code>// Delegate Function of UIImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];

    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    else
        UIGraphicsBeginImageContext(imageSize);

    CGContextRef context = UIGraphicsGetCurrentContext();

    // Draw the image returned by the camera sample buffer into the context.
    // Draw it into the same sized rectangle as the view that is displayed on the screen.

    float menubarUIOffset = 44.0;
    UIGraphicsPushContext(context);
    [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height-menubarUIOffset)];
    UIGraphicsPopContext();

    // Render the camera overlay view into the graphic context that we created above.
    [cameraOverlayVCObject cameraOverlayVCObject.view inContext:context];

    // Retrieve the screenshot image containing both the camera content and the overlay view
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();

    // here is that final Image I am storing into Saved Photo Albums/ Library
    UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil);
    UIGraphicsEndImageContext();

    // I dont want my Camera to be Closed
    //[self dismissModalViewControllerAnimated:YES];
    self.view.hidden = NO;
}

// now got Picture from Camera need to Render Context on it here is Function
- (void)renderView:(UIView*)view inContext:(CGContextRef)context
{
    // -renderInContext: renders in the coordinate space of the layer,
    // so we must first apply the layer's geometry to the graphics context
    CGContextSaveGState(context);
    // Center the context around the window's anchor point
    CGContextTranslateCTM(context, [view center].x, [view center].y);
    // Apply the window's transform about the anchor point
    CGContextConcatCTM(context, [view transform]);
    // Offset by the portion of the bounds left of and above the anchor point
    CGContextTranslateCTM(context,
                          -[view bounds].size.width * [[view layer] anchorPoint].x,
                          -[view bounds].size.height * [[view layer] anchorPoint].y);

    // Render the layer hierarchy to the current context
    [[view layer] renderInContext:context];

    // Restore the context
    CGContextRestoreGState(context);
    [appDelegate.cameraPicker dismissModalViewControllerAnimated:YES];
}
</code>
anything couldn't understandable, feel free to ask
Answer: use this,
<code>UIGraphicsBeginImageContext(webview.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
</code>
This will allow you to capture a screenshot of your app and it will be saved in photos in your iPhone.
Comment: I am gone through with all these solutions, This is will only Capture Above view as Image not Camera Element. I want them captured both at the same time. UIImages or Button I added on CameraView + CameraView (mean what I am watching with Camera).. I think it would be done with AV Foundation but don't know how, if anyone knows please help. I am gone through this tutorial http://developer.apple.com/library/ios/#qa/qa1714/_index.html but its Delegate Function doesn't get called. any suggestion?


Something eats all memory (I suspect memory leak on some app). How to detect what?

Question: I have server which runs liquidsoap+icecast bundle and simple website (httpd+mysqld). Nothing special. Visitors around 2000+ per day, with around 50 being online simultaneously on average.
Server has 8GB RAM. As the time goes by, amount of free memory constantly decreases, although nothing new is started on server and there are no new users. At some point it starts to swap, load on server goes up and it becomes unresponsive. Usually what I do is just restart the server...
What can be done to detect what exactly leaks memory? I use top to monitor usage of resources, but as far as I see it shows nothing helpful:

Is there any way to find out what uses that much memory? or what starts to swap to disk heavily? Any way to free up memory without rebooting the server?
Comment: Any reason why you don't try restarting some of the services (apache, liquidsoap) instead of the server?
Comment: I originally responded for normal memory usage.  I have updated with a set of tools which may help identify the problem.
Comment: @jamespo, actually I tried that, but it had no effect, so restart was the only thing I knew could help.
Comment: The 4027092k cached should explain the memory usage, no? I'm working at the moment on a similar problem elsewhere, and so far I've managed to figure out the memory transfer can be regulated with the following params:
vfs_cache_pressure
vm.dirty_ratio
vm.dirty_background_ratio This is not a complete fix and any feedback's most welcome. I hope it's a right direction to go.
Answer: Running top in batch mode to report memory sizes periodically can be used to see who is using the memory when things go south.  Runing sar in batch mode should give some good diagnostics on memory use, and related I/O.  Running munin to monitor the system should give you a graph with good detail on what memory is being used for.  This may help a lot.
You can use limits.conf to limit the maximum core size of programs.  Properly set, this should kill any programs which are leaking memory.  This works with the pam_limits module. Limits can also be set with the ulimits command.
You are running a few programs which could use large amounts of memory.  Some things you could look at include.

Poorly programmed applications running under apache2 can leak memory.  You should see the memory size increase when this happens.  You can tune apache2 to recycle children after a certain number of uses by setting MaxRequestsPerChild to 100 or so.  If this resolves the problem, then you need to resolve the leak.  I would watch this first.
MySQL may try to load data into memory.  If you have a lot of data in memory this may cause some thrashing, but should not be as dramatic as you are seeing.
If you have a large tmpfs file system mounted, then you may leak memory if files are not deleted when used.  Large long lived files can also be a problem.
If the problem is occurs at roughly the same time of day, you may have a scheduled program which is leaking memory.
If you have a program that allocates shared memory, but does not release it before exiting, you will have a relatively invisible memory leak.  If the shared memory is locked in memory, then it may force swapping.  The amount of available shared memory is typically relatively limited.
The liquidsoap+icecast bundle could run into buffering issues that use memory. I haven't used this combination, so I am not sure how this would appear.

Normal memory usage:  Free memory is not something you want a lot of.  If your system has been up for a long time and has a lot of free memory something is wrong.  Every time you read or write a file, the blocks will go into the buffer cache.  This will reduce your free memory, and is a good thing.  The system will keep enough free space to start a few programs without looking elsewhere for memory.  As many programs run quickly, their memory will be returned to the free pool when they stop running.
When you read a file that is in buffer cache, no disk access is required and the read is resolved from the buffer cache.  Writes use a similar mechanism.  If your system needs memory, the buffer cache is one of the first places that is used.  Most buffers can be released immediately.
If you have a memory leak, you will see free memory and buffers both begin to shrink.  This is still not a severe problem, as the leaked memory should eventually be moved to swap space.  Your system will still run fine until you fill the swap space, and draw down the remaining free space to the point programs can't be started.  It is typical that a small amount of swap space may be used.
Comment: @jayarjo: Munin and sar should help detecting what is going on.  If you have lots of free memory you shouldn't be swapping.  You may have a different I/O problem.  `sar` will help pinpoint which partition has the I/O and may help discover the problem.
Comment: The problem in my case is kinda weird. Even when the load is huge and server swaps heavily, there's plenty of free memory (as I understood after I read about buffers and caches). top doesn't show any process hogging memory increasingly. But load goes up and at some point server becomes unusable :|

Thanks for the detailed response.
Comment: +1 for MaxRequestsPerChild advice
Answer: You can use this command to see the top 10 applications regarding RAM usage:
ps -A --sort -rss -o comm,pmem | head -n 11

Sometimes this command helps you if many sub processes have been generated:
ps auxf

This way you can see which processes belong together.
Comment: Try to get more information with "vmstat" (e.g. vmstat -s). Or with the already mentioned tool "sar". Do you maybe have a RAM based filesystem? Then maybe "iostat" can give more information as well.
Comment: I have been in doubt whether the "pmem" (%MEM) field in `ps` or `top` output is the right thing to look at if trying to detect a memory leak: Isn't this only the percentage of the physical memory the process currently is using? But other parts of the process's used (incl. leaked) memory may be swapped out. Perhaps "size" or "vsize" would be more appropriate for measuring the size of a process? E.g., `ps -A --sort -size -o comm,size | head -n 11` or `ps -A --sort -vsize -o comm,vsize | head -n 11`
Comment: These are handy commands, thanks I will note them for future. But the problem is that there are always the same processes on top (you can see them in attached screenshot) - apache, mysql, liquidsoap, icecast. And they use (or at least are shown to use) the same amount of memory (negligible really), even when server is dying of load :|
Comment: @jayarjo: Does the number of processes change? Do you have a lot more processes? And is it a physical server or a virtual one?
Comment: I've not noticed any change in number of processes. Basically when I do top, while server is dying of load I see a very similar picture to what I've attached in original question, except the huge load :| Server is physical.
Answer: Nothing is really using that memory in terms of applications.
You need to deduct the 'cached' value which represents the page cache to get a better idea as to what your actual memory usage is in terms of program usage.
Basically this is good memory management and this is ideally what you want.
See the link here for more infomation: http://www.linuxatemyram.com/
Comment: yes found that link and read about buffers and caches, but as far as I could get from what I read, they cannot cause swapping, can they?
Comment: @jayarjo I think to understand what happens there we would need stats demonstrating the problem then. The numbers you have given do not show swapping or a lot of real memory usage.
Answer: I am not a pro at this really, but liquid soap+icecast is multimedia related. When the system is free, it caches and/or occupies memory for future use.
And if the traffic increases at a certain time of the day/ over a period of time, then it will start swapping.
At this point, if the requests ( users viewing content) increases, then the resources needed will be more than 8GB of ram.