erro com bootstrap

Question: Estou tendo um erro com o bootstrap, o carousel está funcionando certinho mas a imagem que deveria pegar todo o espaçamento do box está minimizada e o hover não está centralizando na imagem, sem o link do bootstrap funciona tudo certo mas eu preciso atualizar esse código pra poder utilizar o link e não estou conseguindo, alguém pode me dar uma idéia do que fazer?
assim que deveria ficar

.box14{position:relative}
.box15,.box17,.box18{box-shadow:0 0 5px #7e7d7d;text-align:center}
.box14:before{content:"";width:100%;height:100%;background:rgba(0,0,0,.5);position:absolute;top:0;left:0;opacity:0;transition:all .35s ease 0s}
.box14:hover:before{opacity:1}
.box14 img{width:100%;height:auto}
.box14 .box-content{width:90%;height:90%;position:absolute;top:5%;left:5%}
.box14 .box-content:after,.box14 .box-content:before{content:"";position:absolute;top:0;left:0;bottom:0;right:0;opacity:0;transition:all .7s ease 0s}
.box14 .box-content:before{border-bottom:1px solid rgba(255,255,255,.5);border-top:1px solid rgba(255,255,255,.5);transform:scale(0,1);transform-origin:0 0 0}
.box14 .box-content:after{border-left:1px solid rgba(255,255,255,.5);border-right:1px solid rgba(255,255,255,.5);transform:scale(1,0);transform-origin:100% 0 0}
.box14:hover .box-content:after,.box14:hover .box-content:before{opacity:1;transform:scale(1);transition-delay:.15s}
.box14 .title{font-size:21px;font-weight:700;color:#fff;margin:15px 0;opacity:0;transform:translate3d(0,-50px,0);transition:transform .5s ease 0s}
.box14:hover .title{opacity:1;transform:translate3d(0,0,0)}
.box14 .post{font-size:14px;color:#fff;padding:10px;background:#a2c270;opacity:0;border-radius:0 19px;transform:translate3d(0,-50px,0);transition:all .7s ease 0s}
.box14 .icon,.box15 .icon{padding:0;list-style:none}
.box14:hover .post{opacity:1;transform:translate3d(0,0,0);transition-delay:.15s}
.box14 .icon{width:100%;margin:0;position:absolute;bottom:-10px;left:0;opacity:0;z-index:1;transition:all .7s ease 0s}
.box14:hover .icon{bottom:20px;opacity:1;transition-delay:.15s}
.box14 .icon li a{display:block;width:40px;height:40px;line-height:40px;border:1px solid #fff;border-radius:0 16px;font-size:14px;color:#fff;margin-right:5px;transition:all .4s ease 0s}
.box14 .icon li a:hover{background:#a2c270;border-color:#a2c270}
@media only screen and (max-width:990px){.box14{margin-bottom:30px}
}

.icon-cards {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 300px;
  margin: 0;
  -webkit-perspective: 10000px;
          perspective: 10000px;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
}
.icon-cards__content {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
          transform-style: preserve-3d;
  -webkit-transform: translateZ(-182px) rotateY(0);
          transform: translateZ(-182px) rotateY(0);
  -webkit-animation: carousel 15s infinite cubic-bezier(0.005, 0.625, 0.365, 0.840) forwards;
          animation: carousel 15s infinite cubic-bezier(0.005, 0.625, 0.365, 0.840) forwards;
}
.icon-cards__item {
  border: 1px solid #a2c270;
  position: absolute;
  top: 0;
  left: 0;
  width: 400px;
  height: 300px;
}
.icon-cards__item:nth-child(1) {
  background:linear-gradient(45deg, hsla(83, 40%, 60%, 0.60), hsla(162, 33%, 61%, 0.60))!important;
  -webkit-transform: rotateY(0) translateZ(300px);
          transform: rotateY(0) translateZ(300px);
}
.icon-cards__item:nth-child(2) {
  background:linear-gradient(45deg, hsla(83, 40%, 60%, 0.60), hsla(162, 33%, 61%, 0.60))!important;
  -webkit-transform: rotateY(120deg) translateZ(300px);
          transform: rotateY(120deg) translateZ(300px);
}
.icon-cards__item:nth-child(3) {
  background:linear-gradient(45deg, hsla(83, 40%, 60%, 0.60), hsla(162, 33%, 61%, 0.60))!important;
  -webkit-transform: rotateY(240deg) translateZ(300px);
          transform: rotateY(240deg) translateZ(300px);
}

@-webkit-keyframes carousel {
  0%,  17.5% {
    -webkit-transform: translateZ(-182px) rotateY(0);
            transform: translateZ(-182px) rotateY(0);
  }
  27.5%, 45% {
    -webkit-transform: translateZ(-182px) rotateY(-120deg);
            transform: translateZ(-182px) rotateY(-120deg);
  }
  55%, 72.5% {
    -webkit-transform: translateZ(-182px) rotateY(-240deg);
            transform: translateZ(-182px) rotateY(-240deg);
  }
  82.5%, 100% {
    -webkit-transform: translateZ(-182px) rotateY(-360deg);
            transform: translateZ(-182px) rotateY(-360deg);
  }
}

@keyframes carousel {
  0%,  17.5% {
    -webkit-transform: translateZ(-182px) rotateY(0);
            transform: translateZ(-182px) rotateY(0);
  }
  27.5%, 45% {
    -webkit-transform: translateZ(-182px) rotateY(-120deg);
            transform: translateZ(-182px) rotateY(-120deg);
  }
  55%, 72.5% {
    -webkit-transform: translateZ(-182px) rotateY(-240deg);
            transform: translateZ(-182px) rotateY(-240deg);
  }
  82.5%, 100% {
    -webkit-transform: translateZ(-182px) rotateY(-360deg);
            transform: translateZ(-182px) rotateY(-360deg);
  }
}
<!DOCTYPE html>

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1″>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8″>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="css/estilo.css" rel="stylesheet">

Lorem, ipsum.

                Web Designer

Lorem, ipsum.

                Web Designer

Lorem, ipsum.

                Web Designer

Answer: O que está deixando as imagens menores são as classes col-md-4 e col-sm-6, o que, pela estrutura das divs, me parecem desnecessárias.
Outra classe que está bugando a div escura no hover é a mt-5, que aplica uma margem superior extra ao elemento fazendo ele ficar fora da div.
Retire essas classes e tudo fica no lugar:

.box14{position:relative}
.box15,.box17,.box18{box-shadow:0 0 5px #7e7d7d;text-align:center}
.box14:before{content:"";width:100%;height:100%;background:rgba(0,0,0,.5);position:absolute;top:0;left:0;opacity:0;transition:all .35s ease 0s}
.box14:hover:before{opacity:1}
.box14 img{width:100%;height:auto}
.box14 .box-content{width:90%;height:90%;position:absolute;top:5%;left:5%}
.box14 .box-content:after,.box14 .box-content:before{content:"";position:absolute;top:0;left:0;bottom:0;right:0;opacity:0;transition:all .7s ease 0s}
.box14 .box-content:before{border-bottom:1px solid rgba(255,255,255,.5);border-top:1px solid rgba(255,255,255,.5);transform:scale(0,1);transform-origin:0 0 0}
.box14 .box-content:after{border-left:1px solid rgba(255,255,255,.5);border-right:1px solid rgba(255,255,255,.5);transform:scale(1,0);transform-origin:100% 0 0}
.box14:hover .box-content:after,.box14:hover .box-content:before{opacity:1;transform:scale(1);transition-delay:.15s}
.box14 .title{font-size:21px;font-weight:700;color:#fff;margin:15px 0;opacity:0;transform:translate3d(0,-50px,0);transition:transform .5s ease 0s}
.box14:hover .title{opacity:1;transform:translate3d(0,0,0)}
.box14 .post{font-size:14px;color:#fff;padding:10px;background:#a2c270;opacity:0;border-radius:0 19px;transform:translate3d(0,-50px,0);transition:all .7s ease 0s}
.box14 .icon,.box15 .icon{padding:0;list-style:none}
.box14:hover .post{opacity:1;transform:translate3d(0,0,0);transition-delay:.15s}
.box14 .icon{width:100%;margin:0;position:absolute;bottom:-10px;left:0;opacity:0;z-index:1;transition:all .7s ease 0s}
.box14:hover .icon{bottom:20px;opacity:1;transition-delay:.15s}
.box14 .icon li a{display:block;width:40px;height:40px;line-height:40px;border:1px solid #fff;border-radius:0 16px;font-size:14px;color:#fff;margin-right:5px;transition:all .4s ease 0s}
.box14 .icon li a:hover{background:#a2c270;border-color:#a2c270}
@media only screen and (max-width:990px){.box14{margin-bottom:30px}
}

.icon-cards {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 300px;
  margin: 0;
  -webkit-perspective: 10000px;
          perspective: 10000px;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
}
.icon-cards__content {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
          transform-style: preserve-3d;
  -webkit-transform: translateZ(-182px) rotateY(0);
          transform: translateZ(-182px) rotateY(0);
  -webkit-animation: carousel 15s infinite cubic-bezier(0.005, 0.625, 0.365, 0.840) forwards;
          animation: carousel 15s infinite cubic-bezier(0.005, 0.625, 0.365, 0.840) forwards;
}
.icon-cards__item {
  border: 1px solid #a2c270;
  position: absolute;
  top: 0;
  left: 0;
  width: 400px;
  height: 300px;
}
.icon-cards__item:nth-child(1) {
  background:linear-gradient(45deg, hsla(83, 40%, 60%, 0.60), hsla(162, 33%, 61%, 0.60))!important;
  -webkit-transform: rotateY(0) translateZ(300px);
          transform: rotateY(0) translateZ(300px);
}
.icon-cards__item:nth-child(2) {
  background:linear-gradient(45deg, hsla(83, 40%, 60%, 0.60), hsla(162, 33%, 61%, 0.60))!important;
  -webkit-transform: rotateY(120deg) translateZ(300px);
          transform: rotateY(120deg) translateZ(300px);
}
.icon-cards__item:nth-child(3) {
  background:linear-gradient(45deg, hsla(83, 40%, 60%, 0.60), hsla(162, 33%, 61%, 0.60))!important;
  -webkit-transform: rotateY(240deg) translateZ(300px);
          transform: rotateY(240deg) translateZ(300px);
}

@-webkit-keyframes carousel {
  0%,  17.5% {
    -webkit-transform: translateZ(-182px) rotateY(0);
            transform: translateZ(-182px) rotateY(0);
  }
  27.5%, 45% {
    -webkit-transform: translateZ(-182px) rotateY(-120deg);
            transform: translateZ(-182px) rotateY(-120deg);
  }
  55%, 72.5% {
    -webkit-transform: translateZ(-182px) rotateY(-240deg);
            transform: translateZ(-182px) rotateY(-240deg);
  }
  82.5%, 100% {
    -webkit-transform: translateZ(-182px) rotateY(-360deg);
            transform: translateZ(-182px) rotateY(-360deg);
  }
}

@keyframes carousel {
  0%,  17.5% {
    -webkit-transform: translateZ(-182px) rotateY(0);
            transform: translateZ(-182px) rotateY(0);
  }
  27.5%, 45% {
    -webkit-transform: translateZ(-182px) rotateY(-120deg);
            transform: translateZ(-182px) rotateY(-120deg);
  }
  55%, 72.5% {
    -webkit-transform: translateZ(-182px) rotateY(-240deg);
            transform: translateZ(-182px) rotateY(-240deg);
  }
  82.5%, 100% {
    -webkit-transform: translateZ(-182px) rotateY(-360deg);
            transform: translateZ(-182px) rotateY(-360deg);
  }
}
<!DOCTYPE html>

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1″>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8″>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="css/estilo.css" rel="stylesheet">

Lorem, ipsum.

                Web Designer

Lorem, ipsum.

                Web Designer

Lorem, ipsum.

                Web Designer

erro com bootstrap


How to delete rows if cells abide by if conditions

Question: I have created a macro to delete entire row if a range of cells of the row abides by an if condition. The problem so far is that the macro is actually not deleting all the rows that should be deleted and I have no idea why. I have tested numerous times but no result. I should mention that the range is copy pasted from another worksheet, but I have already made this part work. So, I dont think there is a problem there. I am providing a screenshot of my excel sheet and the code below.

    Sub a()

Dim lastrow3 As Long

    Sheets.Add.Name = "Report_Copy"
    Worksheets("Report").Cells.Copy
    With Worksheets("Report_Copy")
    .Cells.PasteSpecial xlValues
    .Cells.PasteSpecial xlFormats
    End With
    With Worksheets("Report_Copy").UsedRange
        .Value = .Value
    End With

    Dim i As Long

With Sheets("Report_Copy")
    lastrow3 = .Cells(.Rows.Count, "K").End(xlUp).Row

    For i = lastrow3 To 25 Step -1
        Set cell = .Range("L" & i)
        If WorksheetFunction.CountIf(.Range(cell, cell.Offset(0, 9)), "<0.5") = 10 Then
            cell.EntireRow.Delete
        End If
    Next i
End With

End Sub

Answer: When deleting rows you need to loop backwards.
Use the loop below and replace it with your last loop:
Dim i As Long

With Sheets("Report_Copy")
    lastrow3 = .Cells(.Rows.Count, "K").End(xlUp).Row

    For i = lastrow3 To 25 Step -1
        Set cell = .Range("L" & i)
        If cell.Value < 0.5 And cell.Offset(0, 1).Value < 0.5 And cell.Offset(0, 2).Value < 0.5 And cell.Offset(0, 3).Value < 0.5 And cell.Offset(0, 4).Value < 0.5 And cell.Offset(0, 5).Value < 0.5 And cell.Offset(0, 6).Value < 0.5 And cell.Offset(0, 7).Value < 0.5 And cell.Offset(0, 8).Value < 0.5 And cell.Offset(0, 9).Value < 0.5 Then
            cell.EntireRow.Delete
        End If
    Next i
End With

Note: you can repalce your multiple cells condition with the same critera <0.5 by using the CountIf function:
If WorksheetFunction.CountIf(.Range(cell, cell.Offset(0, 9)), "<0.5") = 10 Then

Comment: @PericlesFaliagas you didn't copy my updated code, without the `.Value` at the end
Comment: It gives an error on Set cell = .Range("L" & i).Value saying type mismatch
Comment: Unfortunately it still gives the error in the same line... I am updating the code as it is after the changes...
Comment: @PericlesFaliagas how did you define `cell` ? is it `Range` ?
Comment: Still it says there is a type mismatch in the same line.. I havent defined cell
Comment: @PericlesFaliagas use `Option Explicit`at the top of your code, this will help you find a lot of errors, Also define all your variables and objects
Comment: The only variable I have defined is the lastrow3. Which other should I define??
Comment: @PericlesFaliagas `Dim lastrow3 As long, i As Long, cell As Range`
Comment: Buddy thank you very much for all the help!! You were right ! Dim cell As Range and is perfect now! Thank you!!
Answer: When delete row index move to the next element in loop. If two rows meet the requirements lie next to each other, the bottom row will not be removed.
Use for next loop. Example removed all rows with value 1 in range(A1:A4):
Public Sub test()
Dim cell As Range
For i = 1 To Range("A1:A4").Rows.Count
 Set cell = Range("a" & i)
    If cell = 1 Then
    cell.EntireRow.Delete
    i = i - 1
End If
Next i
End Sub


PAM won't authenticate with mysql (make_scrambled_password deprecated)

Question: I have spent some time searching for this and it seems I'm the only one having problem with PAM not authenticating through mysql due to current updates so I thought I will post my problem here and if I find solution I will post here as well for others to follow.
In short - I'm running postfix with saslauthd and dovecot. Both are authenticating through pam employing mysql as credentials source.
Everything was working fine until today update - I can't connect to mail server any more and here is what I see in logs:
<code>PAM unable to dlopen(/usr/lib/security/pam_mysql.so): /usr/lib/security/pam_mysql.so:     undefined symbol: make_scrambled_password
PAM adding faulty module: /usr/lib/security/pam_mysql.so
DEBUG: auth_pam: pam_authenticate failed: Module is unknown
do_auth         : auth failure: [user=xxxx] [service=smtp] [realm=xxxx] [mech=pam] [reason=PAM auth error]
</code>
So I may be wrong but to my understanding pam_mysql.so is using deprecated make_scrambled_password that is not supported by mysql any more.
I don't know what the solution would be and will appreciate if anybody can advice.

I checked source code on project page and can see deprecated function is being used. So this seems to be a bug in pam_mysql and update will be needed ([bug reported on pam_mysql sourceforge page][1] as well as on arch community bug tracker (https://bugs.archlinux.org/task/39083?project=5&pagenum=1))

I have seen some workaround patches around internet (https://lists.fedoraproject.org/pipermail/scm-commits/2011-June/613231.html) however I'm not sure if that's suitable for production environment.
It seems I will have to patch it myself. I will post patch here for others to use.
Many thanks,
Greg
Comment: Did you update your system? It seems one of the shared libraries that pam_mysql.so uses no longer has the symbol (aka function) "make_scrambled_password". Perhaps reverting to a previous version of that library will fix the problem. Or updating your pam_mysql.so to a newer version (preferable). If this is part of distro packages (and not hand-compiled) then all dependencies should match.
Comment: Thanks Fred. It seems this is other way around - pam_mysql is using make_scrambled_password which was deprecated a while ago and was now ruled out from mysql. I raised bug report with pam_mysql developers (hopefully they are still around) so this can be patched at source.
Answer: Support for pam_mysql is now dropped due to project being dead for almost 6 years. Solution will be to migrate and use another pam backend.
I was using cyrus sasl - that was now uninstalled and replaced by dovecot that provides smtpd authentication backend recognized by postfix. I configured dovecot to use sql natively (without pam in the middle).


Facebook login having issue (php sdk)

Question: I am using php sdk for facebook login on my website. But i am facing a very stupid problem, when i click on connect facebook button it redirects me to facebook website to enter email and password but after redirecting back to my website it creates infinite loop which does not end.
This is my code:
require('facebook/facebook.php');

  $facebook = new Facebook(array(
    'appId'  => 'app_id',
    'secret' => 'app_secret',
  ));

  // See if there is a user from a cookie

      $user = $facebook->getUser();
      //echo $user;
      if ($user) {
        try {
          // Proceed knowing you have a logged in user who's authenticated.
          $user_profile = $facebook->api('/me');
        } catch (FacebookApiException $e) {
          echo '
'.htmlspecialchars(print_r($e, true)).'
';
          $user = null;
        }
      }

print"
";
  print_r($user_profile);
  print"
";

You can test the it on this url:
http://www.conceptbeans.co.uk/cb/projects/xedact/login.php

I will be appreciable any help from your side.
Thanks
Zain
Comment: What do you expect from the URL? I get back my FB profile ID.
Comment: You are saying that you log in successfully from this url?
Comment: I just saying that when i connect to facebook on my website so it creates a redirect loop and i give you a url for testing, Also i want what is the issue? That's it
Answer: your syntax isnt correct when you define your new facebook object, you have a , at the end of array. should be:
$facebook = new Facebook(array(
    'appId'  => 'app_id',
    'secret' => 'app_secret'
  ));

Comment: I cannot get the user after redirecting back to my website, also it is  creating redirecting loop. I checked the syntax error which you point out but it still same
Comment: are you using the latest version of the sdk? [link](https://github.com/facebook/facebook-php-sdk)
Comment: Yes i am using the latest version of sdk, downloaded it from github
Comment: check your app settings on facebook, [check this image](http://4de08c6af39c20343f39-fec7c301d7eca18188203e783b444e60.r36.cf1.rackcdn.com/2011/04/app_setting.jpg)

Facebook login having issue (php sdk)


I need help to compute the RMSE of lasso model

Question: I was following this other example on how to find lasso regression in r . The image posted below is the image of the codes. I need help with find the RMSE
Comment: Hi, welcome to the site! We can't see your image, could you try again? But regardless, the only hard part in computing RMSE is getting extracting the predictions. Once you've got those, RMSE is simply, in python notation, $\texttt{np.sqrt(np.mean(np.square(pred-y)))}$.
Comment: `sqrt(mean((y-predictions)^2))` is the R syntax. If you need help extracting the predictions from the model, a software site like the original Stack Overflow could be a valuable resource.
Answer: Let's break down the term.
ROOT: Take the square root.
MEAN: Add up a bunch of numbers, and divide by the number of values you added up.
SQUARED: Multiple a number by itself (square the number).
ERROR: The error is by how much you missed the true value, so the difference between truth and predictions. (You can subtract in either order, since the value is squared.)
Consequently, root mean squared error, where $\hat y_i$ is the $i^{th}$ prediction and $n$ is the sample size, is:
$$
RMSE=\sqrt{
\dfrac{
\sum_{i=1}^n\left(
y_i - \hat y_i
\right)^2
}{
n
}
}
$$
(If this reminds you of standard deviation, there is a reason the formulas look so similar. RMSE relates to the estimated standard deviation of a regression error term.)
Once you extract predictions from the model, just apply this formula.
Some sources will divide by $n-1$, $n-2$ or $n-p$. These all relate to other ways of estimating the regression error standard deviation and have their advantages. Without context to clarify the exact formula, though, I would default to dividing by the sample size $n$ (particularly for a LASSO model).


how to decompress .tar.bz2 in memory with python

Question: How to decompress *.bz2 file in memory with python?
The bz2 file comes from a csv file.
I use the code below to decompress it in memory, it works, but it brings some dirty data such as filename of the csv file and author name of it, is there any other better way to handle it?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import StringIO
import bz2

with open("/app/tmp/res_test.tar.bz2", "rb") as f:
    content = f.read()

    compressedFile = StringIO.StringIO(content)
    decompressedFile = bz2.decompress(compressedFile.buf)
    compressedFile.seek(0)

    with open("/app/tmp/decompress_test", 'w') as outfile:
        outfile.write(decompressedFile)

I found this question, it is in gzip, however my data is in bz2 format, I try to do as instructed in it, but it seems that bz2 could not handle it in this way.
Edit:
No matter the answer of @metatoaster or the code above, both of them will bring some more dirty data into the final decompressed file.
For example: my original data is attached below and in csv format with the name res_test.csv:

Then I cd into the directory where the file is in and compress it with tar -cjf res_test.tar.bz2 res_test.csv and get the compressed file res_test.tar.bz2, this file could simulate the bz2 data that I will get from internet and I wish to decompress it in memory without cache it into disk first, but what I get is data below and contains too much dirty data:

The data is still there, but submerged in noise, does it possible to decompress it into pure data just the same as the original data instead of decompress it and extract real data from too much noise?
Answer: For generic bz2 decompression, BZ2File class may be used.
from bz2 import BZ2File
with BZ2File("/app/tmp/res_test.tar.bz2") as f:
    content = f.read()

content should contain the decompressed contents of the file.
However, given that this is a tar file (an archive file that is normally extracted to disk as a directory of files), the tarfile module could be used instead, and it has extended mode flags for handling bz2.  Assuming the target file contains a res_test.csv, the following can be used
tf = tarfile.open('/app/tmp/res_test.tar.bz2', 'r:bz2')
csvfile = tf.extractfile('res_test.csv').read()

The r:bz2 flag opens the tar archive in a way that makes it possible to seek backwards, which is important as the alternative method r|bz2 makes it impractical to call extract files from the members it return by extractfile.  The second line simply calls extractfile to return the contents of 'res_test.csv' from the archive file as a string.
The transparent open mode ('r:*') is typically recommended, however, so if the input tar file is compressed using gzip instead no failure will be encountered.
Naturally, the tarfile module has a lower level open method which may be used on arbitrary stream objects.  If the file was already opened using BZ2File already, this can also be used
with BZ2File("/app/tmp/res_test.tar.bz2") as f:
    tf = tarfile.open(fileobj=f, mode='r:')
    csvfile = tf.extractfile('res_test.csv').read()

Comment: You can just simply use [`requests.get`](http://docs.python-requests.org/en/master/user/quickstart/) and read the `response.content` into a [`io.BytesIO`](https://docs.python.org/2/library/io.html#io.BytesIO). Example: `fileobj = BytesIO(requests.get(url).content)` and then `contents = tarfile.open(fileobj=fileobj).extractfile(filename).read()`
Comment: Hi, thank you for your answer, I have tried your method, however it still contains too much noise in the final decompressed data, I have edited the question according to this test, and I just wonder could you please share some more idea?
Comment: @buxizhizhoum my bad, I didn't clue into the fact that you are really working with a tarfile.
Comment: And one more question, does it possible to read the content if the tar.bz2 file is get with from web directly without buffer it to disk?


Why exactly is π(mean of radius)² less than the mean of the areas calculated for each radius?

Question: For example, a uniformly distributed value for a radius between 0 and 1 is calculated many times and the area for each radius is calculated:
<code>μ(radius) = 0.4998

μ(area) = 1.0467

π ( μ(radius) ) ² = 0.7849
</code>
If you compare the mean of the areas calculated during the loop with the value of the mean of the radii squared, why are they different? I would guess that it's to do with squaring the radius each time having a logarithmic / exponential effect on the sum of the areas, but I have no idea how. Any ideas?
Answer: Because
$$E(r^2) \ge E(r)^2$$
where $E(X)$ is the mean of the quantity $X$.  This is true because of something called Schwartz's Inequality.  That is,
$$\left |\int_0^R dr \, r \right |^2 \le \int_0^R dr \, r^2$$
Answer: If $A=\pi\cdot R^2$ and $R$ is not almost surely constant, then $\mathbb E(A)=\pi\cdot\mathbb E(R^2)\gt\pi\cdot(\mathbb E R)^2$ by Cauchy-Schwarz inequality.
Answer: In general $E(X^2)\ne E(X)^2$. The simplest case to see this is when $X=\pm1$ with probability $\frac12$ each, so that $E(X)=0\ne E(X^2)=1$.
In fact, $$V(X):=E((X-E(X))^2)=E(X^2-2E(X)X+E(X)^2) = E(X^2)-E(X)^2$$ is the variance of random variable $X$.
Since the variance oof the uniform distribution on $[0,1]$ is $\frac1{12}$, we'd expect the difference between your expressions to be $\frac\pi{12}\approx 0.2618$, which matches very well with your numerical results.


Positivity of a matrix

Question: Let $A$ be a $3\times 3$ matrix defined in the following way:
$$A=\begin{bmatrix} a & c & 0\\c & b &-c\\0 & -c & 1-a-b\end{bmatrix}$$
I wish to show that $A=BB^t$ for some matrix $B$. Further suppose that $a,b,c\ge0$ and $abc\ne0$.
Since there is a characterization of positive elements in matrices which says that $A$ is positive iff $A$ can be written as $BB^t$ for some matrix $B$.
Towards that end, for $u=[x,y,z] \in \mathbb{R}^3$, I looked at the inner product $\langle Au,u \rangle$ and found out that $$\langle Au,u \rangle=ax^2+by^2+(1-a-b)z^2+2cxy-2cyz$$
By Hilbert's seventeenth problem, a polynomial of degree $n$ is positive iff it can be written as a sum of $2^n$ positive polynomials. How do I write this polynomial as a sum of such polynomials?
Thanks for the help!!
Answer: In order for your matrix to be positive definite, all its leading principal minors must be positive.
So in addition to $a > 0$ you need $ab - c^2 > 0$ and $ab + b c^2 - a^2 b - a b^2 - c^2 > 0$.
EDIT: For your matrix to be positive semidefinite, you need
$  ab + b c^2 - a^2 b - a b^2 - c^2 \ge 0$ and $a+b-a^2-ab-b^2-2c^2\ge 0$.
Comment: A quibble: If $A=BB^t$ but $B$ is 2-by-3 (or equivalently, if $B$ is 3-by-3 but one of its columns is zero) then $A$ will have a zero eigenvalue and thus be positive semi-definite rather than positive. (Whether $A$ should be PD or PSD is a bit ambiguous from the question.) In that case the relevant criterion is that all its principal minors be non-negative, not just the leading principal minors.

Positivity of a matrix


SQL Server - Average a column that sometimes has numbers and sometimes strings

Question: I'm working with a column that was poorly set up as nvarchar, it sometimes has a number, which I want to average, and sometimes letters, nulls, or an empty string value.  How can I get an average of all of the numeric values that are greater than 0 for this column?
Side question: If I want to fix the column, what's the best way to do it without losing any of the numeric values?
Answer: Not bullet proof but should work:
WITH cte AS (
  SELECT *
  FROM your_tab
  WHERE ISNUMERIC(col) = 1
)
SELECT AVG(CAST(col AS DECIMAL(18,2))) AS average
FROM cte
WHERE CAST(col AS DECIMAL(18,2)) > 0;

SQL Server 2012+ has great TRY_CAST function:
SELECT AVG(casted_col) AS average
FROM (
  SELECT TRY_CAST(col AS DECIMAL(18,2)) AS casted  -- NULL if cannot cast
  FROM your_tab
) sub
WHERE casted_col > 0;

Comment: This is handy, I can use the CTE to fix the table, too.
Comment: Re: "Not bullet proof". For those new to [`IsNumeric()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql), it is notoriously [problematic](http://www.sqlservercentral.com/articles/ISNUMERIC()/71512/).


Laura hire in apple?

Question: Laura has applied for a job with Company A. As part of the hiring process, Company A will of course look at her grade in a Business class. If Laura gets an $A$, there is a $85\%$ chance that Company A will hire her. But if she does not get an $A$, there is only a $10\%$ chance that they will hire her. Laura's professor says that there is a $70\%$ chance that Laura will get an A in her Business class $90$.
What is the probability that Laura gets an A in Business class and also gets hired by Company A?
My answer is $= 0.952$ that is correct?
Comment: Is she trying to be hired by apple or is she trying to be hired by facebook?  Before math comprehension, reading comprehension should come first.
Comment: Can you explain how you arrived at your answer?
Comment: thats rigth!!! suppose apple.
Comment: I found P(H)=P(H|A) *P(A) +P(H|A')P(A') , then I need P(H intersection A), therefore I apply mult. rule and I have :P(h|a)=P(h intersection A)*P(h) /P(a).
Comment: Please explain "BUS 90 at SJSU". This is not common knowledge.
Comment: @barakmanos presumably it is the business class which the OP is enrolled in.  "Business 90."  It just gives flavor to the problem.
Comment: @JMoravitz: So "BUS 90" is the name of the class and "SJSU" is the name of the academic institution? Despite the flavor, this sentence is rather hard to read.
Comment: @Electro82: Please can you explain what the events H and A mean and edit your question to explain your reasoning and how you arrived at the answer.
Comment: The answer is 0.595, I use a wrong formula(equation).

P(h|a)=P(h intersection A) /P(a)

Thanks
Comment: A fascinating title; I won't dare to edit it into something boring.
Answer: Yes, you are correct in your comment above. But you should explain your reasoning so that someone who is reading your answer can understand the steps that you took to arrive at that answer. For example, this is how I would write-up the solution:
Let $H$ be the event that Laura gets hired and $A$ be the event that she gets an A in class. Then from the definition of conditional probability we have,
\begin{eqnarray}
P(H|A) & = & \frac{P(H \cap A)}{P(A)} \\
\implies P(H \cap A) & = & P(H |A) P(A) \\
\implies P(H \cap A) &=& 0.85 \times 0.7 = 0.595 \textrm{ (Substituting the probabilities given in the question).}
\end{eqnarray}
So the probability that Laura gets an A in business class and also gets hired by the company is $59.5\%$.
Answer: Imagine 1000 "Laura"s.  70% of them, 700 "Laura"s, get an A.  85% of the 700 "Laura"s who get an A, .85(700)= 595, are hired by company A.  So 595 of the 1000 "Laura"s, 595/1000= 0.595 or 59.5%, both got an A and were hired.
That is, of course, the same as Multiplying (.70)(.85).

Laura hire in apple?


Select com resultado errado

Question: Possuo o seguinte select:
SELECT suprimento, public.tiposuprimento.descricao, capacidade,
count(public.estoque.codigosuprimento) quantidade,estoqueminimo, sum (valorunitario) valor
FROM public.estoque,public.tiposuprimento, public.suprimento
WHERE public.estoque.codigosuprimento = public.suprimento.codigo and
public.tiposuprimento.codigo = public.suprimento.codigotiposuprimento and usado = '0'
  AND codigosuprimento = 155
GROUP BY suprimento, public.tiposuprimento.descricao,capacidade,estoqueminimo
ORDER BY suprimento

Que me retorna corretamente as seguintes informações:

Porém preciso adicionar quais equipamentos são compatíveis com esse suprimento, para isso criei a seguinte Query
SELECT codigosuprimento, array_to_string(array_agg(modelo),' | ') AS modelo
FROM public.modelosuprimento, public.impressoramodelo
WHERE public.impressoramodelo.codigo = public.modelosuprimento.codigomodelo
  AND codigosuprimento = 155
GROUP BY codigosuprimento;

E ela me retorna os equipamentos corretamente:

Porém não estou conseguindo unir essas Querys ou faze-las em um select apenas, sempre que tento adaptar para um select só meu resultado é inconsistente com as informações corretas. Já tentei da seguinte forma:
SELECT suprimento, public.tiposuprimento.descricao, capacidade,
count(public.estoque.codigosuprimento) quantidade,estoqueminimo, sum (valorunitario) valor,
array_to_string(array_agg(modelo),' | ') AS modelo
FROM public.estoque,public.tiposuprimento, public.suprimento, public.modelosuprimento, public.impressoramodelo
WHERE public.estoque.codigosuprimento = public.suprimento.codigo
  AND public.estoque.codigosuprimento = public.modelosuprimento.codigosuprimento
  AND public.modelosuprimento.codigomodelo = public.impressoramodelo.codigo
  AND public.tiposuprimento.codigo = public.suprimento.codigotiposuprimento
  AND usado = '0'
  AND public.modelosuprimento.codigosuprimento = 155
GROUP BY suprimento, public.tiposuprimento.descricao,capacidade,estoqueminimo
ORDER BY suprimento

E obtive o seguinte resultado:

Que está incorreto, se tiverem alguma ideia de o que estou fazendo errado ou alguma dica de como alcançar esse objetivo, agradeço.
Comment: Em vista o problema é que você está usando `WHERE` para relacionar as tabelas, e se caso 1 delas não tiver correspondência, o valor não é retornado. Utilize `JOINS` para fazer essa união. Se tiver isso no sqlfiddle faço o select para você.
Comment: @RBZ como posso substituir por JOIN nesse caso?
Comment: Você precisa baixar o script do banco, com a criação das tabelas, inserts, etc, assim ele gera seu banco no fiddle, aí você passa o link. http://sqlfiddle.com/ , exemplo: http://sqlfiddle.com/#!9/a6c585/1
Comment: @RBZ Tu teria como colocar um exemplo de como utilizar o JOIN dai eu adapto para minha necessidade?
Comment: posta a estrutura das tabelas
Comment: @R.Santos Publiquei como resposta. Dê uma olhada em https://pt.stackoverflow.com/questions/274433/selecionar-somente-tuplas-de-uma-tabela-com-join/274447#274447
Answer: Em vista o problema é que você está usando WHERE para relacionar as tabelas, e se caso 1 delas não tiver correspondência, o valor não é retornado. Utilize JOINS para fazer essa união.
Basicamente você tem que entender o conceito da esquerda e direita (left e right), por exemplo:
A sua tabela em FROM ela é a sua tabela esquerda, ou seja, LEFT, quando for fazer um JOIN.
FROM tabela1 X
LEFT OUTER JOIN tabela2 Y ON Y.campo1 = X.campo2

Ou seja, você está trazendo tudo da tabela X, mais os registros da Y que tem vínculo com a X.
Agora em:
FROM tabela1 X
RIGHT OUTER JOIN tabela2 Y ON Y.campo1 = X.campo2

Você trás tudo que está na sua tabela da direita "Y" mais os de "X" que tem relação com "Y".
O INNER somente o que for em comum nas 2 tabelas, e o FULL trás TUDO independente das relações.
Link#1
Link#2
Answer: Resolvi meu problema realizando um subSelect:
SELECT public.estoque.codigosuprimento as cod ,suprimento, public.tiposuprimento.descricao, capacidade,
count(public.estoque.codigosuprimento) quantidade,estoqueminimo, sum (valorunitario) valor, (SELECT array_to_string(array_agg(modelo),' | ') AS modelo
FROM public.modelosuprimento, public.impressoramodelo where
public.impressoramodelo.codigo = public.modelosuprimento.codigomodelo and codigosuprimento = public.estoque.codigosuprimento group by codigosuprimento)
FROM public.estoque,public.tiposuprimento, public.suprimento
where public.estoque.codigosuprimento = public.suprimento.codigo and
public.tiposuprimento.codigo = public.suprimento.codigotiposuprimento and usado = '0'
group by suprimento, public.tiposuprimento.descricao,capacidade,estoqueminimo,public.estoque.codigosuprimento
order by suprimento

Select com resultado errado


How do you train a neural network by the highscore instead of correct output data?

Question: Before coming to the question, I'd like to mention that I've been reading through some basic articles about machine learning and watched some tutorials on the net. With that said; my knowledge is very limited in the subject.
Most examples I've seen (in code) often has datasets that contains the desired
output of certain data, this in order to train and test.
What I'd like to try - or see by code example at least - would be an example of a neural network getting trained and tested by its achieved scores, instead of the desired output to be the exactly expected.
What I mean with trained by achieved scores would for instance be that the machine has three options:
Stand still, Walk right, Jump. So instead of training the machine exactly when to stand still, walk or jump, it is trained by how many points it gets. I.e the more you walk and jump, the more points you might get according to the situation (i,e if you don't jump, a monster kills you). So, the more score you get the better.
How do you train a neural network by high scores instead of the exact desired output in a situation?

P.S: This video is pretty similar of what I am trying to explain, but I'd like it more easier than a game like this.
Also, if you could add examples in code (python would be preferable if possible), that is highly appreciated.
Answer: What you are looking for is called 'reinforcement learning'. Searching on google etc for 'reinforcement learning' will yield a ton.
Some good introductions:

karpathy's posts: http://karpathy.github.io/2016/05/31/rl/
http://cs.stanford.edu/people/karpathy/reinforcejs/
https://blog.openai.com/evolution-strategies/
https://blog.openai.com/dota-2/

Well, you know what, Karpathy's posts, together with the search terms 'reinforcement learning' are enough to get you started I reckon :)


Backus-Naur form of a token that begins and ends with double quotes

Question: Is it possible to write a Backus-Naur form description of a token that:

starts with double quotes
ends with double quotes
can contain inner
double quotes

?
For example I have programming construct called MESSAGE that can look like:
MESSAGE "She said "Hello" to him"
Is that possible to describe with an LL(1) Backus-Naur form?
Edits:  let's assume that I'm parsing by simply iterating over each character, one at a time, with one lookahead pointer.
The input string is the whole thing, including MESSAGE.
Comment: I don't think you've provided enough information about what you're trying to do to get a definitive answer. Is `MESSAGE` part of the input? Can a MESSAGE span multiple lines? What are you parsing, and how?
Comment: How do you know where the MESSAGE ends? iow, why.is your example not two MESSAGEs with a word Hello between them?
Comment: MESSAGE is part of the input, but I already know how to specify that part in BNF.  Let's assume it can span multiple lines (I'm doing research to find out if that's true or not because if it can't then I can just parse til the newline). I'll update the question the make it more clear.
Answer: Something like this might do the trick (Sorry for the syntax. It's a while ago, that I worked with BNF).
message : MESSAGE message_text
message_text : " inner_message " | message_text inner_message " inner_message "
inner_message : [a-z0-9...]+

Your example MESSAGE "She said "Hello" to him"
should be interpreted in two steps: First, the second form of message_text gets the hello " to him" and than, secondly, the first form of message_text gets "She said ".
inner_message must contain all possible characters and spaces.
As mentioned in the comments, the 'magic'  lies in the second definition of message_text. As BNF has no concept of loops or if's, recursion is the only way to describe repetitions. One just need to ensure, that the syntax does not get ambiguous, means that for each possible input only one valid path exists (or none, which declares an error). The above syntax should work except for empty middle strings like in " he replied with "" silence".
Comment: Interesting.  The second option for message text is hard for me to interpret.  Is that where the magic lies?  Would you mind trying to explain it conversationally?
Comment: I triedi n the answer. Lets see if I can answer any other specific question.
Comment: Ah I see.  I can understand it now by assuming that the first option is the base case of the recursion.  So what do you think about:  message_text : " inner_message " | " [message_text]+ "    That would work, right?
Comment: If BNF would allow lops like regular expressions. BNF is extremely basic at this point


Any logs for AWS RDS auto start?

Question: From AWS documentation Stopping an Amazon RDS DB Instance Temporarily:

You can stop a DB instance for up to seven days. If you do not manually start your DB instance after seven days, your DB instance is automatically started.

But I cannot find any StartDBInstance event in CloudTrail. Is it because the start action is not from API call?
Is there any log for the RDS auto start? (something like AutoStartDBInstance?)
Answer: CloudTrail logs actions performed by you, not by the service internally so you won't see the Automatic Start.
An event is published to SNS however, RDS-EVENT-0088

Any logs for AWS RDS auto start?


Lebesgue inner measure formula

Question: I cannot prove this formula:
$E$ is measurable and $A$ is any subset of $E$
show that $m(E)=m_*(A) +m^*(E-A)$.
Define inner measure of $A$ by $m_∗(A)=\sup(m(F))$, where the supremum is taken over all closed subsets $F$ of $E$.
$m(E)$ means $E$ is measurable and for outer measure of $E$, cover $E$ by countable collection $S$ of intervals $I_k$. i.e. $m^\ast(E)=\inf \sum \nu(I_k)$
Thanks and regards.
Comment: In any case, when you ask it here you should provide the definitions you are using.
Comment: What did you try? Can you recall the definition of inner and outer measure, then try to see how it may solve the problem.
Answer: With the little information you give on what you know, this is bound to be somewhat tricky.
Here's an outline for a proof of the following more general formula:
For every measurable set $E$ and an arbitrary set $A$ we have
$$m(E) = m_\ast(E \cap A) + m^\ast(E \smallsetminus A).\tag{$*$}$$

Prove that for all $A$ the identity $m^\ast(A) = \inf{\{m(G)\,:\,G \supset A \text{ measurable}\}}$ holds.
[If $m^\ast(A) = \infty$ then ... If $m^\ast(A) \lt \infty$ take $G_n \supset A$ to be a union of intervals with $m(G_n) \lt m^\ast(A) + \frac{1}{n}$ and put $G = \bigcap G_n$.]
Prove that for all $A$ we have $m_\ast(A) = \sup{\{m(F)\,:\,F \subset A \text{ is measurable}\}}.$
If the measure of $E$ is finite, we have $m^\ast(E \smallsetminus A) \lt \infty$ and we may write
$$
\begin{align*}
m(E) - m^\ast(E \smallsetminus A)
& =
m(E) -  \inf{\{m(G)\,:\,G \supset E \smallsetminus A \text{ is measurable}\}} \\
& =
m(E) -  \inf{\{m(G)\,:\,E \supset G \supset E \smallsetminus A \text{ is measurable}\}} \\
& = m(E) - \inf{\{m(E) - m(F)\,:\,F \subset E \cap A \text{ is measurable}\}}
\tag{#} \\
& = \sup{\{m(F)\,:\,F \subset E \cap A \text{ is measurable}\}} \\
& = m_\ast(E \cap A)
\end{align*}
$$
so that $m(E) = m_\ast(E\cap A) + m^\ast(E \smallsetminus A)$, which is the desired formula (for sets $E$ of finite measure).
[Note that in $(\#)$ we used measurability of $E$ and finiteness of its measure to conclude that for $E \supset G \supset E \cap A$ and $F = E \smallsetminus G$ we have $m(E) = m(G) + m(F)$.]
By definition
$m_\ast (A) = \sup{\{m(F)\,:\,F \subset A \text{ is closed}\}}$.
For each closed $F \subset E \cap A$ we have
$$
m(E) = m(F) + m(E \smallsetminus F) \geq m(F) + m^\ast(E \smallsetminus A)
$$
since measurability of $F$ gives
$m(E \smallsetminus F) = m^\ast(E \smallsetminus F)$,
and since $E \smallsetminus F \supset E \smallsetminus A$ yields
$m^\ast(E \smallsetminus F) \geq m^\ast(E \smallsetminus A)$ because $m^\ast$ is monotone.
Taking the supremum over all closed $F \subset E \cap A$ we get
$$
m(E) \geq m_\ast(E \cap A) + m^\ast(E \smallsetminus A).\tag{1}
$$
Finally, we can establish $(\ast)$ for arbitrary measurable $E$ by observing that monotonicity of $m_\ast$ and $m^\ast$ give
$$
\begin{align*}
m_\ast(E \cap A) + m^\ast(E \smallsetminus A)
&\geq \sup{\{m_\ast (F \cap A) + m^\ast(F \smallsetminus A)\,:\,F \subset E \text{ measurable, }m(F) \lt \infty\}} \\
&= \sup{\{m(F)\,:\,F \subset E \text{ measurable, } m(F) \lt \infty\}} \\
&= m(E)
 \end{align*}
$$
and combining this with the inequality in $(1)$. In the first equality here we used what we proved in 3.

Lebesgue inner measure formula


How to "speed up" basic investment formula?

Question: I have a formula (start of year, not end) for calculating basic investment, but it only works when calculated once per year. Say I wanted to add interest every day so that after a year the total be the same as the above formula pays out once a year. How would I adjust the formula to do that?
Comment: Is the formula in that link?  If so please enter it here using MathJax.  I don't follow links out of the site.  One question will be to do with rounding.  An answer calculated by a computer would be subject to intermediate rounding.
Comment: idk how to use MathJax but the formula is `Balance(Y)   =   P(1 + r)^Y + c[((1 + r)^(Y + 1) - (1 + r)) / r]`. The link explained the formula in depth so I thought it better to post that.
Comment: There is a tutorial here: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference. And plenty more on the web if you search.  People here will be much more willing to help if you learn to format your answers nicely.
Comment: It sounds as if your question may be more about programming than maths. If so, this is not the best site.
Comment: Well it is being used for programming but that's irrelevant to what I need, which is just a math formula.
Comment: If I go to stackoverflow asking for help with a math formula they'll just point me here lol
Comment: You say below "I'd have to store extra variables" - that sounds like programming not maths.  Another tricky point is rounding.  A maths answer will deal with exact calculations. A computer will deal with approximations.  A mathematician may give you a clever formula that will do the same job more efficiently. When you run it on a real computer, you might get slightly different results. Would that matter?
Answer: Basically, what you would do is get the percentage and round it and turn it from a percentage to a number. After that, you're going to get that number and add it to the actual calculation or the result. You would adjust the calculation and divide it to the actual interest of the percentage. Afterwards, you would be left with a percentage which is the result of dividing the first division to the actual result without interest, you would keep that result somewhere and redo the whole process while using the NEW result.
Comment: Doesn't work like that, formula isn't that simple. And even if it did I'd have to store extra variables to do it, which is also a no go.


General case integral $\int^1_0 f(x) \, f'(1-x) \, dx $

Question: Suppose we get the following general case
$$\int^1_0 \, f(x) \, f'(1-x) \, dx $$
where $f$ is differentiable on $[0,1]$ . Can we have a general formula for the integral ?
Of cousre we can generalize for
$$\int^a_0 \, f(x) \, f'(a-x) \, dx $$
Interesting examples would be
$$\int^{\frac{\pi}{2}}_0 \sin^n(x) dx $$
Which is easily found by beta function or integration be parts .
Answer: Here is a suggestion for functions of class $\mathcal{C}^1$:
Suppose first that $f(0)=f(1)$. In that case, $f$ can be extended into a 1-periodic function via a Fourier series $$f(x)=\sum_{-\infty}^\infty c_n e^{2 \pi n i x}, \\ c_n=\int_0^1f(x) e^{-2 \pi n ix }\mathrm{d} x.$$
The derivative is then $$f'(x)= \sum_{-\infty}^\infty 2 \pi n i c_n e^{2 \pi n i x},$$ so that $$f'(1-x)=\sum_{-\infty}^\infty2 \pi n i c_ne^{-2 \pi n i x}. $$
When multiplying $f(x) \cdot f'(1-x)$ and integrating over the period, only the constant coefficient is of interest. The integral is then $$ \int_0^1 f(x) f'(1-x) \mathrm{d} x= \sum_{-\infty}^\infty 2\pi n i c_n^2 .$$
If $f(0) \neq f(1)$, consider the function $g(x)=f(x)-x(f(1)-f(0))$. It is of class $\mathcal{C}^1$ as well as $f$, and it also satisfies $g(0)=g(1)$. $g$ has Fourier coefficients $$d_n=c_n-(f(1)-f(0))e_n ,$$ where $$e_n=\begin{cases} \frac{1}{2}& n=0 \\ \frac{i}{2 \pi n} & n \neq 0 \end{cases} .$$
We know that $$\int_0^1 g(x) g'(1-x) \mathrm{d} x= \sum_{-\infty}^\infty 2 \pi n i d_n^2 .$$
The integral can be further simplified: $$\int_0^1 [f(x)-x(f(1)-f(0))][f'(1-x)-(f(1)-f(0))] \mathrm{d} x \\=\int_0^1 f(x) f'(1-x) \mathrm{d} x-(f(1)-f(0)) \int_0^1 f(x) \mathrm{d} x-(f(1)-f(0)) \int_0^1 x f'(1-x) \mathrm{d} x+\frac{(f(1)-f(0))^2}{2}. $$ We recognize $\int_0^1 f(x) \mathrm{d} x$ as $c_0$, and integrate $\int_0^1 x f'(1-x) \mathrm{d} x$ by parts. Finally we have $$\int_0^1 f(x) f'(1-x) \mathrm{d} x=(f(1)-f(0))(2c_0-f(0))-\frac{(f(1)-f(0))^2}{2}+ \sum_{-\infty}^\infty 2 \pi n i d_n^2. $$


freebsd does not recognise that php was installed via ports

Question: I have php 5.2.12 installed on FreeBSD 8.0-STABLE. It was installed from ports and I am trying to upgrade it to 5.3.2.
However for some reason my system is not recognising that php was installed via ports. When I run "pkg_version" the list does not include php it does however include all the extensions that I have installed.
I have even tried to do "make deinstall" on "/usr/ports/lang/php5" it told me that the port had been deinstalled but php still appears to be working correctly i.e "php -v" works
any ideas on how this port has become de attached from the ports system? and how I can get the ports system to recognise that it installed php?
EDIT: When I run "make deinstall" over and over again I always get the same answer

Deinstalling for lang/php5

I never get

php52 not installed, skipping

which is what I am expecting after the first time I run "make deinstall"
Answer: If you're in lang/php5 then you're uninstalling PHP 5.3; you need to be in lang/php52 to uninstall PHP 5.2
Comment: I get this "php52 not installed, skipping" when running make deinstall in lang/php5 and lang/php5 currently contains 5.3.2 not 5.2
Comment: Correct. To deinstall 5.2 you must be in the /usr/ports/lang/php52 directory. You can not uninstall 5.2 from the 5.3 (or 5.0, depending on how current your ports tree is) directory. The two versions are **not in the same directory**.
Answer: Roughly speaking, PHP 5.3.2 was only recently introduced to the FreeBSD ports tree and in order to properly install 5.3.2, you must first update your local ports tree using csup or cvsup. Have you gone thru these steps first?
Comment: ran cvsup several times lang/php5 says it has php 5.3.2 but some some reason my system does not recognise that php is installed at all
Answer: I am not sure why but the answer was to rebuild all of the ports

portupgrade -a

after running this pkg_version now realises that php is installed.
Fortunately this is not a production machine so this was not a problem if I get this happening on a production machine I think I will need a better answer so, if anyone has an explanation as to why portupgrade -a might have fixed my issue that would be very helpful.


Backupchain bandwidth calculation

Question: we have 7 servers being backed up right now using backup chain locally for about a year now. I have tried the FTP backup on one of our financial number crunch VMs to move it offsite to our other office and it has been working great. I am not a big ftp expert hence a little question
Question: we currently have upload isp speed 10 mega bits and we plan to back all the VMs over the wire. total size of our VMs right now is 600GB and of course growing
do you think we need a better isp to back this whole thing up over night?
How much bandwidth should we buy to get this to work smoothly?
Answer: I shouldn't have to do this for you, but here we go anyway:
<code>10Mbps == 1.25MB/sec
600GB  == 614400MB

614400MB / 1.25MB/sec = 491520 Seconds
  491520 / 60         = 8192 Minutes
    8192 / 60         = 136.53 Hours
  136.53 / 24         = 5.68 Days
</code>
You're gunna need a bigger boat if you want to transfer that sort of data regularly. But if you're doing full backups over the wire, you're crazy. You want to do one full backup and then just the deltas (incremental backups).
Problem's going to be that you're going to have 6 days worth of changes queued up while the initial copies go over.

Backupchain bandwidth calculation


Game Center share achievement or leaderboard crashes on iPad iOS 8

Question: Hello everyone I am trying to implement Game Center on my iOS8 app and have run into a crash on the iPad. I already have the achievements and leaderboards set up and can successfully hit the blue share button on the iPhone but when i press share on the iPad the GKGameCenterViewController crashes and gives me the following report:

Application Specific Information:
  *** Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController
  (<_UIAlertControllerActionSheetRegularPresentationController:
  0x7b1480a0>) should have a non-nil sourceView or barButtonItem set
  before the presentation occurs.' terminating with uncaught exception
  of type NSException abort() called CoreSimulator 110.4 - Device: iPad
  Retina - Runtime: iOS 8.1 (12B411) - DeviceType: iPad Retina

Any help would be appreciated thank you!
Answer: I got the same crash. When I present the GKGameCenterViewController modally, it's important I provide the sourceView, using the code in this order:
    gameCenterVC.modalPresentationStyle = .Popover
    gameCenterVC.popoverPresentationController?.sourceView = view!
    gameCenterVC.popoverPresentationController?.sourceRect = view!.frame
    presentViewController(gameCenterVC, animated: true, completion: {})

Your error reads

"reason: 'UIPopoverPresentationController [...]"

which suggests your modalPresentationStyle = .Popover.
In that case, you will need to set the source view or button bar, like the rest of the error indicates.
The instance popoverPresentationController in non-nil because...

If you created the view controller but have not yet presented it, accessing this property creates a popover presentation controller when the value in the modalPresentationStyle property is UIModalPresentationPopover

according to popoverPresentationController
Comment: Welcome to Stack Overflow! A link to a potential solution is always welcome, but please add context around the link so your fellow users will have some idea what it is and why it's there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.
Answer: I am testing on an iPad Air with iOS 9.3.
I am getting it to run without crashing [using my solution in the above post], but it does not display the game center popups or view controllers with
modalPresentationStyle = .Popover

However, I do get my view controllers and sign in pop ups when I set
modalPresentationStyle = .Fullscreen


How can I make the user add a new field using a button using javascript?

Question: I have a script posted down below, and I want the user to add a new field, when the new field gets added I want a new var to be added.
Live example:
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
I don't have an idea of how to do the above honestly.
<!DOCTYPE html>

<form name="TRF" method="post">

Accepted Format

Accepted Format

                  Applicant's Name:
                  <input type="text" name="accname" size="75" placeholder="" required>

                  Reason 1:
                  <input type="text" name="R1" size="75" placeholder="" required>

                  Reason 2:
                  <input type="text" name="R2" size="75" placeholder="" required>

CODE:

              <textarea  id="box" cols="100" rows="10"></textarea>

GENERATE CODE

            <button id="newField">
            add new field
            </button>

</color>

User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
Comment: do you want to use vanilla js or is jquery ok
Comment: It doesn't really matter honestly, as long as I can get the result I want.
Answer: In Javascript it's possible to create html elements at runtime using the createElement() function. In your case we need to create quite a lot of individual elements to replicate the structure of the table. Those are
  <input>.
The tr element needs to be added to the table, the td containing the text 'Reason #:' as well as the td holding the input element are childs of tr. To add a dynamically created element to the DOM, the appendChild() function is used.
The input element needs some special treatment because it contains an unique id. The two html-made elements you have are 'R1' and 'R2' - so a new one should follow that pattern and start with 3. This is done by setting up a global variable , appending it to the name and increment it afterwards.
Finally we need to add a 'Create new field' button.
Take a look at this example (you have to scroll down to see the button):

var newField = document.getElementById("newField");
var counter = 3;

function createNewField() {
  var tr = document.createElement("tr");
  var td1 = document.createElement("td");
  var td2 = document.createElement("td");
  td1.innerHTML = "Reason " + counter + ":";
  var inp = document.createElement("input");
  inp.type = "text";
  inp.size = "75";
  inp.name = "R" + counter;
  td2.appendChild(inp);

  document.getElementById("theTable").appendChild(tr);

  tr.appendChild(td1);
  tr.appendChild(td2);

  counter++;
}
newField.addEventListener("click", createNewField);

function generateCode2() {
  var AccoutName = document.forms["TRF"]["accname"].value;
  var reasons = "";

  for (var a = 1; a < counter; a++) {
    reasons += "Reason " + a + ": " + document.forms["TRF"]["R" + a].value + "\n";
  }

  document.getElementById("box").value =
    "[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]" +
    "[hr]" +
    "\n" +
    "[b]Dear[/b] " + AccoutName +
    "\n" +
    "After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. " +
    "\n" + reasons +
    "Welcome to the Family. " +
    "\n" +
    ""
}
<form name="TRF" method="post">

Accepted Format

Accepted Format

                  Applicant's Name:
                  <input type="text" name="accname" size="75" placeholder="" required>

                  Reason 1:
                  <input type="text" name="R1" size="75" placeholder="" required>

                  Reason 2:
                  <input type="text" name="R2" size="75" placeholder="" required>

CODE:

              <textarea id="box" cols="100" rows="10"></textarea>

GENERATE CODE

            <button id="newField">
            add new field
            </button>

Comment: Exactly what I wanted, except that I want to add what the user types into the text area above the "generate code" text.
Reason Three: "User Input"
Comment: Do you have a way to do that?
Comment: When I enter the input for Reason 3, Reason 4, etc.
The input is not put in the "text area". It only displays
Reason One:
Reason Two:
While the other reasons added by the user are not displayed.
Comment: Ah I understand. Take a look at the updated generateCode2() function in my snippet above.
Comment: The script is exactly what I wanted, except that when I generate, Reason 1 looks like this: "undefinedReason 1: " I want to remove the "Undefined"
Comment: Whoops - my bad! I accidentally forgot to initialize reasons as String. Change: `var reasons;` to `var reasons = "";`
Comment: Thanks a lot for your awesome help.


Unable to insert EMF into Word using Python

Question: I have a requirement for inserting SVG file into Word. Since, we cannot do this directly I am planning to convert SVG to EMF and insert it. Conversion from SVG to EMF works fine using the inkscape. However, I am unable to come up with right code for inserting it into Word.
I followed the steps explained the the person Alvaro in this post. Have shown the steps followed in the attached file -
This is my code -

However, when I run the code shown in the attachment - It still throws docx.image.exceptions.UnrecognizedImageError. The Contributor of the library on github claims that this library addresses this issue. If so then please let me know if I am missing anything.
I am able to insert the EMF file successfully manually. Attaching the doc by inserting the EMF. This EMF was downloaded from the internet for testing.
Comment: It looks like the problem is in the images. EMF format is unfamous for its glitches. Probably some images can be handled this way but some can't. Can you paste the images into DOCX file manually? DOCX file is basically a zip-archive with xml and media files. You can make a DOCX file manually, save it, unzip it and see, how your EMF are stored. And then to figure out how you can do something alike with another file.
Comment: @YuriKhristich - Thanks for responding. I am able to insert the EMF file into Word. Have just updated my question attaching the doc. Please have a look and let me know.
Comment: @YuriKhristich-Sorry, you are right. I missed that Stackoverflow does not allow us to upload the files. Is there a way I can share it with you? Can mail it to you if you share your email address.
Comment: Have just uploaded the doc here - https://file.io/29Vhavlq5Mak
Comment: This is the EMF file - https://file.io/9n8QTizYYlT2
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232869/discussion-between-ashwin-kumar-and-yuri-khristich).
Answer: Here is another solution based on win32com module and MS Word API:
from pathlib import Path
import win32com.client

cur_dir  = Path.cwd()                                   # get current folder
pictures = list((cur_dir / "pictures").glob("*.emf"))   # get a list of pictures
word_app = win32com.client.Dispatch("Word.Application") # run Word
doc      = word_app.Documents.Add()                     # create a new docx file

for pict in pictures:                                   # insert all pictures
    doc.InlineShapes.AddPicture(pict)

doc.SaveAs(str(cur_dir / "pictures.docx"))              # save the docx file
doc.Close()                                             # close docx
word_app.Quit()                                         # close Word

Put your EMF images in subfolder pictures and run this script. After that you get in current folder the file pictures.docx that contains all these EMF images inside.
Comment: You are great! Thanks a lot. This works fine. Let me give it a try for the solution kiwiwings provides. He has given a Java project. Will try if that works before closing this question.
Comment: Keep in mind that `win32com` works only on Windows.
Comment: Will do, Thanks
Comment: your solution using win32com seem to be addressing our requirements. Will accept that as the answer to my question. Thanks a lot for you time and the valuable suggestions you gave.
Answer: It seems the module docx doesn't work with EMF files.
The work around that I mean is here:
import shutil
import zipfile

temp_dir = "_temp"

old_docx = "doc.docx"
new_docx = "doc_new.docx"

old_emf = temp_dir + "/word/media/image1.emf"
new_emf = "new_image.emf"

# unpack content of the docx file into the temp folder

with zipfile.ZipFile(old_docx, "r") as z:
    files = z.namelist()
    for f in files: z.extract(f, temp_dir)

# replace the image

shutil.copyfile(new_emf, old_emf)

# pack all files from temp folder back into the new docx file

with zipfile.ZipFile(new_docx, "a") as z:
    for f in files: z.write(temp_dir + "/" + f, f)

# remove the temp folder

shutil.rmtree(temp_dir)

Typical structure of a docx file:
doc.docx
│
├─ [Content_Types].xml
│
├─ _rels
│  └─ .rels
│
├─ docProps
│  ├─ app.xml
│  └─ docProps
│
└─ word
   ├─ document.xml    <-- text is here
   ├─ fontTable.xml
   ├─ settings.xml
   ├─ webSettings.xml
   ├─ styles.xml
   │
   ├─ _rels
   │  └─ document.xml.rels
   │
   ├─ theme
   │  └─ theme1.xml
   │
   └─ media
      └─ image1.emf   <-- your image is here

It unpacks content of the doc file doc.docx in temporary folder _temp, then it replaces the file image1.emf inside the temp dir with another file new_image.emf from current dir. Then it packs the content of the temp folder back into doc_new.docx file and removes the temp dir.
Note: new image will have the same size in the new_doc.docx as old one.
So the workflow can be like this: you make template docx file, place there manually template emf picture and save the docx file. Then you take the new emf image, put the image next to the docx file and run the script. This way you get new a docx file with the new emf image.
I suppose you have many emf images, so it makes sense to add in this script a couple lines that it be able to take several images and make several docx files.
It will work fine if all the emf images have the same size. In case they have different size it will take more coding to handle with xml data.
Update
I've figured out how to get sizes of emf image. So here is full solution:
from docx import Document
import shutil
import zipfile

temp_dir = "_temp"
old_docx = "doc.docx"
new_docx = "doc_new.docx"
old_emf  = temp_dir + "/word/media/image1.emf" # don't change this line
new_emf  = "img5.emf"

# unpack content of the docx file into temp folder
with zipfile.ZipFile(old_docx, "r") as z:
    files = z.namelist()
    for f in files: z.extract(f, temp_dir)

# replace the image
shutil.copyfile(new_emf, old_emf)

# pack all files from temp folder back into the new docx file
with zipfile.ZipFile(new_docx, "a") as z:
    for f in files: z.write(temp_dir + "/" + f, f)

# remove temp folder
shutil.rmtree(temp_dir)

# get sizes of the emf image
with open(new_emf, "rb") as f:
    f.read(16)
    w1, w2 = f.read(1).hex(), f.read(1).hex()
    f.read(2)
    h1, h2 = f.read(1).hex(), f.read(1).hex()

width  = int(str(w2) + str(w1), 16) * 762
height = int(str(h2) + str(h1), 16) * 762

# open the new docx file and set the sizes for the image
doc = Document(new_docx)
img = doc.inline_shapes[0]  # suppose the first image is the image
img.width  = width
img.height = height

doc.save(new_docx)

Comment: Thanks, @Yuri Will try this tomorrow and let you know
Comment: I am able to run this and it transfers the EMF from doc to doc_new. However, please let me know how can I utilize this?
Comment: This script changes EMF image in doc.docx file with another EMF image (taken from current folder) and saves new docx file with name doc_new.docx. It's up to you how to utilize this. Probably, I don't know, if you have hundreds emf files, you can put them in a folder, and (after minimal modifications of this script) make hundred docx file each of them will contain a relevant EMF image. But you still haven't mentioned what do you trying to do.
Comment: My primary objective is to insert the SVG files into Word. We are resorting to SVG because the image remains undistorted when the resolution changes. This image will primarily contain some of the plots my Team generates. Here is an example - https://file.io/IotKrLUtqdUY   Since we couldn't find any way for inserting SVG we planned to convert SVG to EMF using incscape and wanted to build a script that inserts all the plots into a word document. Please let me know if you have any thoughts for handling our requirement.
Comment: See my another solution based on `win32com` module
Answer: SVG can be added to Word directly - just try it out manually in Word (2016).
I've created an example Java project as a POC for your use case.
No need to call inkscape, because the fallback PNG is created on the fly via Batik.
Of course the OP asked for a Python solution - but in case python-openxml is missing some functionality, there might be a point where there needs to be put more effort in getting it to run via python vs. invoking a java runtime.
Regarding the workaround solution via EMF - be aware that there are various methods in determining the bounds - in the EMF renderer, which I've implemented in POI, I scan through the Window and Viewport records by default and only use the EMF header bounds if I couldn't find anything else or if the scan is omitted via configuration option. This gives me usually better results.
The relevant code snipplet of the example project is the following:
public class AddSvgToDocument {
    public static void main(String[] args) throws IOException, InvalidFormatException {
        File tmplDocx = new File(args[0]);
        File svgFile = new File(args[1]);
        File outDocx = new File(args[2]);

        try (FileInputStream fis = new FileInputStream(tmplDocx);
             XWPFDocument doc = new XWPFDocument(fis)) {

            SVGImageRenderer rnd = new SVGImageRenderer();
            try (FileInputStream fis2 = new FileInputStream(svgFile)) {
                rnd.loadImage(fis2, PictureData.PictureType.SVG.contentType);
            }

            Rectangle2D nativeDim = rnd.getNativeBounds();
            double widthPx = 500;
            double heightPx = widthPx * nativeDim.getHeight() / nativeDim.getWidth();

            BufferedImage bi = rnd.getImage(new Dimension2DDouble(widthPx, heightPx));
            ByteArrayOutputStream bos = new ByteArrayOutputStream(100_000);
            ImageIO.write(bi, "PNG", bos);

            XWPFRun run = doc.createParagraph().createRun();

            int widthEmu = Units.pixelToEMU((int)widthPx);
            int heightEmu = Units.pixelToEMU((int)heightPx);
            XWPFPicture pic = run.addPicture(new ByteArrayInputStream(bos.toByteArray()), PictureData.PictureType.PNG.ooxmlId, "image.png", widthEmu, heightEmu);
            CTOfficeArtExtensionList extLst = pic.getCTPicture().getBlipFill().getBlip().addNewExtLst();
            addExt(extLst, "{28A0092B-C50C-407E-A947-70E740481C1C}"
                , "http://schemas.microsoft.com/office/drawing/2010/main", "a14:useLocalDpi"
                , "val", "0");

            addExt(extLst, "{96DAC541-7B7A-43D3-8B79-37D633B846F1}"
                , "http://schemas.microsoft.com/office/drawing/2016/SVG/main", "asvg:svgBlip"
                , "r:embed", addSVG(doc, svgFile));

            try (FileOutputStream fos = new FileOutputStream(outDocx)) {
                doc.write(fos);
            }
        }
    }

    private static void addExt(CTOfficeArtExtensionList extLst, String uri, String namespace, String name, String attribute, String value) {
        CTOfficeArtExtension ext = extLst.addNewExt();
        ext.setUri(uri);
        XmlCursor cur = ext.newCursor();
        cur.toEndToken();
        String[] prefixName = name.split(":");
        cur.beginElement(new QName(namespace, prefixName[1], prefixName[0]));
        cur.insertNamespace(prefixName[0], namespace);
        if (attribute.contains(":")) {
            prefixName = attribute.split(":");
            String prefix = prefixName[0];
            String attrNamespace = DEFAULT_XML_OPTIONS
                .getSaveSuggestedPrefixes().entrySet().stream()
                .filter(me -> prefix.equals(me.getValue()))
                .map(Map.Entry::getKey)
                .findFirst().orElse(null);
            cur.insertAttributeWithValue(new QName(attrNamespace, prefixName[1], prefix), value);
        } else {
            cur.insertAttributeWithValue(attribute, value);
        }
        cur.dispose();
    }

    private static String addSVG(XWPFDocument doc, File svgFile) throws InvalidFormatException, IOException {
        // SVG is not thoroughly supported as of POI 5.0.0, hence we need to go the long way instead of adding a picture
        OPCPackage pkg = doc.getPackage();
        String svgNameTmpl = "/word/media/image#.svg";
        int svgImageIdx = pkg.getUnusedPartIndex(svgNameTmpl);
        PackagePartName svgPPName = PackagingURIHelper.createPartName(svgNameTmpl.replace("#", Integer.toString(svgImageIdx)));
        PackagePart svgPart = pkg.createPart(svgPPName, PictureData.PictureType.SVG.contentType);

        try (FileInputStream fis = new FileInputStream(svgFile);
             OutputStream os = svgPart.getOutputStream()) {
            IOUtils.copy(fis, os);
        }
        PackageRelationship svgRel = doc.getPackagePart().addRelationship(svgPPName, TargetMode.INTERNAL, IMAGE_PART);
        return svgRel.getId();
    }
}

Comment: Thanks for your response. Have cloned the Project into my Eclipse. Please note, I am not an active developer. Can you please give me the steps for running this project?
Comment: As mentioned in the github readme, you need to install [gradle](https://gradle.org) and then use `gradle distZip` to create a zip file with all dependencies/jars. There's also shell script to show the invocation of the program.
Comment: Thanks for your time. For now, I am able to achieve my objective using the suggestion made by Yuri - using win32com. Will stick to it for now. Will contact you back if anything change on our side.


Expand width to the left and the right from center with css transition

Question: I want my navbar, which has a fix width and is centered, on page scrolling to expand left and right from its center. Currently it's just jumping to its new width.
I set up a demo which you can see what I'm trying to do:
http://codepen.io/anon/pen/Qyozvd
(Better look at the demo on codepen.)

$(document).ready(function() {

    // run test on initial page load
    checkSize();

    // run test on resize of the window
    $(window).resize(checkSize);

  $(".navbar-toggle").on("click", function () {
  $(this).toggleClass("navbar-toggle-fix");
 });

});

var header, logo, yPos, windowWidth, headerCollapse, mbsp;
function yScroll() {
    header = document.getElementById('header');
    logo = document.getElementById('logo');
    headerCollapse = document.getElementById('headerCollapse');
    mbsp = document.getElementById('mbsp');
    yPos = window.pageYOffset;
    windowWidth = $(document).width();

    if (yPos > 10) {

        header.style.height = "69px";
        $(headerCollapse).removeClass('container');
        $('#logo').addClass('LogoCollapse');
        $('.navbar').addClass('mb-navbarCollapse');

        if (windowWidth > 768) {

         //mbsp.style.height = "0px";

        }

        if (windowWidth < 768) {
        }

    } else {

        header.style.height = "186px";
        $(headerCollapse).addClass('container');
        $('#logo').removeClass('LogoCollapse');
  $('.navbar').removeClass('mb-navbarCollapse');

        if (windowWidth > 768) {

         //mbsp.style.height = "186px";
            logo.style.width = "137px"
            logo.style.height = "69px"
            logo.style.backgroundSize = "137px auto"

        }

        if (windowWidth > 1024) {

            logo.style.width = "160px"
            logo.style.height = "119px"
            logo.style.backgroundSize = "160px auto"

        }

        if (windowWidth < 768) {
        }

    }

}
window.addEventListener("scroll", yScroll);

//Function to the css rule
function checkSize(){
    if ($(".mqJquery").css("float") == "none" ){

  $(function() {
    var $el, leftPos, newWidth;
    var $mainNav = $(".nav-tabs");
    var activeItem = $(".nav-tabs .active")[0] ? $($(".nav-tabs .active")[0]) : null;
    var itemLinks = $(".nav-tabs li a");

    $mainNav.append("

");
    var $magicLine = $("#magic-line");

    if (activeItem) {
      $magicLine
        .width(activeItem.width())
        .css("left", activeItem.position().left)
        .data("orig-left", activeItem.position().left)
        .data("orig-width", $magicLine.width());
    } else {
      $magicLine.width(0);
    }

    itemLinks.hover(function() {
      $el = $(this);
      leftPos = $el.parent().position().left;
      newWidth = $el.parent().width();

      if (activeItem == null && $magicLine.position().left === 0) {
        $magicLine.css("left", leftPos + newWidth / 2);
      }

      $magicLine.stop().animate({
        left: leftPos,
        width: newWidth
      });
    }, function() {
      $magicLine.stop().animate({
        left: $magicLine.data("orig-left"),
        width: $magicLine.data("orig-width")
      });
    });
  });

    }
}

// ADD SLIDEDOWN ANIMATION TO DROPDOWN //
$('.dropdown').on('show.bs.dropdown', function(e){
  $(this).find('.dropdown-menu').first().stop(true, true).slideDown(500, "easeOutBounce");
});

// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
  $(this).find('.dropdown-menu').first().stop(true, true).slideUp(500, "easeOutBounce");
});
/* Basic styles */

@import url(https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic);

html {
  position: relative;
  min-height: 100%;
}

body {
 background-color:#cfcfcf;
 font-family: 'Roboto',Arial,Helvetica,sans-serif;
}

.mqJquery {
 float:left;
}

.clearfix {
 clear: both;
}

/* Headings */

h1 {}
h2 {}
h3 {}
h4 {}
h5 {}
h6 {}

/* Color Theme */

.mb-bg-red {
 background-color:#fd100a;
}

.mb-font-red {
 color:#fd100a;
}

.mb-bg-darkgrey {
 background-color: #3e3e3e;
}

.mb-red-grid-pattern {
 background-image: url('img/red-grid-pattern.png');
 background-repeat:repeat;
}

.mb-darkgrey-grid-pattern {
 background-image: url('img/darkgrey-grid-pattern.png');
 background-repeat:repeat;
}

/* Header styles */

header {
 background-image: url('img/header-pattern.png');
 border-top:4px solid #fd100a;
 width:100%;
 height:100px;
 transition: height 0.2s linear 0s, top 0.2s linear 0s;
    -webkit-transition: height 0.2s linear 0s, top 0.2s linear 0s;
 -webkit-background-clip: padding-box; /* for Safari */
 background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

/* Navbar responsive styles */

.navbar {
  margin-bottom: 20px;
}

.nav {
 margin-bottom: 15px;
}

.nav-tabs > li > a {
    border-radius: 0;
    color: #fff;
    font-size: 9pt;
    font-weight:500;
    -webkit-transition: background-color 150ms linear;
 -moz-transition: background-color 150ms linear;
 -o-transition: background-color 150ms linear;
 -ms-transition: background-color 150ms linear;
 transition: background-color 150ms linear;
}

.navbar .open .dropdown-menu > li > a:focus, .dropdown-menu > li > a:hover,
.nav .open > a, .nav .open > a:focus, .nav .open > a:hover,
.nav > li > a:focus, .nav > li > a:hover {
    background-color: #a41d1d;
    text-decoration: none;
}

.nav-tabs > li > a:hover {
    border-color: #eee #eee #ddd;
}

.nav-tabs > li {
    float:none;
}

.navbar-default,
.navbar-default .navbar-collapse, .navbar-default .navbar-form,
.nav-tabs {
    border-color: transparent;
}

.nav .open > a, .nav .open > a:focus, .nav .open > a:hover,
.navbar-default .navbar-toggle {
    border-color: #a41d1d;
}

.navbar-default .navbar-toggle .icon-bar {
    background-color: #a41d1d;
}

.navbar .open .dropdown-menu {
    background-color: transparent;
    border: 0 none;
    box-shadow: none;
    float: none;
    margin-top: 0;
    position: static;
    width: auto;
}

.navbar .open  .dropdown-menu > li > a {
 color:#fff;
}

.navbar .open .dropdown-menu .dropdown-header {
 color:#a41d1d;
}

.navbar .open .dropdown-menu .divider {
 background-color:#a41d1d;
}

.nav > li {
    display: block;
    position: relative;
}

.nav > li > a {
    display: block;
}

.navbar-default .navbar-toggle:focus, .navbar-default .navbar-toggle:hover {
    background-color: transparent;
}

 /* Animated navbar collapse icon */

 .navbar-toggle-fix {
  padding-left: 12px;
     padding-right: 8px;
 }

 .navbar-toggle .icon-bar {
     width: 22px;
     transition: all 0.2s;
     -webkit-transition: all 0.2s;
 }
 .navbar-default .navbar-toggle {
     position:relative;
     padding-top:10px;
     z-index:100
 }
 .navbar-toggle .top-bar {
     transform: rotate(45deg);
     -webkit-transform: rotate(45deg);
     transform-origin: 10% 10%;
     -webkit-transform-origin: 10% 10%;
 }
 .navbar-toggle .middle-bar {
     opacity: 0;
 }
 .navbar-toggle .bottom-bar {
     transform: rotate(-45deg);
     transform-origin: 10% 90%;
     -webkit-transform: rotate(-45deg);
     -webkit-transform-origin: 10% 90%;
 }
 .navbar-toggle.collapsed .top-bar {
     transform: rotate(0);
     -webkit-transform: rotate(0);
 }
 .navbar-toggle.collapsed .middle-bar {
     opacity: 1;
 }
 .navbar-toggle.collapsed .bottom-bar {
     transform: rotate(0);
     -webkit-transform: rotate(0);
 }

/* Content styles */

#content {
 margin-top: 50px;
}

/* Footer styles */

footer {
   position: relative;
   bottom: 0;
   width: 100%;
   height: 448px;
   background-color: #515151;
}

/* Layout styles */

#logo {
    background-image:url('img/logo.png');
 height: 67px;
 width: 90px;
    background-size: 67px auto;
    transition:all 0.4s;
    -webkit-transition:all 0.4s;
    -o-transition:all 0.4s;
    -moz-transition:all 0.4s;
    margin-top:7px;
 margin-bottom: 11px;
}

/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {

 .mqJquery {
  float:none;
 }

}

/* Medium devices (desktops, 992px and up) */
@media (min-width: 992px) {

}

/* Large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {

 /* Navbar styles */

 .navbar {
  height:64px;
  padding-left: 30px;
  padding-right:-30px;
     position: absolute;
     top: 150px;
     -webkit-transition: top 0.3s ease-in-out, width 0.3s ease-in-out;
     -moz-transition: top 0.3s ease-in-out, width 0.3s ease-in-out;
     -o-transition: top 0.3s ease-in-out, width 0.3s ease-in-out;
     -ms-transition: top 0.3s ease-in-out, width 0.3s ease-in-out;
     transition: top 0.3s ease-in-out, width 0.3s ease-in-out;
 }

 .container {
  -webkit-transition: width 0.5s ease-in-out;
     -moz-transition: width 0.5s ease-in-out;
     -o-transition: width 0.5s ease-in-out;
     -ms-transition: width 0.5s ease-in-out;
     transition: width 0.5s ease-in-out;
 }

 .mb-navbarCollapse {
  width: 100%;
  top:0px;
  background-color: #515151;
  background-image: url('img/darkgrey-grid-pattern.png');
  -webkit-transition: width 0.5s ease-in-out, top 0.5s ease-in-out, background-color 0.5s ease-in-out, background-image 1s ease-in-out;
     -moz-transition: width 0.5s ease-in-out, top 0.5s ease-in-out, background-color 0.5s ease-in-out, background-image 1s ease-in-out;
     -o-transition: width 0.5s ease-in-out, top 0.5s ease-in-out, background-color 0.5s ease-in-out, background-image 1s ease-in-out;
     -ms-transition: width 0.5s ease-in-out, top 0.5s ease-in-out, background-color 0.5s ease-in-out, background-image 1s ease-in-out;
     transition: width 0.5s ease-in-out, top 0.5s ease-in-out, background-color 0.5s ease-in-out, background-image 1s ease-in-out;
 }

 .mb-navbarCollapse .nav .open > a,
 .mb-navbarCollapse .nav .open > a:focus,
 .mb-navbarCollapse .nav .open > a:hover,
 .mb-navbarCollapse .nav-tabs > li > a:hover,
 .mb-navbarCollapse .nav > li > a:focus,
 .mb-navbarCollapse .nav > li > a:hover,
 .mb-navbarCollapse .nav-tabs > li.active > a,
 .mb-navbarCollapse .nav-tabs > li.active > a:focus,
 .mb-navbarCollapse .nav-tabs > li.active > a:hover {
     color: #f9131b !important;
 }

 .nav {
  margin-bottom: 0;
 }

 #magic-line {
     background: #3e3e3e none repeat scroll 0 0;
     top: 0px;
     height: 0.2em;
     left: 0;
     position: absolute;
     width: 100px;
 }

 .nav-tabs {
     border-bottom: 0 none;
 }

 .nav-tabs:hover {
     border-bottom: 1 none;
 }
 .nav .open > a, .nav .open > a:focus, .nav .open > a:hover,
 .nav-tabs > li > a:hover,
 .nav > li > a:focus, .nav > li > a:hover,
 .nav-tabs > li.active > a, .nav-tabs > li.active > a:focus, .nav-tabs > li.active > a:hover {
  border: 0;
  border-color: transparent;
     background-color: transparent;
     color: #3e3e3e;
     cursor:pointer;
     padding: 23px 16px;
     -webkit-transition: color 150ms linear;
     -moz-transition: color 150ms linear;
     -o-transition: color 150ms linear;
     -ms-transition: color 150ms linear;
     transition: color 150ms linear;
 }

 .nav > li > a {
     padding: 22px 15px;
 }

 .nav-tabs > li {
     float:left;
 }

 .navbar .open .dropdown-menu {
     background-clip: padding-box;
     background-color: #fff;
     border: 1px solid rgba(0, 0, 0, 0.15);
     border-radius: 4px;
     box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
     display: none;
     float: left;
     font-size: 14px;
     left: 0;
     list-style: outside none none;
     margin: 0;
     min-width: 160px;
     padding: 5px 0;
     position: absolute;
     text-align: left;
     top: 100%;
     z-index: 1000;
 }

 .navbar .open .dropdown-menu > li > a {
     color: #3E3E3E;
 }

 .navbar .open .dropdown-menu > li > a:hover {
     color: #fff;
 }

 /* Header style*/

 header {
  position: fixed;
  z-index: 1;
     height: 186px;

 }

 #headerCollapse {
  position: relative;
  -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
 }

 /* Content styles */

 #content {
  margin-top:20px;
 }

 /* Layout styles */

 #logo {
  height: 119px;
  width: 160px;
     background-size: 160px auto;
  margin-top:17px;
  margin-bottom: 21px;
 }

 .LogoCollapse {
  background-size: 64px auto !important;
     height: 48px !important;
     left: 25% !important;
     margin-top: 7px !important;
     position: absolute !important;
     width: 64px !important;
     z-index: 9999 !important;
 }

}
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="https://getbootstrap.com/favicon.ico">

    <title>Muth Bau</title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://mirsoftware.de/muthbau/css/jquery-ui.min.css" rel="stylesheet"/>

              <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                Toggle navigation

              </button>

HOME

ÜBER UNS

                  SERVICE

Action

Another action

Something else here

Nav header

Separated link

One more separated link

KONTAKT

IMPRESSUM

blabla beispiel text

This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

blabla beispiel text

This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

blabla beispiel text

This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

blabla beispiel text

This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

Place sticky footer content here.

Comment: warning: your codepen have a little typo: the html  tag is unclosed and it produces an error if the user download it as a zip file (because the appends like jquery come after it).
Comment: Thanks! I updatete it
Comment: "...which has a fix width and is centered" just to let you know: the bar isnt centered on my screen 1280x800, [screenshot](https://i.gyazo.com/d0ffc0065b030f435c6506bba3c64e1f.png).
Comment: if i remove `position: absolute;` and `top: 150px;` from `.navbar` the bar showsup in the center; but then it creates a new transition jump: now vertical.
Comment: [screenshot 2](https://i.gyazo.com/2b4176d7fb25565f8d910ac04cfa9b0c.png) 1280x800 now without `position: absolute;` and `top: 150px;` on `.navbar`.
Comment: thanks for your investment freestock.tk. But this was not the question. i can fix this later. But thank you
Answer: You are doing many changes on many elements at the same time for no reason. Use only one container to do all your animations, let's say #headerCollapse, use transitions and change it's properties just by adding the .container class.
#headerCollapse {
  transition: width 0.5s ease-in-out;
  position:relative;
}
#headerCollapse:not(.container){
  width:100%;
  height: 69px;
}
#headerCollapse.container{
  height: 186px;
}

That way, you have #headerCollapse animating from full width and 69px height to .container width and 186px height, just by adding .container class to it.
The next thing you want to do is to position .navbar in a such way that is always stuck to the bottom of #headerCollapse and expands to its width.
.navbar {
  position:absolute;
  left:0;
  right:0;
  bottom:0;
}


Finding adjoint operator $T:L^2((0,1))\rightarrow \mathbb{R}^2$

Question:
Find the adjoint operator of $T:L^2((0,1))\rightarrow \mathbb{R}^2$ $x\mapsto (\int^1_0sx(s)ds, \int^1_0s^2x(s)ds)$

My attempt was to look at $\langle Tf,g\rangle = \langle f, T^{\ast}g\rangle$
\begin{align*}
\langle Tf,g\rangle = \int_0^1 Tf(t)g(t)dt = \int^1_0 (\int_0^1 sf(s)ds,\int_0^1 s^2f(s)ds) g(t) dt
\end{align*}
I tried to proceed with integrating by parts but that just leads me to...
\begin{align*}
\int^1_0 (\int_0^1 sf(s)ds,\int_0^1 s^2f(s)ds) g(t) dt =\int^1_0 (F(1) -\int_0^1 F(s)ds, F(1)-\int^1_0 sF(s)ds) g(t) dt
\end{align*}
I don't think that's useful. I want to get to the form $\int_0^1 f(t) ... dt$ so that I can rewrite it to $\langle f, T^{\ast}g\rangle$.
Any suggestions?
Comment: Be careful, $Tf\in \mathbb R^2$ and not $L^2([0,1])$
Answer: You got the defintion of the adjoint wrong.
$T^{*}$ is an operator from the dual of $\mathbb R^{2}$ which can be identified with $\mathbb R^{2}$ itself into $L^{2}(0,1)$. $T^{*}(a,b) x=(a,b)Tx=a\int_0^{1} sx(s)ds+b \int_0^{1} s^{2}x(s)ds$. Hence $T^{*}(a,b)=as+bs^{2}$.
Comment: I see now. Thanks a lot!


Submit email form without page refresh NO JQUERY

Question: I am trying to make form that submits without a page refresh.  I cannot use jQuery to accomplish this.  I can't seem to find any solution anywhere that DOESN'T mention it, so I just want to know what I am doing wrong with what I have so far, and how I can fix it.
html
<form id="contactForm" name="contactForm" method="post" onsubmit="return validate(this);">
<fieldset>

Email Address<input class="text" id="email" name="email" size="30" type="text">

First Name<input class="text" id="firstName" name="firstName" size="30" type="text">

Last Name<input class="text" id="lastName" name="lastName" size="30" type="text">

Message<textarea cols="40"  id="message" name="message" rows="20"></textarea>

<input class="button" id="contactSubmit" name="submit" type="submit" value="submit">
</fieldset>
</form>

Ajax/JS
function observeEvent(target, eventName, observerFunction, useCapture){
    if (target.addEventListener) {
        target.addEventListener(eventName, observerFunction, useCapture);
    } else if (target.attachEvent) {
        target.attachEvent("on" + eventName, observerFunction);
    }
}

function start() {
    var xmlhttp = new XMLHttpRequest();
    var contentDiv = document.getElementById("success");

    xmlhttp.open("POST", "processor.php", true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            contentDiv.innerHTML=xmlhttp.responseText;
            alert('message sent!');
        }
    }
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
    xmlhttp.send("email=" + email +"&firstName=" + firstName + "&lastName=" + lastName + "&message=" + message);
}

observeEvent(window,"load",function() {
    var btn=document.getElementById("contactSubmit");
    observeEvent(btn,"click",start);
});

PHP for good measure
<?php

$fName = $_POST['firstName'];
$lName = $_POST['lastName'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = 'email@example.com';
$subject = 'the subject';
$message = 'FROM: ' . $fName . ' ' . $lName . ' Email: ' . $email . 'Message: '. $message;
$headers = 'From: ' . $to . "\r\n";

$mailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';

if (preg_match($mailRegex, $email)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
}

Comment: your email validation will fail a lot of valid email addresses
Answer: Got it!!!!
I wasn't giving any values to be sent from the form.  I fixed it by making my start() function look like this:
function start() {
    var xmlhttp = new XMLHttpRequest();
    var contentDiv = document.getElementById("success");

    var email = document.getElementById('email').value;
    var fName = document.getElementById('firstName').value;
    var lName = document.getElementById('lastName').value;
    var mes = document.getElementById('message').value;

    xmlhttp.open("POST", "processor.php", true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            contentDiv.innerHTML=xmlhttp.responseText;
            alert('message sent!');
        }
    }
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
    xmlhttp.send('email=' + encodeURIComponent(email) + '&firstName=' + encodeURIComponent(fName) + '&lastName=' + encodeURIComponent(lName) + '&message=' + encodeURIComponent(mes));

    return false;
}

I had tried to use the values from a validating function beforehand, but there was a scope issue related to that.  This works!!!  I'm a real programmer (sort of)!
Answer: The easiest way to do this is just to have an iframe in your document and hide it with CSS.  Give the iframe a name and then set a target attribute on your form which refers to your hidden iframe.
This will cause the form to post inside the hidden iframe and the whole page will not reload.
No javascript is even required.
If you need to process the result of the post, just use the onload event on the iframe to detect and process the output of the php page, which is now in the iframe.
Comment: Cool, but it actually NEEDS to use Javascript.
Answer: There two ways to fix it:

Expression in form onsubmit attribute should return false;
You should call event.preventDefault method in handler of form submit event or input[type="submit"] click event.
Comment: Try this `onsubmit="validate(this);return false;"` on form element
Comment: Also you can disable default behavior of submit button by calling event.preventDefault() in clickEvent handler