Asp.net Core MVC Dealing with validation scripts as a seperate file

Question: I was in the process of adding javascript files to site.js and the page was recognizing the scripts however I struck a wrinkle when I tried to move the validation scripts to site.js.
Site.js appears above the validation scripts which are added to the page using
<code>    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
</code>
Rather than having the validation scripts for the page being on the page (or is this how most people do it) how do I add say add a validation.js page etc that I might add below the above entry.. further,
If I do add another page how do I minify it (add it to GULP) and add it in the production staging environment as well..
Answer: It is recommended that you should put the validation script rendering into a section as:
<code>@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
</code>
and then refer it in the _Layout.cshtml at the bottom of the body as:
<code>    @RenderSection("scripts", required: false)
</code>
Then you will be able validate your forms and these JS files will appear only at that view in which you referred.

If I do add another page how do I minify it (add it to GULP) and add it in the production staging environment as well..

You will have to minify your JS files once for all of your Views (pages) and they will work.
Comment: I already have that in the bottom of my page. I am referring to custom validation scripts in this case a custom script for validating the Australian ATO number. Its currently at the bottom of the page that uses it however I think it should be in its own file. Its under these circumstances that I ask about where do I put this custom validation script.. sorry of the question was not clear.
Comment: If it is in the validation section, modify the order in which files get rendered in the section and check the developer tooling of the browser that which file got missed who made the validations failed. Putting them in another file is also an option. But it is recommended to put them in the same section.
Answer: Ideally you'd like all scripts to be loaded at the end of the page as scripts can block the rendering of your page and make it appears slower to the user.  The way we achieve this is by using sections in our layout file.
In your layout file you could add the following code:
<code>@rendersection("scripts", required: false)
</code>
Then in your views you can add any specific scripts that they require:
<code>@section scripts {
    @Scripts.Render("~/Scripts/Validation.js")
}
</code>
Scott Gu has a good blog post that will explain sections a bit more in depth
As for minification have you looked at using the built in bundling and minification tools that come with mvc nowadays?  Here's another blog post this time by Rick Anderson that explains in all but essentially you can define different bundles which can be set to automatically bundle and minify the scripts for you.  Defining a bundle is as simple as:
<code>bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
             "~/Scripts/jquery-{version}.js"));
</code>
And outputing them to your page is the same as above except instead of the link to your source file you use the bundle link you defined. So outputting the above would be done like so:
<code>@Scripts.Render("~/bundles/jquery")
</code>


How often is the product of the distinct prime factors of a number greater than that of the next number?

Question: The radical $\mathrm{rad}\; n$ of a positive integer $n$ is the product of $n$'s distinct prime factors. For example $\mathrm{rad}\; 12=2\cdot 3=6$.
Denote the sum of $n$'s distinct prime factors by $\mathrm{spf}\; n$.

Claim: Given any $k \ge 1$, for nearly half of positive integers $n$, $\mathrm{spf}\; n > \mathrm{spf}\; (n+k)$, but for only one-third of positive integers $n$,
  $\mathrm{rad}\; n > \mathrm{rad}\; (n+k)$.

Detailed explanation:
For any $k \ge 1$, there will be $n$ such that $\mathrm{rad}(n) > \mathrm{rad}(n+k)$ e.g. $n=15, k = 1$. We define
$$
a_{n,k} = \begin{cases}
      1 & \frac{\mathrm{rad}(n)}{\mathrm{rad}(n+k)} > 1 \\
      0 &\text{ otherwise}
   \end{cases}
$$
Question: What is limiting value
$$
\lim_{x \to \infty}\dfrac{1}{x}\sum_{n \le x}a_{n,k}
$$
Instead of product when I used sum, the limiting value approached $0.5$ which means that it is equally likely the sum of distinct prime factors of a natural number is greater or less than that of the next natural number which makes intuitive sense.
Similarly I was expecting that product of the distinct prime factors of a number is equally likely to be greater than or less than that of the the next number but this was not the case. I was surprised to see that for $x = 1.5 \times 10^8$
$$
\dfrac{1}{x}\sum_{n \le x}a_{n,k} \approx 0.3386
$$
and was decreasing with $x$ hence the eventual limit is expected be be slightly less than this.
Note: The initial version of this question was with $k=1$ but the result doesn't change with $k$, hence I have updated the question.
Comment: $p_n$ for primes $p(n)$ for partitions to be precise :)
Comment: Well the Euler product is written $\prod_p \frac1{1-p^{-s}}$. $p$ is reserved for primes in this context, use $\Pi$ or anything.
Answer: Each of these products will be $\frac{n}{p}$ and $\frac{n+1}{q}$ for some $p,q\in\mathbb{Z}^+$, where $p$ and $q$ are the "leftover" primes in the factorizations of $n$ and $n+1$ when one copy of each distinct prime has been removed.
If $p\neq q$, $\frac{n}{p}>\frac{n+1}{q}\iff p<q$. Which of $p$ and $q$ is larger will be effectively "random", in that the behavior will jump around a lot and one will be larger than the other with a limiting ratio of $0.5$. (A formal proof might prove difficult, but you can certainly gather some numerical evidence to support this - I think it makes as much intuitive sense as the sum case you mentioned.)
When $p=q$, the comparison will always go in favor of $n+1$. But since $n$ and $n+1$ are relatively prime, this only happens when $p=q=1$ - i.e., when $n$ and $n+1$ are each squarefree. So we want to find out what fraction of consecutive integer pairs are squarefree, and hence what limiting ratio to exclude from the even split mentioned above.
Fortunately, we can express this as an infinite product. For a number to be squarefree is just for it to not be divisible by $4, 9, 25, \ldots, p^2,\ldots$. The limiting fraction of $(n,n+1)$ pairs which do not contain a multiple of 4 is $2/4$; likewise, for neither to be a multiple of 9 is $7/9$, and so on.
However, congruence modulo the first $N$ primes is independent over large ranges by the Chinese remainder theorem. So our probability that a "random" pair are both squarefree is
$$\prod_p\frac{p^2-2}{p^2}$$
which looks to be around $0.322634...$, or a touch under one third. This means that your limiting value will be
$$\frac12\left(1-\prod_p\frac{p^2-2}{p^2}\right) \approx 0.33868295...$$
Answer: If $n+1$ is squarefree then $p(n+1)=n+1\implies a_n=0$ thus $$\lim\sup_{n\to \infty} \dfrac{1}{x}\sum_{n \le x}a_n \le 1-\frac{6}{\pi^2}\approx 0.393$$
Comment: If your value is correct the convergence should be in $O(x^{-1/2+\epsilon})$ (that's what predicts the random model for the primes)
Comment: Ah, I missed the ≤. Apologies. A graph of the ratios from n=1000 to 100,000 is at https://imgur.com/3LOWorl, with the blue line the constant estimated to around 9 digits.
Comment: You can quickly verify with some numerical calculations that 0.39 is much too high. Try n from 1 to 10,000.
Comment: Sure this is just a rigorous upper bound, your approach is a conjectural estimate. It seems hard to make it rigorous, you should show us a plot of how well does it fit.
Comment: For $x = 1.65 \times 10^8$, the value is $0.3386851$ so I guess there is scope to tighten the upper bound.


Reason for "Gateway Timeout" (mod_wsgi)

Question: I get "Gateway Timeout"

504: The gateway did not receive a timely response from the upstream server or application.

I use apache with mod_wsgi Version 4.4.8.
In the apache error log I see:
Timeout when reading response headers from daemon process 'md':
    /home/user/mc/src/mc/mc/mc.wsgi

The wsgi config:
WSGIDaemonProcess md user=mc group=users threads=1 processes=4
                     maximum-requests=1000
                     request-timeout=600
                     python-home=/localhome/user/mc
WSGIScriptAlias /mc /home/mc/src/mc/mc/mc.wsgi
<Location "/mc/">
    WSGIProcessGroup md
    WSGIApplicationGroup %{GLOBAL}
    Require all granted
</Location>

The timeout happens after 100 seconds.
The timeout according to config is 600 seconds.
I have no clue why this happens. It is repeatable. The error is repeatable. It happens every time for a particular URL.
Step one would be for me: A better error message. Who is responsible for this message "Timeout when reading response headers from daemon process"?
Answer: I found the solution myself.
There was Timeout 100 somewhere in the Apache config.

Reason for "Gateway Timeout" (mod_wsgi)


How should I conduct a double time tempo change?

Question: I am working on a pop arrangement. It starts out in a simple 4/4 quarter note equals 90 and then a tempo change doubles it. Now it's eight notes = 90 and quarter = 180.

Do I change the time signature to 4/8?
When I conduct if I lose my tempo while going slow then doubling is that just practice work or can changing the meter help me?
Comment: Why not just score it in half time, rather than doubling the tempo? Problem solved, song is still at 90bpm, everybody's playing 16ths instead of 8ths.
Answer: Not 4/8 for a pop song.
DOES it go into a fast 4 or a moderate 2?  If the former, write 4/4 quarter=180.  If the latter, write cut time half=90.


Why does it make sense for all the members of a random sample to come from the same distribution?

Question: In all the examples I've seen so far, we always make the assumption that when we take a random sample from some population, each member of the sample comes from the same distribution as the other members i.e. they're identically distributed
Why is it okay to make this assumption?
Is it not possible to have members of the sample that follow some other distribution?
Is this a question worth pondering ?
Answer:
...we take a random sample from some population...

Here, population represents the distribution. If you take samples from different populations, your samples would be from different distributions, and therefore not identically distributed.
Comment: How do we know that a population follows a particular distribution? Would we deduce what the population distribution isfrom the empirical distribution of a large sample from that distribution?
Comment: population doesn't follow a distribution, it represents it. individual samples follow distribution. I couldn't understand your second sentence.
Answer: Often it is simply because it is a reasonable assumption. If you sample from a population, say for instance, the height of men in Europe, it is reasonable to assume they follow the same distribution.
If you are in a setting where you are uncomfortable with the assumption of identically distributed, you could do the bayesian approach and and construct a hierarchical model. Then you can get different posterior distributions, but then these are based on some "deeper" assumption. But then you need to consider how to construct this model.
In the end I think it boils down to if you are going to make a model, you need a place to start. And if you take measurements of individuals in a population, the assumption is reasonable.


Grant a specific user to modify a specific table rows

Question: For security reason, I don't like the auditor has the privilege to modify all the rows of the table. So I tried:
GRANT UPDATE audit_comment ON cgis TO auditor IDENTIFIED BY 'audit@TE';

But it failed
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'audit_comment ON cgis TO auditor IDENTIFIED BY 'audit@TE'' at line 1

I've googled a lot, but I couldn't find the answer, maybe mysql doesn't allow us to do this?
Answer: You could also try using views instead of tables which can be used to restrict access to only a certain type of rows. Here is a very basic example
PICTURES table:
CREATE TABLE IF NOT EXISTS pictures_t
(
   id      INT NOT NULL auto_increment,
   public  BOOL NOT NULL DEFAULT TRUE,
   PRIMARY KEY(id)
)

PICTURES view:
CREATE VIEW pictures_v
AS
SELECT
   P.*
FROM pictures_t AS P
WHERE
   P.public = TRUE
ORDER BY id;

Create Users:
GRANT SELECT, INSERT, UPDATE ON db.pictures_t TO 'god'@'localhost' IDENTIFIED BY 'heaven';
GRANT SELECT, INSERT, UPDATE ON db.pictures_v TO 'satan'@'localhost' IDENTIFIED BY 'hell';

Answer: You cannot specify privileges on rows, just on columns. Check the syntax here
You need something like
GRANT UPDATE (audit_comment) ON db_name.cgis TO 'auditor'@'host_name'
Answer: Alternatively, consider using a stored procedure.  Have the procedure update the rows, and set it to use SQL SECURITY DEFINER.  Within the stored procedure, you can include whatever validation you need, and revoke the access to modify rows from the person or people you want to limit it on.  It's a bit more complicated, but it's the only way I know of to limit the kind of access you're looking for.
Comment: Apparently they've removed the article from their site.  Why, I have no idea, but Google can't find a current copy of it there any more.  Here's a link to it from the Internet Archive.  http://bit.ly/IE9dHW  There's also a mirror here: http://mirror.neu.edu.cn/mysql/tech-resources/articles/mysql-storedproc.html


Como eu faço para alinhar ao centro usando html5 e css3 um bloco com 4 vídeos embedados do YouTube?

Question: Estou tentando alinhar ao centro um bloco de vídeos embedados do YouTube (2 em cima e 2 em baixo) de forma que o bloco todo saia do alinhamento esquerdo (como é default ao embedar) e fique centralizado.
Já tentei colocar 2 em vídeos em divs separadas, já tentei criar uma única div e centralizar via css no head, mas todos os vídeos ficam alinhados em modo de coluna e não de bloco.
O código atual está mais ou menos

    Desafio de vídeo

Vídeos legais para assistir

Agradeço a ajuda desde já!
Answer: Pode criar uma outra div envolvendo esses dois blocos e organizar eles usando flexbox, segue estrutura html:

Agora no css, você pode fazer assim:
.bloco-videos {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  gap: 1rem;
}

.bloco {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  gap: 1rem;
}


Passar um id por um checkbox no Angular 5

Question: Preciso passar um id através de um método em um form quando meu checkbox for marcado. Ja tentei de varias maneiras sem nenhum resultado.
Abaixo segue o codigo

{{event.name}}

                {{event.date}}

                {{event.adress_id}}

              Mapas

                    convidado
                    convidar
                    confirmação

                    {{guest.name}}
                    {{guest.id}}

                      <input type="checkbox" [ngModel]="eventGuest" id="eventGuest" autocomplete="off" name="guest.id" [value]="guest.id">

                      <fa-icon *ngIf="guest.confirmed==1" [icon]="faCheckSquare"></fa-icon>
                      <fa-icon *ngIf="guest.confirmed==0" [icon]="faSquare"></fa-icon>

                    <input type="submit" value="Convidar">

      </form>

Answer: Basta utilizar o ngModelChange no input.
html
<input type="checkbox" id="1"
       [ngModel]="filter" (ngModelChange)="onFilterChange($event)"> Checkbox

TS
export class HelloWorld {

  filter = false;

  onFilterChange(event: any) {
    console.log(event);
    this.filter = !this.filter;
  }
}

Espero que ajude!
Aqui o exemplo já funcionando https://codesandbox.io/embed/q9rvn6kpq


Change background color multiple times while scrolling down the page

Question: I'm working on this project where I'm creating a website using parallax scrolling. It's supposed to be one long one pager. As you scroll down the page the background color is supposed to change when you get to each new section of the page.
I have spent days searching the web and also here on stackoverflow, but I haven't found anything that works in the way i want it to.
I found this script here on stack:
 var tStart = 100 // Start transition 100px from top
      , tEnd = 500   // End at 500px
      , cStart = [250, 195, 56]  // Gold
      , cEnd = [179, 217, 112]   // Lime
      , cDiff = [cEnd[0] - cStart[0], cEnd[1] - cStart[1], cEnd[1] - cStart[0]];

    $(document).ready(function(){
        $(document).scroll(function() {
            var p = ($(this).scrollTop() - tStart) / (tEnd - tStart); // % of transition
            p = Math.min(1, Math.max(0, p)); // Clamp to [0, 1]
            var cBg = [Math.round(cStart[0] + cDiff[0] * p), Math.round(cStart[1] + cDiff[1] * p), Math.round(cStart[2] + cDiff[2] * p)];
            $("body").css('background-color', 'rgb(' + cBg.join(',') +')');
        });
    });

http://jsfiddle.net/dtZDZ/12/ Here is the fiddle
This script does exactly what I want, except that I only change color one time back and forth. I need it to change background color like 4-5 times while you scroll down the page. Also I would like it to have a smooth transition when changing colors like in the fiddle :)
I hope someone out there can help me with this or just point me in the right direction.
Thank you in advance
Comment: why you want to do that with javascript/jQuery? it can be done by css html
Comment: @Sarfaraz, CSS doesn't support scroll, you need JS in this one!
Comment: @Safaraz I figured it was the best solution and I also wanted a sort of animated effect when it changed between the colors. But if it I can be done in html css that would be great. Can you show me how?
Comment: @drinchev Do you have a solution with JS then :)?
Comment: [example](http://jsfiddle.net/3zWfN/).
Comment: @Vucko is it possible to say specifically when the colors should change? For example: When you scroll 1500px down the page it turns green and another 1000px it turns red and so on?
Comment: @JonasNilsson you can googling with `parallax scrolling` keyword and you can see demos and also when you debug it you can understand how to do that.
Comment: @JonasNilsson here is a link for demo http://nettuts.s3.amazonaws.com/2138_SimpleParallax/Demo/index.html
Comment: @JonasNilsson here you [go](http://jsfiddle.net/3zWfN/1/).
Comment: @Vucko Thanks. It's close to what I need. Can you maybe do like a smooth transition from color to color like this script http://jsfiddle.net/dtZDZ/12/ . Then I would be very grateful :)
Comment: Derived from Vucko - http://jsfiddle.net/G4j6d/
Comment: @miro But with this script I can't choose what color and when it should change, can I?  In Vucko's script I could do that.
Answer: You could use a gradient background using css :
body {
background-color: linear-gradient(red, blue, green, blue, red)
}

Scrolling down, your background will change. This method is a little bit "cheaty", but it works as it will loop when it arrives at the end of the background.
Answer: Here you go :
You may assign as many colors as you like in your colors variable
var colors = [
     [250, 195, 56], // Gold
     [250, 0, 0],    // Red
     [0, 250, 0],    // Green
     [0, 0, 250],    // Blue
     [179, 217, 112] // Lime
];

var height = $('body').height() - window.innerHeight;

$(document).scroll(function() {
  var steps = Math.floor(height / colors.length);
  var position = $(this).scrollTop();
  var currentStep = Math.floor(position / steps);
  if ( currentStep === colors.length ) currentStep = colors.length - 1;
  var rgb = $("body").css('background-color').replace('rgb(','').replace(')','').replace(/\s/g, '').split(',');
  var previousColor = colors[currentStep] || colors[0];
  var nextColor = colors[currentStep+1] || colors[colors.length-1];
  var percentFromThisStep = ( position - ( currentStep * steps ) ) / steps;
  if ( percentFromThisStep > 1 ) percentFromThisStep = 1;

  var newRgb = [
     Math.floor(previousColor[0] + ( ( nextColor[0] - previousColor[0] ) * percentFromThisStep )),
     Math.floor(previousColor[1] + ( ( nextColor[1] - previousColor[1] ) * percentFromThisStep )),
     Math.floor(previousColor[2] + ( ( nextColor[2] - previousColor[2] ) * percentFromThisStep ))
  ];

  $("body").css('background-color', 'rgb('+ newRgb.join(',') +')');
});

Demo here : http://jsbin.com/ulohif/1/edit
Comment: Thanks for the script but I need to be able to choose when the different colors take place. Like Vucko did earlier. Like at a 1000px from the top turn red, 2000px from the top turn green and so on. Can you incorporate this in your script :)?
Comment: Well, you can figure it out by yourself from now on. Play with this code a bit.
Comment: Damn ;) But okay :) I'm pretty novice when it comes to scripts, but I will try
Comment: I know it's a lot to ask but can you fix it for me? I really don't have any clue to be honest. I would appreciate it a lot :)


Present Modal view over Modal view not showing

Question: I've had a look on SO and can't find an answer to this.  I'm presenting a modal view from:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
     ICObservationEditController *controller = [[ICObservationEditController alloc] initWithObservation:[self.observations objectAtIndex:indexPath.row]];
     UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
     navController.navigationBar.barStyle = UIBarStyleBlackOpaque;
     navController.navigationBar.tintColor = [UIColor grayColor];
     [self.editController presentModalViewController:navController animated:YES];
}

Once presented, as an option I want to present a text message over the top from the MessageUI framework:
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText]) {
    NSLog(@"presented");

    //code here for text body

    controller.recipients = [NSArray arrayWithObjects:@"", nil];
    controller.messageComposeDelegate = self;
    [self.editController presentModalViewController:controller animated:YES];
}

The debugger confirms I'm receiving the event, but no view is presented.  The code is correct as I have used the exact same code in other apps when not already in a modal view.
Comment: It is not a good practice to present a modal view from a view that is already being presented modally. http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ModalViewControllers/ModalViewControllers.html
Answer: The UIKit won't allow this but there are workarounds. This article should help you.


ANOVA table in R: F-value does not "match the math"

Question: I was playing around with a simple linear models when I noticed that, in the ANOVA table, the ratio MSreg/MSres does not exactly correspond to the F-value. Indeed, the two values are very similar but not the same.
Here my script
#quick view of the dataset
> head(my_data)
  Diameter Height
1    0.325  0.080
2    0.320  0.100
3    0.280  0.110
4    0.125  0.040
5    0.400  0.135
6    0.335  0.100

#setting up the lm()
> ls1 <- lm(Diameter~Height, data=my_data)
> anova(ls1)
Analysis of Variance Table

Response: Diameter
          Df  Sum Sq Mean Sq F value    Pr(>F)
Height     1 0.82415 0.82415  602.63 < 2.2e-16 ***
Residuals 98 0.13402 0.00137
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Here 0.82415/0.00137=601.5693 which is not the F value in the table. Is there a particular reason for that?
Comment: It's an issue with loss of numerical precision due to rounding. Try (0.82415 / 1 ) / (0.13402 / 98).
Answer: The number 0.00137 is rounded (hopefully, rather than truncated) to around three figures of accuracy (actually, if it's rounded, the % error could be nearly half a percent -- the starting digit is only "1", so  it's really somewhat less than three figures, perhaps nearer to two).
The accuracy of your calculated ratio using that number should not be expected to have greater accuracy, but it could have less (imagine the numerator rounded up while the denominator rounded down, for example). So to three figures (at best) you have 602 give or take something in the ballpark of 1 or so.
i.e. everything is about what it should be to the accuracy we can expect.
You did the calculation at the end to 7 figures. If you want close to 7 figure accuracy you'll need at least 7 figures in the numbers you calculated it from (as long as you didn't do any calculation that would lead to a larger loss of significant figures, like subtracting two almost-equal numbers). For a simple ratio like this aim for one or two more figures than you want to have at the end. For something a bit less stable you may need more again.
In that case, the rounded numbers in the table are not sufficient for the  purpose calculation check you want to do. If you want to check the calculations to say 4 or 5 digits, you would need to extract more figures for the mean squares that are the inputs to that ratio (this is easy to do in R).
https://en.wikipedia.org/wiki/Significant_figures
https://en.wikipedia.org/wiki/Loss_of_significance


Transformation of data in mixed models (lme4)

Question: I am trying to fit the following model where I'm measuring fungal growth (length) in Petri dishes that were kept at 0C, room temperature, and 50C (Treatment).

<code>myModel <- lmer(Length ~ Treatment + Chemical_1 + Chemical_2 +
(1 | Treatment), data = myData, REML = F)
</code>

Each treatment has 60 Petri dishes. I quantified two chemicals in the media before fungal inoculations, and now I am determining if any of the chemicals in any of the treatments is playing a role in influencing fungal growth. All my variables (response and fixed effects) are NOT normally distributed and I have been reading about the different options available to deal with the situation, however; the more I read the more I get myself confused!!
Any idea what's the right way to move forward?
Comment: Why do you want to put a random effect per Treatment group? Do you expect that length measurements of Petri dishes within the same treatment are correlated? Mixed models are typically use to account for correlations you expect to have in your data.
Comment: Then I'd say you don't need to put treatment as random effect. As said in my previous comment, by putting a random effect per treatment you assume that length measurements are correlated within each treatment group.
Comment: the random effect represents the fact that the Petri dishes in each treatment (0C, room Temp. and 50C) were randomly selected. I don't expect that the length measurements in each treatment will be correlated.
Answer: Welcome to CV.
First of all, multilevel models do not assume that the variables are normally distributed.  They assume the errors are normally distributed. We don't know the error, but we estimate it by the residual.
Second, if it does turn out that your residuals are not normally distributed, what to do next depends. Your DV is length. If you take the log of length, then your model will have effects that change length multiplicatively rather than additively. That is a 1 unit change in an IV will lead to multiplying the expected value of the DV by a constant. Does that make sense? If it does, try log(length). If it doesn't, then maybe you need a nonlinear multilevel model.
Comment: Thank you so much for the answer. I checked the errors for normality and it does seem to be normally distributed. Is there any specific test that I can perform to formally confirm the normality?


Hosting docker images on multiple registries but reference them the same way e.g. in a k8s deployment

Question: Since I started with docker there is one question that follows me and I could not get a good answer so far.
Let's assume I have a .yaml file specifying a k8s deployment. We are building our docker images on a local build server and they are getting pushed to a local registry e.g. registry.mycompany.com which is only accesiable in our local company network. So in my .yaml I will reference that image with "image: registry.mycompany.com/myrepo/myimage:1.0".
Now when I deploy that on a local k8s cluster it works correctly as the domain name gets resolved and the image can be pulled. Now I want to deploy the same e.g. in any Cloud. Well, it wont work as the registry is not availiable. Same goes if I want to deploy the same .yaml at one of my customers places where they also for a good reason can not access my local registry.
How is this kind of thing solved usually? Right now, I setup another registry either at my customers or in the cloud account, retag all my images and push them to that registry and also change all the image references in the .yamls when I deploy at a customers place or in the cloud. Therefore having to maintain a lot of sets of files that are 99% the same. That is not how it should work right?
My "wish" would be that I can specify just the image name and tag "myimage:1.0" and the k8s cluster just checks all availiable registries if he can find the image and pulls it. But I am also aware that there is no "list of well-known-registries", you either specify the registry in the image name or leave it out and docker hub will be queried. However it would be very cool if I can specify just
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: MyDeployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myimage
    spec:
      containers:
        - name: myimage
          image: 'myimage:1.0'
          ports: []

and a list of registries:
registries:
    - registry.mycompany.com
    - registry.cloud.com
    - registry.localcustomer.com

But there is nothing like that, right?
The only other solution I can think of, is to build everything into helm charts, make the first part of the image reference a variable and pass the registry as a variable to the chart.
Any ideas and infos are welcome. Thanks in advance :)
Comment: Hello. As you said, the Helm chart version should be most convenient solution. Have you checked [Kustomize](https://blog.stack-labs.com/code/kustomize-101/) by any chance as an alternative solution?
Answer: There are some workarounds to achieve the result like you've described in your question:

Helm Chart
Kustomize
Registry

Helm Chart
As you've said in the question:

The only other solution I can think of, is to build everything into helm charts, make the first part of the image reference a variable and pass the registry as a variable to the chart.

This is subjectively most convenient way to specify the repositories for Deployment.
The example of it could like below:
deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ubuntu
spec:
  selector:
    matchLabels:
      app: ubuntu
  replicas: 1
  template:
    metadata:
      labels:
        app: ubuntu
    spec:
      containers:
      - name: "{{ .Values.image.repo }}{{ .Values.image.name }}:{{ .Values.image.tag }}"
        image:
        command:
        - sleep
        - "infinity"

Values inside of a template could be provided either by:

values.yaml file:

image:
  repo: gcr.io/ # <-- only an example
  name: ubuntu
  tag: latest

$ helm command like:

$ helm install ubuntu . --set=image.repo=eu.gcr.io/

A tip!
Specifying --set parameter with already existing value in values.yaml will override it (in this example)!

Kustomize
You can also use kustomize to "render" the Deployment with their respective repositories and images.
There is quite extensive explanation on how it can be done in below blog post:

Blog.stack-labs.com: Code: Kustomize 101

Example of such solution (by following above link) could be boiled down to:
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sl-demo-app
spec:
  selector:
    matchLabels:
      app: sl-demo-app
  template:
    metadata:
      labels:
        app: sl-demo-app
    spec:
      containers:
      - name: app
        image: foo/bar:latest
        ports:
        - name: http
          containerPort: 8080
          protocol: TCP

custom-image.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sl-demo-app
spec:
  template:
    spec:
      containers:
        - name: app # IMPORTANT
          image: eu.gcr.io/ubuntu:latest

kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - deployment.yaml

patchesStrategicMerge:
- custom-image.yaml

After running above example with:

kustomize build

You should see changes in image:

from: image: foo/bar:latest
to: image: eu.gcr.io/ubuntu:latest

You could also take a look on this StackOverflow answer:

Stackoverflow.com: Questions: Kustomize add imagepullsecrets to all deployments

Registry
You can also take a look on registry project such as Harbor.
You can read on their github page:

Harbor is an open source trusted cloud native registry project that stores, signs, and scans content. Harbor extends the open source Docker Distribution by adding the functionalities usually required by users such as security, identity and management.
Features

Cloud native registry: With support for both container images and Helm charts, Harbor serves as registry for cloud native environments like container runtimes and orchestration platforms.

Role based access control: Users access different repositories through 'projects' and a user can have different permission for images or Helm charts under a project.

Policy based replication: Images and charts can be replicated (synchronized) between multiple registry instances based on policies with using filters (repository, tag and label). Harbor automatically retries a replication if it encounters any errors. This can be used to assist loadbalancing, achieve high availabiliy, and faciliate multi-datacenter deployments in hybrid and multi-cloud scenarios.

...
-- Github.com: Goharbor: Harbor

With it you could:

Create repositories that could be used only by authenticated and authorized accounts.
Use it for replication purposes between locations.

Adding to that you could also look on Docker Registry proxy like the one below:

Hub.docker.com: Rpardini: Docker registry proxy

Additional resources:

Helm.sh
Github.com: Kubernetes sigs: Kustomize
Comment: Thanks a lot for that answer :) We already use harbor. However, with each registry at each location I would still have another name. E.g. I would have to pull registry.mycompany.com/myrepo/myimage:1.0, registry.cloud.com/myrepo/myimage:1.0 and registry.localcustomer.com/myrepo/myimage:1.0 depending on which location I am resulting in my original issue. Right now it looks for me the helm chart solution is the way to go.


Is there any other blues chord progression?

Question: I've seen many blues songs, with progression:
I  / / / | I  / / / | I  / / / | I  / / / |
IV / / / | IV / / / | IV / / / | IV / / / |
V  / / / | V  / / / | I  / / / | I  / / / |

or
I  / / / | I  / / / | I  / / / | I  / / / |
IV / / / | IV / / / | IV / / / | IV / / / |
V  / / / | IV / / / | I  / / / | I  / / / |

or
I  / / / | I  / / / | I  / / / | I  / / / |
IV / / / | IV / / / | V  / / / | V  / / / |
V  / / / | IV / / / | I  / / / | I  / / / |

which it's kinda the same. Is there any other progression for blues?
Comment: Usually bars 5-8 of a 12 bar blues are IV,IV,I,I
Comment: The most common is  I,  I,   I,   I,    IV,   IV,    I,     I,    V,    IV,     I,    V
Comment: In the most common 12-bar blues forms, in bars 7 and 8 you would go back to I, not to IV or V.
Comment: Check the jazz variants: http://en.wikipedia.org/wiki/Jazz_blues#In_jazz
Comment: Try | I7 | IV9 | I7 | I7 | IV9 | IV9 | I7–ii7 | iii7–♭iii7 | ii7 | IVmin7 | I7–IV9 | I7–Vaug | from the Allman Bros version of Stormy Monday Blues (see http://en.wikipedia.org/wiki/Stormy_Monday for details).
Comment: Love to know why people put in the slashes - and the barlines, for that matter. Writing words, we leave spaces. Next word after a space. Same works for chord sequences, until you have more than one chord in a bar. Then I use brackets (underneath), wish I could do that on a qwerty board...
Comment: @Dave I know, I'm lazy to input that :p
Comment: @Kirk A - one of the nicest 12 bars written. Originally I believe as a standard 12 bar.
Comment: There are potentially an infinite number of chord progression that could be used for the blues. Cf. *Who Do You Love?* by Bo Diddly has the following progression: i i i i i i i i i i i i i i i i etc.
Answer: 12 bar blue sequences - poffle.com shows at least a dozen. The blues sequence doesn't have to be 12 bars long, it's just that this is the commonest. 8 and 16 are other well used ones. Basically putting 7ths onto each chord will help to bluesify a sequence. Or 9ths, which sound more jazzy. A lot of varieties use 'passing' chords such as diminished to get from one main chord to another. Others will go off on one, for instance, be in C, then find their way to E for a bar, before going 'round the houses' (up in 4ths) to get back to the original C key and chord. Most will use a G (V) as the ultimate turnaround chord, as that leads straight to I for the next verse.
Comment: I wrote a 20-bar blues -- essentially alternating 8-bar and 12-bar. Whatever works, *works*.
Answer: I would say that the basic idea of the (12 bar) blues is this:
4 bars with the feel of I:
Could be as simple as I | I | I | I, or as complex as I | vii III7 | vi | II7 | v I7 (notice that in the important places, the harmonic onbeats, the chords are I, and vi (the relative minor), giving the feel of I even though that chord doesn't appear much.
4 bars, 2 with the feel of IV and 2 with the feel of I:
Traditionally this is IV | IV | I | I, but it could be something like IV7 | iv bVII7 | iii VI7 | biii  bVI7 (even though there isn't much sense of I in the the latter 2 bars, it still sounds like a blues due to the context).
4 bars, 2 with the feel of "coming back to I", and 2 with the feel of I:
This could be V | IV | I | I, or along the lines of | ii | V7 | I VI7 | ii V | (a ii V heading back to I, and then a turnaround in I.
The idea of the blues can also be extended to different numbers of bars.
For instance, in Grease, virtually every song is a blues (or I IV vi V7 (Those Magic Changes)), but only one is 12 bars long.
As I remember, there is also a 14 bar blues:
I   | I   | I | I
IV  | IV  | I | I
V   | IV  | V | IV
I   | I

a 10 bar blues:
I    | I   | I | I
IV   | IV  | I | I
V IV | I

and an 8 bar blues.
The 16 bar blues also exists:
I  | I  | I | I
IV | IV | I | I
V  | IV | V | IV
V  | IV | I | I

The chords in the blues can also have their quality altered - a traditional blues is likely to have all dominant 7th chords, a more modern blues might have higher extensions, and you can also have blues in minor keys.
The blues are also linked by the use of the blues scale to improvise over them (1 b3 4 b5 5 b7) although this scale can also be used in other situations (and often seems to be overused).
N.B. The complicated blues I gave as an example is the Bird changes (that page also lists a couple of other blues for comparison).
Comment: The 7th chords in blues are _not_ dominant seventh, though they're enharmonically equivalent to dominants (but what makes a chord a dominant is the classical V-I resolution, which doesn't happen in blues). Those chords should rather be understood as approximations to [harmonic seventh chords](http://en.wikipedia.org/wiki/Harmonic_seventh_chord).
Answer: We could go the way of Charley Patton's "Hammer Blues" ....
| 1 / / / | 1 / / / | 1 / / / | 1 / / / |
| 1 / / / | 1 / / / | 1 / / / | 1 / / / |
| 1 / / / | 1 / / / | 1 / / / | 1 / / / |

Or Skip James' "Cypress Grove Blues" ...
| 1   / / / | 1 / / / | 1 / / / | 1 / / / |
| 1   / / / | 1 / / / | 1 / / / | 1 / / / |
| 5m7 / / / | X / / / | 1 / / / | 1 / / / |

Where X is the fifth as min7, C7, G or whatever.
The other alternative is to go full jazzy, presented in G:
| G7  / / / | C7    / / / | G7 / / /   | G7  / /  / |
| C7  / / / | C#dim / / / | G7 / / /   | Em7 / /  / |
| Am7 / / / | D7    / / / | G7 / Em7 / | Am7 / D7 / |

I stole some of these progressions from Bob Brozman and you can find others there.
Comment: Edited - you have to put  before and  after. Now waiting for approval as I don't have enough rep.
Comment: If someone could edit this so that it didn't show the chord descriptions in the jazzy version, I'd love it.
Answer: The sequences you've listed are extremely common, but there are thousands of variations that you could still call blues. So many, that it becomes futile to try and "collect" them. Just listen to lots of blues, listen to the chords and learn to spot the different sequences.
One example "Going Back Home" by Dr Feelgood:
 | 1 / / / | 1 / / / | 1 / / / | 1 / / / |
 | 4 / / / | 4 / / / | 1 / / / | 1 / / / |
 | 5 / / / | 4 / / / | 5 / / / | 3 2 1 / |

Answer: On (lots of) available evidence, the most common blues progressions as of the 1910s were
I-I-I-I-IV-IV-I-I-V-V-I-I or very similar (with e.g. AAB or AAA lyrics, where A just means it's the same lyric again and B means it's different)
and
I-I-I-I-IV-IV-I-I-IV-IV-I-I-V-V-I-I or very similar (with e.g. AAAB or ABBB lyrics).
(IV-IV-I-I-IV-IV-I-I-V-V-I-I or very similar was far less common early on, but still survived until e.g. Junior Parker's "Mystery Train.")
W.C. Handy's dislike of very repetitive lyrics, such as AAAB, and his huge influence on other composers once he became a well-known writer of blues caused that second, 16-bar-blues progression to drop far off in popularity in the late '10s and '20s, but it was still fairly well-known; e.g., Lightnin' Hopkins ever used it.
Progressions ending ...V-IV-I-I were actually rarely used before 1930, despite the fact that that later became so accepted as a well-known blues cliche. Eight-bar folk songs were extremely popular with whites and blacks as of about 1900 and there seems to have been little association between the 8-bar song and the idea of the blues song until about 1930 either.
Twelve-bar non-blues folk songs were very popular among black musicians as of about 1900-1905, and the IV-IV-IV-IV middle mentioned above was more popular in them than in blues, but occasionally found in blues, such as "Rolling Blues" by Bo Carter and "Royal Garden Blues" by Williams and Williams.


I want to PROGRAMMATICALLY change the roles that can view a block

Question: What I really want is that I have a block and I want it to be shown only for authenticated users.
Can anyone help me?
Note: I want to do it programmatically without an extra module.
Comment: Possible duplicate of http://drupal.stackexchange.com/questions/69861/how-to-assign-block-access-programmatically (assigning access to the "authenticated user" role in your case). BTW, it would be useful to edit the original question to mention that you want to do it programmatically ;)
Comment: admin is also authenticated, is that what you want?
Answer: Check out this module block access
Answer: there is the option of assigning a role in the block settings under the Visibility settings.
Comment: use php code for the body section and put the condition `if($user == admin) { // body content }` the body content only show if user admin.
Comment: as body content what do you mean?
Comment: if you add block then you write your code under "Block body".
Comment: Is the main-menu block from admin_menu module
Comment: can you explain what actually you want.
Answer: hook_block_list_alter()
global $user;
check $user->roles and unset your block:
function modulename_block_list_alter(&$blocks){
  global $user;
  $roles = $user->roles;
  if(!in_array('authenticated user', $roles)){
    unset($blocks[6]);
  }
  // 6 is actually a block id witch is
  //an array key from $blocks
}

I have just tested it with simpletest and it works. You need to check the user roles also.
Comment: could you help me how to unset a block?
Comment: global $user;
  if (!isset($user->uid)) {
    unset($blocks[19]);
  }  this does not work for me
Comment: $user->id is allway set. like $user->id = 0 for anonymous
Comment: global $user;
  if ($user->uid = 0) {
    unset($blocks[19]);
  }     It also does not work again...
Comment: with $user->uid = 0 you just assignet 0 to $user->uid. Replace it with $user->uid == 0 or even better take a look on my last edit;)
Comment: again not working :/ :/ :/
Comment: copy-paste my code. change `modulename`, `6`, and `authenticated user` accordingly. I have tested it in simpletest
Comment: it works thx!!.
Answer: If you looking it through grammatically so follow this.
function hook_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'demo_block1':
      if (in_array('Admin', array_values($user->roles))) {
        $block['content'] = t('Hello Admin');
      }
      break;

    case 'demo_block2':
      if ($user->uid) {
        $block['content'] = t('Hello Authenticated User');
      }
      break;
  }

  return $block;
}


How to transfer data from one table into another?

Question: Okay, I've 2 tables. One is called users2 and one is called user_totals. ive rows that are called clicks(impression_count), fclicks(use_count), completed_stus(completion_count). the ones in braces are the new ones in the user_totals table. Anyway I'd like to add all the ints from the first table into the second table but only if the stats in the second table are 0. also it should be added to the same user id which is id in the first table and user_id in the second. Could somebody give me a working mysqli statement to perform that ?
Answer: You can create a insert with select:
<code>INSERT INTO x
    (a, b, c, d)
SELECT a, b, c, d
FROM y
WHERE z=2
</code>


Probability measures from states on $C(X)$

Question: Let $X$ be a compact Hausdorff space and let $\omega$ be a state on $C(X)$. I know by Riesz representation theorem that states on $C(X)$ corresponds to probability measures on $X$ and vice versa. Given a probability measure $\mu$, I know how to construct the state, it is given by
$\omega_m(f)=\int f d\mu$. How to go the other direction?
That is given a state $\omega$, is it true that the measure corresponding to it can be calculated by $\mu(B)=\omega(1_B)$, where $B$ is a Borel measurable set and $_B$ is the indicator function. Is indicator functions are continuous? At least for Borel measurable sets?
Comment: Indicator functions are not continuous and there is no simple construction of $\mu$. In particular when $X$ is connected **no indicator function is continuous** except the two trivial ones corresponding to the empty set and $X$.
Answer: One standard way that I know of to go back from a state (functional) $\omega$ on $C(X)$ to a measure, is to consider Urysohn functions for pairs $(K,U)$, where $K$ is compact and $U$ open with $K \subseteq U$; such function are continuous $X \to [0,1]$, are $\equiv 1$ on $K$ and $\equiv 0$ outside $U$, and then for such a function $\omega(f)$ approaches what $\mu(K)$ should be for $U$ "closer to $K$". Note that local compactness of $X$ is need to have enough of such pairs; usually we can take infima of $\omega(f)$ for such Urysohn functions, and when we have values for $\mu(K)$, inner regularity of $\mu$ tells us what the value on all Borel sets of $X$ should be, etc.


How can I remove the right margin of the last ?

Question: I tried :last-child {margin-right: 0;} but it didn't work.

.navigation-menu .social-icons i {
  margin-top: 15px;
  margin-right: 10px;
  color: #FFFFFF;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.css" rel="stylesheet" >

Answer: The selector for that should be
.navigation-menu .social-icons a:last-child i { ... }

You are adressing the i inside the last a element inside the .social-icons div, so the :last-child has to be appended to the a.
Answer: please add following style
.social-icons i:last-child{
  margin-right: 0px;
}


Generate a new form

Question: I want to insert a form element (type = 'select') into an EXISTING page.
Normally we would use define a new page with a page callback, the page callback would then call drupal_get_form.
In this case, the page is being generated by views and I want to simply insert a form field within hook_views_pre_view .
Not having success so far with drupal_get_form or drupal_build_form.
drupal_build_form is advertised as returning a rendered form. But doesn't seem to work.
Comment: Where do you want to insert the field?  Can you use a block?
Comment: No... as I indicated, I want to insert a form into an existing page that is being generated by Views. I am using hook_views_pre_view to prepend dynamic data into the output. It is within that hook that I want to insert the form. I'm already using renderable arrays to insert various items...

I simply want to add a form.
Answer: In Drupal 7 you can achieve by the following steps

You can embed a node creation form inside a VIEW

Either in VIEW Header or you can created a new VIEW and attach it to your VIEW

For this example I am embedding inside Views Header. Embedding inside Views Header will be the better options. Click to Add Views Header

Select Global: Text area

Add the PHP code and don't forget to change the Text Format to PHP

PHP code

<?php
    module_load_include('inc', 'node', 'node.pages');
    $node_form = node_add('node_type');
    print drupal_render($node_form);
?>

Note :

Don't forget to replace node_type in the PHP code.
Use hook_form_alter for node form redirection, as after the node creation the form will redirect to node detail page. If you want to redirect to your page then use $form_state['redirect'] = 'mycustompage'; reference
Enable PHP Filter module using admin/modules

Set the Permissions for this module by enabling "Administrator" for Execute PHP Code as follows:
Comment: That would probably work.

Generate a new form


Flamenco sketches ear training vs. sheet music

Question: I'm trying to get Coltrane's solo on Flamenco Sketches from Kind of Blue by Miles Davis, and i think i'm missing out on what i read on the spread sheet.
This is the relevant part (the beginning of the solo):

It's in the key of D major, so far so good.
But the first note being played is clearly (to my ears) is a b followed by  a c note (not sharpen) while the notes state it begins with a c# followed by a d, and it just sounds awful.
Am i reading the sheet wrong? (it's the official sheet by hal leonard)
Or am i missing some theory regarding these notes and how to read them?
(by the way, the last note should be d and not e#, same goes to that as well.
I'm trying to play this on a standard tuning electric guitar
Comment: This is probably music for a Bb instrument which means it's written a whole step higher than it sounds.
Comment: I've read that most of the commercial releases of "Kind of Blue" had the tape speed wrong, meaning that the recording you hear was higher in pitch than how it was performed. Could that have anything to do with the discrepancies you are hearing between the recording and the sheet music?
Comment: @ToddWilcox, thanks, but does it make sense that only the sharpen notes according to the scale are a step higher? all the other notes seem to be ok...
Comment: Here is a link to an article about the tape speed and playback issues with the "Kind of Blue" recording sessions. http://www.stereophile.com/thefifthelement/206fifth/
Comment: @WheatWilliams, cool article! :) but it does not relate to the issue I was discussing, just pick up an instrument and play this part, you'll notice the horror :)
Comment: The use of tied notes in the example is incorrect
Comment: @NeilMeyer, why?
Answer: super old thread, but the answer is yes, it's a Bb flat sheet, you need to play it a step up.
For guitarists who can't be bothered to transpose just detune a tone and boom.  D standard is great anyway.
Answer: option 1 : Your ears are wrong
option 2 : your PDF is wrong
My money is on Option 2,
When I was learning Donna Lee I noticed the part Jaco plays is slightly different than what Charlie Parker played, and even what Parker played is different than what was in my Realbook! Trust your ears! use a different PDF if you have to;) use transcribe software too!!!!!! it will slow the music down to an atomic speed so each of those 16th notes is about 3 seconds long ;)


There is white space at the bottom of my gallery

Question: There is unwanted white space at the bottom of my .gallery-mosaic div. What is causing this and how can I get rid of the white space? ................................................................................................................................................................................................................................................................................................

About Me

Gallery

Services

Contact Me

Tenasi Art

Lorem ipsum dolor sit amet.

About the Photographer

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero eligendi ab quam necessitatibus. Aspernatur temporibus laudantium cum, aliquid libero, perferendis placeat illum aperiam atque doloremque, architecto molestiae voluptatibus beatae quidem ipsam. Fuga, nemo aperiam nostrum sint autem iusto praesentium deleniti rem, soluta eum voluptatibus voluptas fugiat, assumenda necessitatibus labore. Blanditiis!

Tenasi Art Gallery

          See All

    ```

     ```lang-css
        body {
          font-family:'IBM Plex Sans', sans-serif;
          margin:0;
          padding:0;
          box-sizing: border-box;
          width:100%;
        }

        h1,h2,h3,h4,h5,h6 {
          font-weight:bolder;

        }

        h1{
          font-size:55px;
        }
        h2{
          font-size:44px;
        }
        h3{
          font-size:36;
        }
        h4{
          font-size:27;
        }
        h5{
          font-size:20;
        }
        h6{
          font-size:16;
        }

                  /* START GALLERY */

        .gallery-mosaic{
          width:100%;
          max-width:120rem;
          margin:auto;
          padding:0 1.5rem;
          /* background-color: purple; */

        }

        .images{
          /* background-color: green; */
          display:grid;
          grid-template-columns: 1fr 1fr 1fr 1fr;
          grid-template-rows: auto;
          grid-gap:1.5rem;
          grid-template-areas:
          'img-1 img-2 img-3 img-3'
          'img-1 img-4 img-4 img-6'
          'img-7 img-7 img-8 img-6'
        }

        .images a{
          width:100%;
          /* height:25rem; */
          background-position: center;
          background-repeat: no-repeat;
          background-size:cover;
          position:relative;
          display:flex;
          align-items:center;
          justify-content:center;
          text-decoration:none;
          color:rgba(255,255,255,.02);
        }

        .images a ion-icon{
          color:rgba(255,255,255, .6);
          font-size:3rem;
          position:relative;
          z-index:100;
          padding:1rem 3rem;
          border:20px solid rgba(255,255,255, .6);
          border-radius:.4rem;
          opacity:0;
          transition:opacity .5s;

        }

        .images a::before{
          content:'';
          position:absolute;
          height:100%;
          width:100%;
          top:0;
          left:0;
          background-color: rgba(0,0,0,.8);
          opacity:0;
          transition:opacity .5s;
        }

        .images a:hover i, .images a:hover::before{
          opacity:1;
        }

        .img-1{
          grid-area:img-1;
          min-height:51.5rem;
          background-image: url('images/img1.jpg');
        }
        .img-2{
          grid-area:img-2;
          background-image: url('images/img2.jpg');
        }
        .img-3{
          grid-area:img-3;
          background-image: url('images/img3.jpg');
        }
        .img-4{
          grid-area:img-4;
          background-image: url('images/img4.jpg');
        }
        .img-5{
          grid-area:img-5;
          background-image: url('images/img5.jpg');
        }
        .img-6{
          grid-area:img-6;
          min-height:51.5rem;
          background-image: url('images/img6.jpg');
        }
        .img-7{
          grid-area:img-7;
          background-image: url('images/img7.jpg');
        }
        .img-8{
          grid-area:img-8;
          background-image: url('images/img8.jpg');
        }

        .see-all{
          /* background-color: red; */
        }

Answer: It seems this line of code is the cause of that white space:

I removed that line and the white space is gone. You are not using that image in the grid. There is no img-5 in your grid-template-areas.


Web Server Permissions/ownership

Question: I have several websites under /home/user/www/, since I've had to restore all www directory from a backup, most of the files are with root ownership and permissions. Looks something like this:
<code>drwxr-xr-x 34 root     root     4.0K 2009-09-10 14:04 .
-rw-r--r--  1 root     root      127 2009-09-10 10:13 file1
-rwxr-xr-x  1 root     root       23 2009-09-10 10:12 file2
drwxr-xr-x  4 user     user     4.0K 2009-09-10 10:05 ..
drwxr-xr-x 14 root     root     4.0K 2009-09-08 12:08 folder
</code>
My question is, how safe is having them like this? should I change permissions/ownerships to all of them (www-data). I'm the only one who edit those files.
Answer: If you're the person who edits those files, change them to the user you edit with (conventional wisdom would hope that this user isn't root)
If any processes need to write to any files or directories, make sure there is appropiate ownership and permissions on them.
It's that simple.
Comment: +1 true... just don't make the files writable by `www-data` (unless they need to be changed by the web server, of course).
Answer: I like to own them to the user that will edit them, and make them group readable by the Apache user, remove all rights to other users.
Definitly do NOT make them owned by www-data (or writable by www-data), as the web-server (and by implication anything that runs along with the webserver - such as the php interpreter) can then overwrite them.

Web Server Permissions/ownership


Javascript regular expression - get all text after [stuff in here]

Question: I have strings in my program that are like so:
var myStrings = [

"[asdf] thisIsTheText",
"[qwerty]  andSomeMoreText",
"noBracketsSometimes",
"[12345]someText"

];

I want to capture the strings "thisIsTheText", "andSomeMoreText", "noBracketsSometimes", "someText". The pattern of inputs will always be the same, square brackets with something in them (or maybe not) followed by some spaces (again, maybe not), and then the actual text I want.
How can I do this?
Thanks
Comment: [*what have you tried?*](http://mattgemmell.com/2008/12/08/what-have-you-tried/)
Comment: You can use the string .split() method. See here: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
Comment: @zzzzBov Sorry, just had to ask for a free-bee, I've never used regex properly before. Definitely working to understand the answers though, so next time I have an initial attempt. Yes I agree with your sentiment though.
Answer: This should get you started:
/(?:\[[^]]*])?\s*(\w+)/

Answer: One approach:
var actualTextYouWant = originalString.replace(/^\[[^\]]+\]\s*/, '');

This will return a copy of originalString with the initial [...] and whitespace removed.
Comment: Thanks, I just had no starting point. I've been debugging your answer with a regex guide so I understand. I've found that .* can work after matching the first \[
Comment: Probably should be `/^\[[^\]]*\]\s*/` (`*` instead of `+`), but that only matters if OP ends up with a string along the lines of `'[] fooBar'`.
Comment: @zzzzBov: You may be right, but the OP said "square brackets with something in them", so I took that to mean `+`.
Comment: @YoungMoney: `.*` will only work if you know that there will be no other `]`s in the string. (But even if there could be, you can change `[^\]]+` to `.+?` if you prefer. The `?` makes it nongreedy.)


Android: continuously update text in the notification area

Question: As Richard said in this question > Possible to continuously update text in the notification area? , I have the same issue here .
 I want to update text in the notification area .
This question is answered and accepted , but the answer doesn't help me .
It's about to create text as bitmap dynamically and set it to Small Icon of notification .
But as Richard commented ,  the images for setSmallIcon must be predefined in the package.There is no ability to edit them on the fly.
Please kindly show me the right way to do this stuff .
Answer: It's quite simple to update your Notification.
First of all when you create it you must create it with an id.
NotificationManager mNotificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle("Title")
    .setContentText("Text")
    .setSmallIcon(R.drawable.ic_notify);
mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());

Now to update your Notification you only need to notify the new notification with the old id and this will be updated (you don't need to reset the paraneter you don't want to update).
  mNotifyBuilder.setContentText(setContentText("New Text")
  mNotifyBuilder.setSmallIcon(R.drawable.ic_new_notify);
    //this update your notification
    mNotificationManager.notify(
                notifyID,
                mNotifyBuilder.build());

Comment: Thanks for your answer , I've already done with this code . Check this link >> (http://developer.android.com/guide/topics/ui/notifiers/notifications.html ) But it's just update the content text of `Notification Drawer` , what I want is to show text in `Notification Area` and to update this text continuously . Notice - to update in `Notification Area` , not in `Notification Drawer` .
Comment: Ok, but to do so you have to dinamically create an icon with your text and then update it it's the only way to achive what you want...
Comment: As I mentioned in my question `the images for setSmallIcon must be predefined in the package.There is no ability to edit them on the fly`. Isn't it ? Or , is there any way to do it ?
Comment: You could dinamically create a bitmap with text here an example [link] (http://snipplr.com/view/73714/android-draw-text-to-dynamically-sized-bitmap/). Or you can use instead this method [link] (http://stackoverflow.com/questions/4688052/animation-in-notification-bar-cutsom-view) which achive what you want
Comment: Sorry I want to apologize for my istake but `setSmallIcon(int drawableid)` method only work with existing drawable resurces, to you use a bitmap you have to use `setLargeIcon(Bitmap icon)` but if don't make another mistake (now I'm going to check), this icon is show in the notification drawer and not in the notification area
Comment: This tutorial will let you make whatever you want with your notification by creating a custom notification view http://www.framentos.com/en/android-tutorial/2012/02/20/how-to-create-a-custom-notification-on-android/. Choose you what of this solution do you prefer. I hope to have helped you.
Comment: Oh , Custom notification ? That may be helpful , ok , I'm gonna check this out . Thank you by the way :) You help me a lot .
Comment: Ok then let me no of You reach what you achive
Comment: It's doesn't match my need @Corti , it's just replacing custom notification xml to default .No process else changed .When I use this code, the image icon and text are show in notification area just like default.when I update the notification , my notification placed in the whole notification area . I don't want to interrupt user when the program is run in the background . I just want to update the text in notification area !
Comment: @zey I'm sorry but the only way to achive what you want is to use predefinited drawable image.
Comment: Yes @Corti , my app shows the data usage , kilobytes per second in notification .If I use predefined drawable image , i would have to make drawable images count of 1024 . Isn't it ?
Comment: Yes it seem to be the only way to achive what you want. To use a dinamically generated bitmap you must use the Large Icon but it is shown in the drawable.
Answer: I tried to make one but it has one disadvantage is that, it has one empty notification in notification drawer,
public static int when = 0;
private void generateNotification(Context context) {
    Log.i(TAG, "generateNotification");
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(
            this.getApplicationContext(), 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mNotification = new NotificationCompat.Builder(
            this)
            // .setContentTitle("AppName")
            // .setContentText("Message For Notification Drawer")
            // .setSound(soundUri)
            // .setDefaults(Notification.DEFAULT_SOUND)
            // .setVibrate(new long[] { 1000, 1000 })
            // .addAction(R.drawable.ic_launcher, "View", pIntent)
            // .addAction(0, "Remind", pIntent)
            // .setNumber(fCount)
            // .setWhen(when)
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker(Integer.toString(when)) // Set String you want
            .setAutoCancel(true)
            .setContentIntent(pIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // notificationManager.notify(when, mNotification.build());
    notificationManager.notify(1, mNotification.build());
    when++;
}


Why doesn't this TypeScript constant satisfy this interface?

Question: I am trying to implement a function that complies with an interface having both a call signature and a constructor signature. I've seen this is possible in the type declarations here: https://github.com/Microsoft/TypeScript/blob/master/lib/lib.d.ts#L142
I would like to be able to implement something like that myself. Below is my attempt.
class C {
    public x: number;
    constructor(x: number) {
        return { x };
    }
}

interface I {
    new(x: number): C;
    (x: number): C;
}

const x: I = C;

I think it should work given that we could call new x(3) and we would get back a C and similarly, we could call x(3) and get back a C, but there is an error:
Type 'typeof C' is not assignable to type 'I'. Type 'typeof C' provides no match for the signature '(x: number): C'
For convenience, I copied the code in a playground snippet accessible here.
Comment: check it here http://www.typescriptlang.org/play/index.html#src=class%20C%20%7B%0D%0A%20%20%20%20public%20x%3A%20number%3B%0D%0A%20%20%20%20constructor(x%3A%20number)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.x%20%3D%20x%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%0D%0A%7D%0D%0A%0D%0Ainterface%20I%20%7B%0D%0A%20%20%20%20new(x%3A%20number)%3A%20C%2C%0D%0A%20%20%20%20init%3F(x%3A%20number)%3A%20C%0D%0A%7D%0D%0A%0D%0Aconst%20x%3A%20I%20%3D%20C%3B%0D%0A%0D%0Alet%20test%20%3D%20new%20x(3)%3B%0D%0Aconsole.log(test.x)%3B%0D%0A%0D%0A%0D%0A
Comment: @Niladri if I were to guess that works because it's the same as if the init field weren't there.
Comment: I made that function optional because your Class C does not have a definition for that function, if you don't make it optional then it will look for that function also in `x`
Comment: But the definition class C (when transpiled to ES5) satisfies the definitions of both the functions there. You can check the answer to see why it doesn't pass the type checking process :)
Answer: It's expected that I can be called as regular function, while ES6 classes can be called only with new.
Even though C can be called like C(1) with E5 target because it's transpiled to regular function (although explicit { x } return that doesn't use this is antipattern), ES6 classes cannot.
Interfaces like ObjectConstructor (which designates Object built-in) that allow calls both with and without new with same result exist for historical reasons. Besides that this approach isn't applicable to ES6 classes, it isn't considered a good practice in general if a function cannot benefit from new call.
In order to match I type, C should be asserted to it, because classes and void functions are de jure newable in TypeScript, and functions that return values are not:
interface C {
    x: number;
}
const C = <{ new(x: number): C, (x: number): C }><any>function (x: number): C {
  return { x };
}

Comment: Thank you for your answer! I am mostly curious if it would be possible to create a function that would pass the TypeScript type checking process that implements that interface. I got why it can't be done with classes.

Do you know how/if any function could satisfy that interface? Thanks!
Comment: I understand that semantically, a function that does not explicitly use `this` can fulfil both the constructor role and that of an object with a call signature, but as far as I can tell, it won't pass the TypeScript type checking.
Comment: As for type checking, I updated the question. As you can see, you have to fight TS at this point.


didChangeState matchstarted

Question: help ! all,
When "Match started! Expected Player Count:1"
but can not call  "didChangeState"
my code is :
===============================
<code>-(IBAction)play{

    GKMatchRequest *request = [[GKMatchRequest alloc]init];
    request.minPlayers = min;
    request.maxPlayers = max;

    mmvc = [[GKMatchmakerViewController alloc]initWithMatchRequest:request];
    mmvc.matchmakerDelegate =self;
    [self presentModalViewController:mmvc animated:YES];

}

- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match {
    [self dismissModalViewControllerAnimated:YES];
    self.myMatch = match;
    self.myMatch.delegate = self;

    NSLog(@"Match started! Expected Player Count:%d  %@",match.expectedPlayerCount, match.playerIDs);
}

- (void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state
{ NSLog(@"OK!"); }
</code>
====================
it can not give me "OK!"
but i can see "Match started! Expected Player Count:1"
Could you help me?
Answer: I had the same issue and I think the problem was in apple servers.
Because I did nothing and after half an hour past it started to work again.
Without any troubles.

didChangeState matchstarted


AJAX form default values

Question: I'm using an AJAX form to match multiple values of a field to an other entity, to do so i've implemented the example we have in the ajax_example ( https://api.drupal.org/api/examples/ajax_example!ajax_example_graceful_degradation.inc/group/ajax_degradation_example/7 ), see ajax_example_add_more*
It is working great (except i would prefer being able to remove the field i want and not always the last one but we can't have everything).
When i submit the form, my chosen values are saved in database and the page is refreshed. The problem is that the form became empty, i might have multiple names for one fieldset and now i only have one empty textfield.
If we continue with the ajax_example, what i can do is this :
<code>$myValues = variable_get('my_var', '');
</code>
And on this part add a default_value (let's assume that in my $myValues['name'] there is the list of the names)
<code>$form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => $myValues['name'],
);
</code>
In the case where i add only one name, it will work. But if i have multiple name, it will only display the last one.
Do you know how can i do to recreate all the form as it is store in the db ?
Thanks by advance
[EDIT]
Thanks to sareed, i found the way to do so. I'll show the modification to ajax_example_add_more. In the example there is only one fieldset, in my work there is x fieldset so i will add $fieldsetName to know which one :
Change :
<code> if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
</code>
By
<code>     $myValues = variable_get('my_var', '');
     if (empty($form_state[$fieldsetName]['num_names'])) {

          if(isset($myValues[$fieldsetName])) {
            $form_state[$fieldsetName]['num_names'] =
              count($myValues[$fieldsetName]) > 0 ? count($myValues[$fieldsetName]) : 1;
          }
          else {
            $form_state[$fieldsetName]['num_names'] = 1;
          }
      }
</code>
AND
<code>  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
  }
</code>
TO
<code>  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => isset($myValues[$fieldsetName][$i]) ? $myValues[$fieldsetName][$i] : '',
  );
</code>
Answer: Loop through the myValues (only use the foreach if you are not already in a for loop) and use the appropriate array element:
<code>foreach($myValues as $index => $name) {
  $form['names_fieldset']['name'][$index] = array( // Already using $i here. Are you in a for loop?
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => $name, // Or $myValues[$i]['name'] if you are already in a for loop (it looks like you might be).
  );
}
</code>
Depending on the structure of the array you may have to change this a little. If these don't work and you can't figure it out, add a print out of one of your smaller arrays using print_r to your question and we can help.
Comment: Thanks for your answer. However, if myValues is empty i won't even have a textfield shown. One answer would be to do as you say if myValues isn't empty elsedo the 'classic' way. but it would mean create twice the same form with just a little difference
Comment: Actually you can still do a loop. A do-while loop would work well. Or you could still use a for just set your stop var to something like this `$count = $myValues ? count($myValues) : 1;` then your for loop `for ($i = 0; $i < $count; $i++)`.

AJAX form default values


How to convert MM::SS string to time format and then manipulate it

Question: I have the following data frame:
library(tibble)
dat <- structure(list(title = c("Title A", "Title B", "Title C"), tm = c(
  "31:17",
  "30:28", "32:06"
)), row.names = c(NA, -3L), spec = structure(list(
  cols = list(title = structure(list(), class = c(
    "collector_character",
    "collector"
  )), tm = structure(list(), class = c(
    "collector_character",
    "collector"
  ))), default = structure(list(), class = c(
    "collector_guess",
    "collector"
  )), delim = ","
), class = "col_spec"), class = c(
  "spec_tbl_df",
  "tbl_df", "tbl", "data.frame"
))

It looks like this:
> dat
# A tibble: 3 × 2
  title   tm
  <chr>   <chr>
1 Title A 31:17
2 Title B 30:28
3 Title C 32:06

The second column is time but as character. What I want to do is to
add 5 minutes to it for every row; resulting in:
  Title A 36:17
  Title B 35:28
  Title C 37:06

The strategy is to convert tm into numeric form first. But I failed with this step
dat %>%
  mutate(nt = hms::as_hms(as.numeric(tm) + 5))

It gave me:
  title   tm    nt
  <chr>   <chr> <time>
1 Title A 31:17    NA
2 Title B 30:28    NA
3 Title C 32:06    NA

What's the right way to do it?
Answer: Using lubridate -
library(dplyr)
library(lubridate)

dat %>%
  mutate(tm = ms(tm) + minutes(5),
         tm_string = sprintf('%02d:%02d', tm@minute, tm@.Data))

#  title   tm       tm_string
#  <chr>   <Period> <chr>
#1 Title A 36M 17S  36:17
#2 Title B 35M 28S  35:28
#3 Title C 37M 6S   37:06

Comment: How can I convert back to MM::SS format after getting your final result?
Comment: thanks. A side question. How can I convert `36:17` character string to `class = c("hms",  "difftime"), units = "secs"))` as in here:

`tdat <- structure(list(tm = structure(c(108900, 105480, 110280), class = c("hms",
"difftime"), units = "secs")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))`
Comment: in short I prefer `hms::as_hms` approach than `lubridate`.
Because there are more complex manipulation  I need to do easier with `hms::as_hms`


No values in the variables when querying a sesame repository?

Question: I want to use a .nt file as a SESAME repository and query it (also called local federation mode). The program written is as follows.
import java.io.File;
import java.util.List;
import org.openrdf.OpenRDFException;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.model.Value;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryLanguage;
import org.openrdf.repository.Repository;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.nativerdf.NativeStore;

public class QuerySesameLocal {

public static void main(String[] args) {

    try
    {

        File dataDir = new File("/home/aidb/out0.nt");
        Repository repo = new SailRepository(new NativeStore(dataDir));
        repo.initialize();

               RepositoryConnection con = repo.getConnection();
               try {
                  String queryString = "SELECT ?x ?y WHERE { ?x ?p ?y } ";
                  TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);

                  TupleQueryResult result = tupleQuery.evaluate();
                  try {

                      if(result.hasNext())
                      {
                          System.out.println("result present");
                      }

                      System.out.println("checkpoint 1");
                        BindingSet bindingSet = result.next();
                        Value valueOfX = bindingSet.getValue("x");
                        Value valueOfY = bindingSet.getValue("y");

                        System.out.println(valueOfX.toString());
                          System.out.println("checkpoint 2");

                        // do something interesting with the values here...
                  }
                  finally {
                      result.close();
                  }
               }
               finally {
                  con.close();
               }
            }
            catch (OpenRDFException e) {
               // handle exception
            }

}

}
This program does not return any results at all. I tried figuring the bug but could not figure out. Can anyone kindly tell what is wrong with the program ?
Comment: Replace `// handle exception` by `throw new RuntimeException(e);`, then execute the program again, and read/paste the full stack trace of the exception, if any. Ignoring exceptions is the best way to not know what happens. Also, learn to use your debugger. It isn't that hard.
Comment: @harry potter as an aside, I noticed that you have asked a number of questions on SO and have received several answers, but have yet to vote on/accept any of them. I'd encourage you to do so (not just on this question here but on any of your older ones as well). Have a look at this: [what should I do when someone answers?](http://stackoverflow.com/help/someone-answers)
Answer: You can't just initialize a Sesame Native Store with an .nt file (or any other rdf file) like this.
The dataDir argument of the NativeStore constructor is a directory where the native store will create its indexes and store added data - it stores this data in its own internal format by the way, not as .nt files. So you should pass it a directory, not a file (in fact I am a bit surprised that you don't get an error when executing this code).
Once the repository is created and initialized, you have to add the file to it. You do this by opening a RepositoryConnection and using one of its add methods to pass the file to it. See the Sesame user documentation, specifically the section on how to add data to a repository.
Comment: As mentioned I initialized a repository, got a connection and then gave it the .nt file. It worked fine. Thanks a lot!


Cannot receive start command

Question: I have a WAMP install (Apache 2.2.3, PHP 5.2.8) with a working Zend Optimizer.
As soon as I add the php.ini lines for Zend Debugger:
[Zend Debugger]
zend_extension_manager.debug_server_ts="C:\zenddebugger"
zend_debugger.allow_hosts=127.0.0.1/32, 192.168.0.0/16, 192.168.1.0/255
zend_debugger.expose_remotely=always

and restart apache, I get a blank page and the following entry in the apache error log.
[Zend Debugger] Cannot receive start command
[Zend Debugger] Cannot send message

Now the incredible thing is that I had it working this morning and now, after reinstalling WAMP there is no way I can get it work again. php.ini is exactly the same as it was before.
I would be extremely glad to get help, I'm trying to get a working server environment going for over a month, can you believe that? I tried XAMPP, Zend Server and now WAMP and I'm going crazy slowly but surely.
Answer: A workaround I just found is to use 127.0.0.1 instead of localhost. Maybe it's just something with the hosts (hosts.ini) file. But that has been ok so far.
It seems that the Debugger doesn't get the new way Windows 7 is resolving localhost, when I add an entry to the hosts file, I can partly debug. Still, my errand has not come to and end since everything is unstable.
Answer: This worked for me on my machine to, also running on Windows 7.  Running Apache 2.2 and PHP 5.2.12

Cannot receive start command


CSS horizontal centering of a fixed div?

Question: #menu {
    position: fixed;
    width: 800px;
    background: rgb(255, 255, 255); /* The Fallback */
    background: rgba(255, 255, 255, 0.8);
    margin-top: 30px;
}

I know this question is a million times out there, however I can't find a solution to my case.
I've got a div, which should be fixed on the screen, even if the page is scrolled it should always stay CENTERED in the middle of the screen!
The div should have 500px width, should be 30px away from the top (margin-top), should be horizontally centered in the middle of the page for all browser sizes and should not move when scrolling the rest of the page.
Is that possible?
Comment: See also http://stackoverflow.com/questions/17069435/center-fixed-div-with-dynamic-width-css
Answer: The answers here are outdated. Now you can easily use a CSS3 transform without hardcoding a margin. This works on all elements, including elements with no width or dynamic width.
Horizontal center:
left: 50%;
transform: translateX(-50%);

Vertical center:
top: 50%;
transform: translateY(-50%);

Both horizontal and vertical:
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

Compatibility is not an issue: http://caniuse.com/#feat=transforms2d
Comment: Yes, Chrome incorrectly blurs content that is transformed. Text is also blurred. But this is the only solution to have a fixed element centered without hardcoding and using wrapper elements. If you don't care about pointer events of the background, you can achieve same effect with a full screen wrapper and flexbox, or @salomvary's solution below.
Comment: This makes a blur effects in box shadow in content elements.
Comment: This work fine but the element I'm trying to center already has an animation, this animate the `translateX(-50%)`...
Comment: This precludes you from having a `fixed` position child.
Comment: I implemented your answer, with a draggable element, and a problem came up. I posted the question here: http://stackoverflow.com/questions/34073485/center-a-fixed-draggable-div
Comment: This seems to set a max width on the centered element that wasn't there before. I'm using this to center a fixed bootstrap panel, and it's forcing the width down smaller than before. Is there a way to overcome this? The content is dynamic (action buttons for my form), so I can't hardcode the width.
Comment: For newcomers, just note that `transform` is not a cheat code. It can cause all sorts of havoc because it creates a new stacking context. However, so does `position: fixed`, so it seems fine as long as there aren't any visual side effects like text blurriness in the browsers you care about.
Answer: left: 50%;
margin-left: -400px; /* Half of the width */

Comment: Completely agree - this is **NOT** a solution! *Never* hard code something in this manner. -1
Comment: I've voted this down NOT because it was a bad answer for its day - it was a good answer, but because it no longer is, and the next-highest answer needs all the help it can get to be seen as the best answer NOW. Quentin: I think it would be a good idea to edit in a comment to that effect in the answer itself - I'd then reverse my down vote.
Comment: @Bahodir: Are you sure?  It looks right to me on resize.  I think this  `-400` is due to the width of the div being set to `800`.
Comment: @PrestonBadeer — Like the one that the question is asking about?
Comment: @Quentin, this holds no advantage over using a transform and has limited usage. A transform would work better and is a better practice. In a responsive age it's bad practice to teach people to hard code these values. I agree that in 2010 this was the correct answer, it just isn't anymore.
Comment: @NateI — This answer is from over half a decade ago, browser support for better alternatives was terrible.
Comment: @Quentin Regardless, new visitors should see that this is **not** the way to do things now. PS - you responded to this in February defending it - that's one motivating factor to me downvoting and informing users that this is an absolutely horrible way to accomplish this task.
Comment: works when width defined but if i use padding to adjust the text given by user then???
Comment: What if you don't know the dimensions at design time?
Comment: @PeterMoore — Then you have a different problem to the one being asked about here. You might want to look at some of the other questions here though.
Answer: If using inline-blocks is an option I would recommend this approach:
.container {
    /* fixed position a zero-height full width container */
    position: fixed;
    top: 0; /* or whatever position is desired */
    left: 0;
    right: 0;
    height: 0;
    /* center all inline content */
    text-align: center;
}

.container > div {
    /* make the block inline */
    display: inline-block;
    /* reset container's center alignment */
    text-align: left;
}

I wrote a short post on this here: http://salomvary.github.com/position-fixed-horizontally-centered.html
Comment: 10x, this worked great for me w/o having to hard-code any numbers for `width` or something -- unlike @Quentins answer
Answer: Edit September 2016: Although it's nice to still get an occasional up-vote for this, because the world has moved on, I'd now go with the answer that uses transform (and which has a ton of upvotes). I wouldn't do it this way any more.
Another way not to have to calculate a margin or need a sub-container:
#menu {
    position: fixed;   /* Take it out of the flow of the document */
    left: 0;           /* Left edge at left for now */
    right: 0;          /* Right edge at right for now, so full width */
    top: 30px;         /* Move it down from top of window */
    width: 500px;      /* Give it the desired width */
    margin: auto;      /* Center it */
    max-width: 100%;   /* Make it fit window if under 500px */
    z-index: 10000;    /* Whatever needed to force to front (1 might do) */
}

Comment: @Joey What does the bottom:0 do? ie why is it needed? (It's some time since I looked at this!)
Comment: `bottom:0` would ensure the menu is always vertically centered, but I see now that's not what the OP asked for. :)
Comment: I tried to use this in a different context byt figured out it doesn't center in FF if the elements height is higher than the window(viewport) height
Comment: Because the world has moved on, I'd now go with the answer that uses transform. (I made this comment before, referencing the name that answerer used - but they changed that name so my comment no longer made sense and I deleted it - just search on this page for transform instead.)
Answer: It is possible to horisontally center the div this way:
html:

content

css:
.container {
    left: 0;
    right: 0;
    bottom: 0; /* or top: 0, or any needed value */
    position: fixed;
    z-index: 1000; /* or even higher to prevent guarantee overlapping */
}

.inner {
    max-width: 600px; /* just for example */
    margin: 0 auto;
}

Using this way you will have always your inner block centered, in addition it can be easily turned to true responsive (in the example it will be just fluid on smaller screens), therefore no limitation in as in the question example and in the chosen answer.
Comment: exactly what i was looking for: a centered block that is fixed
Answer: Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:

    content

The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.
#outer {
  position: fixed;
  left: 50%;          // % of window
}
#inner {
  position: relative;
  left: -50%;         // % of outer (which auto-matches inner width)
}

This approach is similar to Quentin's, but inner can be of variable size.
Answer: ... or you can wrap you menu div in another:

#wrapper{
         width:800px;
         background: rgba(255, 255, 255, 0.8);
         margin:30px auto;
         border:1px solid red;
    }

    #menu{
        position:fixed;
        border:1px solid green;
        width:300px;
        height:30px;
    }

Answer: The best way to do this is have the fixed div and then have a div inside of it that you center. This is most useful when you want a fixed container so the fixed elements do not go outside of the containers width.

A notification that shows up

.fixed {
 position: fixed;
 top: 32px;
 left: 0;
 right: 0;
 pointer-events: none; // so this div does block clicks on content underneath it
}

.container {
 max-width: 1200px;
 width: 100%;
 margin: 0 auto;
}

.toast {
 pointer-events: all; // so you can click on the toast to close it
}

Answer: Here's a flexbox solution when using a full screen wrapper div. justify-content centers it's child div horizontally and align-items centers it vertically.

 //... content

.full-screen-wrapper {
  position: fixed;
  display: flex;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  top: 0;
  align-items: center;
}

.center {
  // your styles
}

Comment: The problem with this solution is that it makes anything in the whitespace (left and right of the div) unclickable
Comment: Good point @Burawi - thanks..
Answer: div {
   left: calc((100vw - 100%) / 2);
}

Comment: Your answer could be improved by adding more information on what the code does and how it helps the OP.


can i say that $x=y$ if both have the same terms?

Question: If I got that,
$$x=\dfrac{y^3+1}{2}\textrm{ and }y=\dfrac{x^3+1}{2}$$
then can I say that $x=y$ ? it looks correct but I'm not sure why.
Thanks.
Comment: No, it's not true. If that condition you state holds, the only thing you can conclude is that $x$ and $y$ are roots of certain polynomial of degree $9$ (the one obtained by substituting $x$ in $y$ or viceversa).
Comment: That's an easy rookie mistake to make,but it's not true, To see why easily, just draw the graphs of the 2 functions and you'll see how different they are.
Comment: They are not equal, just think that they are inverse function (very few function are inverse of themselves).
Answer: Yes, you can certainly say so (contrary to what others have answered), provided you're interested only in real solutions. Not in general, but in this particular case, I mean.
If this system had a solution $(a,b)$ with $a\ne b$, we would have
$$
2a=b^3+1,\quad 2b=a^3+1
$$
from which we get $2(a-b)=b^3-a^3=(b-a)(b^2+ab+a^2)$ and, since $a\ne b$,
$$
a^2+ab+b^2=-2
$$
that has no real solution, a contradiction.
So the intersections of these curves can also be computed as the solutions of
$$
\begin{cases}
2y=x^3+1\\
y=x
\end{cases}
$$
and the resolvent equation is $x^3-2x+1=0$, which factors as $(x-1)(x^2+x-1)=0$ giving
$$
x=1
\qquad\text{or}\qquad
x=\frac{-1-\sqrt{5}}{2}
\qquad\text{or}\qquad
x=\frac{-1+\sqrt{5}}{2}
$$

More generally, if we have equations $y=f(x)$ and $x=f(y)$, where $f$ is a polynomial, we can certainly write
$$
y-x=f(x)-f(y)
$$
and, since $f(x)-f(y)$, as a polynomial in two variables, is divisible by $x-y$, we have
$$
x=y \qquad\text{or}\qquad \frac{f(x)-f(y)}{x-y}=-1
$$
where the fraction denotes the quotient polynomial.
This can be done unless the equation $y-x=f(x)-f(y)$ is trivial, that is, when $f(x)-f(y)=y-x$ as polynomials. This is exactly the case when $f(z)=k-z$, which is the one mentioned by Hagen von Eltzen.
Of course things are more complicated if non polynomial functions are involved.
Comment: Thanks for giving this answer (which was contrary to several incorrect answers).  I'm not sure I agree with your argument about polynomials, though -- for example, if $y=1-x^2$ and $x=1-y^2$, this doesn't imply that $x=y$, even though $f(x)-f(y)=y^2-x^2\ne y-x$.
Comment: @user84413 No: in this case $(f(x)-f(y))/(x-y)=-y-x$ and the equation $-y-x=-1$ is satisfied also for $x+y=1$. So in this case also the "or" branch must be followed, which doesn't happen with the problem in the question.
Comment: Thanks for your reply, and I'm sorry for my misunderstanding; I didn't interpret what you were saying about polynomials correctly.
Answer: ![you can solve a system of equation and find the solution(s) . or ,you can put x from 1st relation into 2nd relation ,to find roots then you have x,y .the picture may help you ][2]
or ,you can put x from 1st relation into 2nd relation ,to find roots then you have x,y .the picture may help you .try this
Answer: No you can't. You have $x=f(y)$ ans $y=f(x)$ for some function $f$. If you had (simpler) $x=10-y$ and $y=10-x$ you could not say $x0y$ either. After all it might be that $x=3$ and $y=7$.
(At least $x$ (and $y$) are fixed points of the iterated function $x\mapsto f(f(x))$.)
Answer: Rewriting the expression gives:
$$
x=\frac{Y^3+1}{2} \Rightarrow \\
Y = \left\{
\begin{array}{rc}
\sqrt[3]{2x-1} & \mbox{for } x \ge 1/2 \\
-\sqrt[3]{1-2x} & \mbox{for } x < 1/2
\end{array}
\right.
$$
Compare this with
$$
y=\frac{x^3+1}{2}
$$
which should be different in general.

The plot indicates three common points, which have to lie on the identity line.
Answer: No, you cannot. Solve for $x$ and $y$ for both functions. When doing so, you'll get $y=\sqrt [3]{2x-1}$ which does not equal ${x^3 + 1}\over 2$. And $x=\sqrt [3] {2y-1}$ which does not equal ${y^3 + 1}\over 2$.
Answer: Yes, you can say this, and this applies more generally to any increasing function:
If $f$ is an increasing function and $f(x)=y$ and $f(y)=x$, then $x=y$.
$\underline{Pf}$ Suppose instead that $x\ne y$, so WLOG we can assume that $x<y$.
$\;\;\;\;$Then $f(x)<f(y)\implies y<x$, which gives a contradiction; so $x=y$.
Answer: Yes the graphs cut along $ x=y $ with real roots/ intersections.