PHPExcel error while saving

Question: I'm using PHPExcel for exporting a report.
It's gave me an error when I run it on internet (using PHP 5.6)..
But, when I'm test on my localhost, it's fine. Works perfectly (using PHP 5.4.31)
Here's my code
function downloadExcelBrand($brand,$tglAwal,$tglAkhir)
{

    $this->load->library('php_excel');

    $objPHPExcel = new PHPExcel();
    // print_r($objPHPExcel);die();
    $objPHPExcel->setActiveSheetIndex(0);

    $objPHPExcel->getActiveSheet()->SetCellValue('A1', "Concept");
    $objPHPExcel->getActiveSheet()->SetCellValue('B1', $brand);

    $objPHPExcel->getActiveSheet()->SetCellValue('A2', "Period");
    $objPHPExcel->getActiveSheet()->SetCellValue('B2', $tglAwal." to ".$tglAkhir);

    $objPHPExcel->getActiveSheet()->SetCellValue('A5', "Boutique");
    $objPHPExcel->getActiveSheet()->SetCellValue('B5', "Q1");
    $objPHPExcel->getActiveSheet()->SetCellValue('C5', "Q2");
    $objPHPExcel->getActiveSheet()->SetCellValue('D5', "Q3");
    $objPHPExcel->getActiveSheet()->SetCellValue('E5', "Q4");
    $objPHPExcel->getActiveSheet()->SetCellValue('F5', "BBC Score");

    $data = $this->surveymodel->getDataLaporanBrand($brand,$tglAwal,$tglAkhir);
    // print_r($data);die();
    $i = 5;
    foreach ($data as $index=>$value) {
        // print_r($data[$index+1]);die();
        if( $index%4 == 0){
            $i++;
            // print_r($value["Score"]);print_r($value['TotalData']);die();
            $AvgQ1 = $value["Score"] / $value['TotalData'];
            // print_r($AvgQ1);die();
            $AvgQ2 = $data[$index+1]["Score"]/$data[$index+1]['TotalData'];
            $AVGQ3 = $data[$index+2]["Score"]/$data[$index+2]['TotalData'];
            $AvgQ4 = $data[$index+3]["Score"]/$data[$index+3]['TotalData'];
            $BSC = $AvgQ1+$AvgQ2+$AVGQ3+$AvgQ4;

            $objPHPExcel->getActiveSheet()->SetCellValue('A'.$i, $value["boutiqueID"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('B'.$i, $AvgQ1);
            $objPHPExcel->getActiveSheet()->SetCellValue('C'.$i, $AvgQ2);
            $objPHPExcel->getActiveSheet()->SetCellValue('D'.$i, $AVGQ3);
            $objPHPExcel->getActiveSheet()->SetCellValue('E'.$i, $AvgQ4);
            $objPHPExcel->getActiveSheet()->SetCellValue('F'.$i, $BSC);
        }
    }

    // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
    $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
    // Write the Excel file to filename some_excel_file.xlsx in the current directory
    header('Content-type: application/vnd.ms-excel');
    // It will be called file.xls
    header('Content-Disposition: attachment; filename="Report_By_Brand.xlsx"');
    // Write file to the browser
    $objWriter->save('php://output');
}

the weird things happen when I remove the $objWriter->save('php://output'); code. It's asking for saving the excel, but the excel file can't be open because it's corrupted..
*EDIT

The error is
This site can't be reached
The webpage at http://my-link-in-here might be temporarily down or it may have moved permanently to a new web address.
ERR_INVALID_RESPONSE

*UPDATE

I try to add ob_end_clean(); or ob_clean(); before $objWriter->save('php://output'); and it saving the Excel, but I can't open it because Excel says "File Format or File Extention is not valid".
I try to change the xlsx extension to xls on filename properties, and the Excel now can be opened. But It shows php error Message:  ob_end_clean(): failed to delete buffer. No buffer to delete
I try to keep the extension but I deleted the ob_end_clean();, and the error comes again..

*Solution :

I changed the code to be Excel5 like this
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="userList.xls"');

And it works like champion. Anyone can make a explanation ? I will give the solution to the one who can make the explanation
Comment: what does the error says?
Comment: here's the error @Beginner `This site can't be reached The webpage at http://the-link-in-here might be temporarily down or it may have moved permanently to a new web address.
ERR_INVALID_RESPONSE`
Comment: I can't provide an explanation: but perhaps if you looked in your log files, or opened the file generated in a text editor to see if it contained any error messages, it might provide you with an explanation
Comment: The generated file that can't be opened ? I have by changed the extension to `xls` and open it using excel. It shows php error `Message:  ob_end_clean(): failed to delete buffer. No buffer to delete` @MarkBaker
Comment: So remove the `ob_end_clean()`
Comment: yap. you're right sir @MarkBaker but, when I remove `ob_end_clean()`, the page is not working and error like the first problem
Comment: Perhaps if you looked in your log files, or opened the file generated in a text editor to see if it contained any error messages, it might provide you with an explanation.... I can't guess (though obvious possibilities include timeout or memory issues), but you can check
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/134683/discussion-between-m-argus-chopin-gyver-and-mark-baker).
Comment: Check that you have PHP's zip extension installed and enabled
Comment: Did you mean archives zip extension @MarkBaker ?
Comment: The OfficeOpenXML format is a collection of XML files wrapped in a zip archive, so it needs PHP with the [zip extension](http://php.net/manual/en/book.zip.php)
Comment: I'm never used any stuff like that before. All I do just upload my program and code.. Can you give me more clues @MarkBaker ?
Comment: Open the file in a text editor and see if there's any plaintext error messages inside that file
Answer: Try install ZipArchive Class i.e sudo apt-get install php7.0-zip
as it might be the problem for newly formed server.(It was for me)
Comment: it is an answer for the above problem @wayneOS
Comment: That should be a comment.
Comment: Can confirm this works on 7.4. Worth noting that as per [one of the maintainer's own comment](https://github.com/phpoffice/phpexcel/issues/716#issuecomment-414599543), officially they do not support >=7.1.
Answer: I found a fix,go to Classes/PHPExcel/Writer/Excel2007.php comment out the following lines, php 7 has a wierd return date type so doing this will enable php excel to work in php 7 pronto. any way
$saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);

to
//$saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
//PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
//PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);

worked for me.
Comment: Thanks this worked for me. I'm on php7, may be for below versions ob_end_clean will work.
Comment: tnx, you saved my night :-) btw. I'm on php7.2
Answer: Saving the $writer output to a file and redirecting to it solved my problem
I also set the time limit and memory limit high so that they don't cause any problem
Code:
        $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); // instantiate Xlsx
        $writer->setPreCalculateFormulas(false);
        //ob_end_clean();
        set_time_limit(500);
        ini_set('memory_limit', '-1');
        $writer->save($filename . ".xlsx"); // save the file to root of project
        redirect('/' . $filename . ".xlsx"); // redirect the user to the file

Answer: Add  ob_end_clean()
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="Filename.xlsx"');
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
    ob_end_clean();
    $objWriter->save('php://output');
    exit;

Comment: adding `ob_end_clean()` is removing the error and allow the file to be downloaded. But the downloaded file is still can't be opened. It's says, format or file extenstion is not valid
Comment: What if you change
     `header('Content-type: application/vnd.ms-excel');`
to
   `header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');`
Comment: Still can't open the file. And it still say the same error @Jordan Sipahutar http://imgur.com/a/ehsT6
Comment: You need to ensure that the file extension that you provide matches the writer, and matches the content type header
Comment: Is there's any wrong code on the header properties from the code that I wrote on the top ?? @MarkBaker ?? I don't understand why this is error on the hosting. Because on my localhost it work perfectly
Comment: I update the question. any changed that I apply to my code have diff effect. But none of them are my solution @MarkBaker
Answer: I had same problem with 4000+ rows. Increasing both memory limit and time limit fixed the problem.
Reason for ERR_INVALID_RESPONSE behavior is that you send xls/x headers but then http error 500 from running out of memory or time.
set_time_limit(120);
ini_set('memory_limit', '256M');
...
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');
exit;

PHPExcel error while saving


NodeJS and HTML DOM not loading Image Background

Question: i'm working on an Image Upload System and I want, that the DIV with the Upload Form shows the Uploaded Image.
Everything works fine, the Image is uploaded and the  gets the background-image-path, but it does not show the Background Image, it stays white.
Can you tell me why? Here's my Code:
Server sends
data = 'http://22.214.171.124:1111/images/xxxxx.jpg'

Client.js
success: function(data) {
    var imagemaster = document.getElementById('bilduploadimage2') //get DIV
    imagemaster.style.backgroundImage = 'url('+data+')' //set BG Image
    imagemaster.style.backgroundSize = 'cover'
  }

Chrome inspect Element gives:

Image Path is working, when I put it in Browser address, but no Image is shown.
Thanks for your help.
Edit:
Also tried with:
imagemaster.style = 'background-image: url(' +data+ '); width: 200px; height: 200px; background-size: cover'

Image loads only half.
PS.: Sorry for my bad English, I'm German.
Comment: Look at what you write for the Chrome inspect. You have style = "" but inside of your style, you're also using quotes, which end the style attribute. If you had single quotes for your url, it would probably work.
Comment: I think it was just a wrong output of Chrome inspect. Single quotes doesn't change anything..
Answer: you need to use background-size:contain in below code.
imagemaster.style = 'background-image: url(' +data+ '); width: 200px; height:
200px; background-size: cover'

to see full image you can also bootstrap image class to resize image automatically according to div size.
Comment: The div already has a backgroundImage and the size width 200px and height 200px
Answer: Your div has height & width ?
check this:
html

css
#image {
  width: 272px;
  height: 92px;
}

js
(function () {
   var img = document.getElementById('image')
   image.style.backgroundImage =   'url(https://www.google.com.hk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png)'
  image.style.backgroundSize = 'cover'
})()

If the div#image has no height & width, the background-image is don't display.
Comment: Tested it.. with the google link it works, when I set the data Image, it only loads half of the Image. When I copy the Link from Chrome Inspect, the file loads completely.. Inspect says "Image corrupt or truncated.", but the File is ok.
Comment: I Really have to say, i don't know. The File Upload works with the Module "Formidable" and "Multer". The Files are all in ".jpg" Format.


Phonegap build for different versions of android

Question: I want to build my phonegap project for specific versions for android, like android 4.4 ( Kitkat ), 5.0 (Lollipop) and lower versions too.
phonegap build

On running build command, it builds for the api level of sdk currently being used.
What command should I run or what settings should I make so as to get version specific builds?
Answer: You should edit the AndroidManifest.xml
<uses-sdk android:minSdkVersion="integer"
          android:targetSdkVersion="integer"
          android:maxSdkVersion="integer" />

minSdkVersion is the minimum API Level required for the application to run.
maxSdkVersion is the maximum API Level on which the application is designed to run.
targetSdkVersion is the API Level that the application targets.
The accepted answer proposes the use of project.properties target, but that is for specifying the SDK used to compile the app, but you shouldn't do that, you should always use the latest installed and change the values on the AndroidManifest.xml
Comment: Thanks, this also works fine. I had previously tried this but I was setting only `android:minSdkVersion`
Answer: In your phonegap project folder, navigate to platforms/android/. Open the project.properties for editing.
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.

target=android-19
android.library.reference.1=CordovaLib

Change the target = android-16 for android version 4.1, target = android-19 for android 4.4, target = android-21 for android 5.0.
Now when you build you will get android version specific builds.
[Note : You need to have the respective api installed. You can open android adk manager by running android, and download the packages.]
Comment: This works perfectly fine. Though installing packages was a bit time consuming.


Show that $\text{Var}[N]\approx cn^2$ for large $n$.

Question:
Consider coupons numbered $1, 2, ..., n,$ which you collect until you
have all numbers. Each time you get a coupon, its number is
independent of previous numbers and all numbers are equally likely.
Let $N$ be the number of coupons you need, and show that
(a) $\mathbb E[N] = n\sum^n_{k=1}\frac{1}{k} \sim n\log n$ for large $n$,
(b) there is a constant c such that $\operatorname{Var}[N] \sim cn^2$ for large $n$. What is $c$?

The problem (a) is already solved in another post, I just included it in case it's needed to be referred to in order to solve (b).
Attempt: We know that
$$\text{Var}[N]=\text{Var}[X_1+X_2+...+X_n]=\text{Var}[X_1]+\text{Var}[X_2]+...+\text{Var}[X_n].$$
From (a) we got that $X_k\sim \text{geom}(\frac{n-k+1}{n}).$ This means that
$$\text{Var}[X_k]=\frac{1-\frac{n-k+1}{n}}{\left(\frac{n-k+1}{n}\right)^2}=\frac{(1-k)n}{n-k+1}.$$
And finally
$$\text{Var}[N]=n\sum_{k=1}^n\frac{1-k}{n-k+1}.$$
Here I'm stuck. I'm not even sure that this is correct because the sum seems quite hard to evaluate.
Answer: You haven't simplified the variance of $X_k$ properly: it should be
$$ \frac{(k-1)n}{(n-k+1)^2} = \frac{n^2}{(n-k+1)^2} - \frac{n}{(n-k+1)}. $$
Then
$$ \frac{\operatorname{Var}{[N]}}{n^2} = \sum_{k=1}^n \frac{1}{(n-k+1)^2} - \frac{1}{n(n-k+1)} = \sum_{r=1}^n \frac{1}{r^2} - \frac{1}{nr}, $$
putting $k=n-r+1$. The first term converges to $\pi^2/6$, while the second term is $\sim -(\log{n})/n$ by comparing with an integral.
Comment: Thank you. But how did you split the first fraction into two partial fractions?
Comment: $$ \frac{k-1}{(n-k+1)^2} = \frac{-(n-k+1)+n}{(n-k+1)^2} $$


Why not directly brute force sparsify the OLS estimator instead of using Lasso?

Question: I have a question about the Lasso estimator. I understand that it is particularly useful in high-dimensional settings due to its sparsity-inducing properties.
For instance, if the design matrix is orthogonal, it is known that applying Lasso is essentially equivalent to performing Ordinary Least Squares (OLS). In this case, one sets to zero all components of the OLS estimator that fall below a certain threshold and finally introduces a slight bias to the remaining components.
However, why can't this strategy be used in the non-orthogonal case? In this scenario, could we not simply perform OLS and then zero out all components of the OLS estimator that are not sufficiently large?
From an intuitive perspective, if a component of the OLS estimator is small, it suggests that the corresponding covariate is not particularly influential. Hence, it seems reasonable to set it equal to zero.
Any help would be much appreciated!
Comment: The problem is that your intuition is incorrect.  Nonorthogonality is equivalent to being unable to assign at least some parameters ("component of the OLS estimator") uniquely to an explanatory variable.  One way to develop a better intuition is to study such situations closely.  Another is to study the implications of the OLS equations.  You can find [many posts here on CV with such material](https://stats.stackexchange.com/search?tab=votes&q=multiple%20regression%20significan*&searchOn=3). Other searches for "interaction," "mediation," "moderation," and "multicollinearity" will help too.
Comment: Also, and separately from @whuber's point, sparsifying the OLS estimator is *not actually easier or faster* than doing lasso.
Comment: Thresholding can be a great idea, just not necessarily to OLS; see e.g. https://arxiv.org/pdf/2009.08071.pdf
Comment: Thank you a lot for your comment, I have understood what I was missing.
Comment: Interesting remarks, thank you!
Answer: First, LASSO lets you pick a value for small based on cross validation.
Second, LASSO does that adjustment.
Simply dropping a variable will result in a big bias.
Statology offers a nice example using the mtcars data.
set.seed(1234)

#Start of statology code
y <- mtcars$hp

#define matrix of predictor variables
x <- data.matrix(mtcars[, c('mpg', 'wt', 'drat', 'qsec')])

install.packages("glmnet")
library(glmnet)

#perform k-fold cross-validation to find optimal lambda value
cv_model <- cv.glmnet(x, y, alpha = 1)

#find optimal lambda value that minimizes test MSE
best_lambda <- cv_model$lambda.min
best_lambda

#produce plot of test MSE by lambda value
plot(cv_model)

best_model <- glmnet(x, y, alpha = 1, lambda = best_lambda)
coef(best_model)

#end of statology code
m1 <- lm(y~x)
m1

The coefficients through LASSO were
(Intercept) 477.905338
mpg          -3.102593
wt           19.252832
drat          .
qsec        -18.534966

Through lm:
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  473.779    105.213   4.503 0.000116 ***
xmpg          -2.877      2.381  -1.209 0.237319
xwt           26.037     13.514   1.927 0.064600 .
xdrat          4.819     15.952   0.302 0.764910
xqsec        -20.751      3.993  -5.197 1.79e-05 ***

Note that 1) The coef for drat is the smallest in terms of absolute value of t. 2) Since the mean of drat is 3.60, if you just drop drat you will be deducting an average of $4.81\cdot3.60 = 17.4$ from each predicted value. 3) LASSO adjusts the other coefficients by fairly substantial amounts, but it does not adjust the intercept by much.
Of course, you could run
x2 <- data.matrix(mtcars[, c('mpg', 'wt',  'qsec')])
m2 <- lm(y~x2)
m2

which gives
 (Intercept)        x2mpg         x2wt       x2qsec
     494.57        -2.70        25.04       -20.97

which is quite different from the LASSO results.
Comment: Thank you for the nice example, it helped me to build intuition and understand the problem.


Is mathematics done in an arbitrary model of ZFC?

Question: Following up a previous thread I posted, I have tried to refine my questions. I would be happy with answers simply confirming that I have understood matters correctly, but of course I would also be happy to read longer and more elaborate answers!
Suppose I want ZFC (as formulated in first-order logic) to be my foundations of mathematics, i.e. I want it to be possible to formalise all of my reasoning about for example number theory as consequences in first-order logic of the ZFC axioms.
These are my questions:

When I consider a "set", for example $\mathbb{N}$, when doing mathematics, is it reasonable to view $\mathbb{N}$ as living in a fixed model of ZFC? So if I wanted to be very pedantic, I would refer to $\mathbb{N}$ as $\mathbb{N}^\mathcal{A}$ where $\mathcal{A}$ is my fixed model of ZFC?
Suppose I am doing mathematics and discussing properties of $\mathbb{N}$ with a friend of mine. Can any "problems" arise from me (implicitly) thinking of $\mathbb{N}$ as being $\mathbb{N}^\mathcal{A}$ living in my ZFC-model $\mathcal{A}$, while my friend thinks of $\mathbb{N}$ as being  $\mathbb{N}^\mathcal{B}$ where $\mathcal{B}$ is his ZFC-model? I suppose since all assumptions we have made about $\mathcal{A}$ and $\mathcal{B}$ is that they are ZFC-models, no "substantial" problems can arise, so my friend and I can therefore safely agree to ease notation by referring to $\mathbb{N}^\mathcal{A}$ and $\mathbb{N}^\mathcal{B}$ as simply $\mathbb{N}$?
Given that my understanding of the above questions is correct, it seems reasonable to view mathematics in a "semantic" way as "being done in an arbitrary model of ZFC"? Alternatively, if I insist on first-order logic ZFC to be my foundations, I could view doing mathematics as a sort of informal natural deduction, i.e. I could have a "syntactic" view on mathematics. The soundness and completeness theorems ensure that the "semantic" and "syntactic" views in some sense are the same, but perhaps one of the approaches has some philosophical advantages? I obviously find the semantic view more pleasing, since the semantic view is "consistent" with my view of a sets as living in models of ZFC...

Thanks in advance!
Edit:
I realise that perhaps "the standard model of ZFC" might be relevant to my questions. That is, I should perhaps view $\mathbb{N}$ as always referring specifically to $\mathbb{N}^\mathcal{S}$ where $\mathcal{S}$ denotes the standard model of ZFC? Similarly, I should perhaps also view mathematics as being done specifically in the standard model of ZFC. If we disregard problems with even defining which model of ZFC is the standard one, this view also seems to give us problems with translating our informal mathematical proofs to natural deduction: If mathematics is done in a very specific model of ZFC, we can no longer rely on completeness of first-order logic to guarantee existence of a derivation in natural deduction.
To summarise my edit: If the standard model of ZFC is relevant to my questions, please illuminate how. I do not think the standard model is relevant for my questions in any other way than being an "intuitive model" when thinking of ZFC.
Comment: You should read Benecerraf's delightful paper "What numbers could not be" (which will show you that even the definition of $\Bbb{N}$ within a given formalization of set theory is a nuanced question).
Comment: I believe soundness means that if your proofs boil down to formal proofs with ZFC axioms alone, the only conclusions you can draw are those true in all models, so it shouldn't matter what model you're thinking of. But if you're thinking only of a model where CH holds, and you want to make use of CH, then you're not "working in ZFC" anymore, but ZFC+CH instead.
Comment: Just wondering ... what if your friend said that he looked at the natural numbers as urelements - would you refuse to discuss math with him?
Comment: It is a good thing you have at least a ZFC mindset. Otherwise some set theory purists would be pouncing on your question with down votes and going for eventual deletion.
Comment: @MikeMathMan If we were actually solving some math problem, I would happily treat the natural numbers as urelements. However, I would also like to feel safe about my foundational questions, to know "what's going on in the background" :)
Answer: Modern maths avoids hazards like Russel's paradox by making the assumption

There exists a model of ZFC

Given this one model we can construct other models with different properties. For example we can construct a model $\mathcal A$ where the Continuum Hypothesis holds and another $\mathcal B$ where it doesn't hold. So if are doing maths over $\mathcal A$ and your friend is doing maths over $\mathcal B$ it is true for you that $\aleph_1= 2^{\aleph_0}$ but not for your friend.
The solution is, rather than imagine you are working over an arbitrarily chosen model, to imagine you are working over ALL models of ZFC at once. When you say  $1+1=2$ you do not mean $1^\mathcal A+1^\mathcal A=2^\mathcal A$ for your favourite model $\mathcal A$. You mean $1^\mathcal A+1^\mathcal A=2^\mathcal A$ for each and every model $\mathcal A$.
An alternate approach might be to try and define a standard model as one which obeys all the axioms of ZFC and does not have any additional sentences that could be added as axioms, and do your maths there. This avoids the continuum problem above. However it is impossible because we can take any non-axiom sentence $P$. Either $P$ or $\neg P$ will hold in the model. Therefore it is also a model of either $ZFC + P$ or $ZFC + \neg P$.
Another alternative would be to try and find a minimal model by somehow taking the intersection of all possible models. This cannot be done as our ultimate assumption does not assume there is some larger space where all the models coexist.


Difference between linear projection and linear regression (OLS)

Question: In this note (approximately from page 7 to 13), ordinary least squares and linear projection are said to be different. But from my linear algebra class, I remember hearing that OLS is indeed projection method. So I am confused here.
What exactly is the difference between these two?
Comment: linear projection refers to the population quantities, while OLS looks at sample quantities
Answer: OLS, conditional expectation and linear projection are all related. It helps to distinguish between the unknown data generating process (the model) and procedures to estimate the parameters of that model.
Let this be model/data generating process. $f$ is some unknown function.
$$y_i = f(x_i, \theta) +\epsilon_i,$$
$$E[x_i\epsilon]=0$$
We could use OLS, and regress $y_i$ on vector $x_i$. The OLS estimator is defined to be the vector $b$ that minimises the sample sum of squares $(y-Xb)^T(y-Xb)$ ( $y$ is $n \times 1$, $X$ is $n \times k$ ).
As the sample size $n$ gets larger, $b$ will converge to something (in probability). Whether it converges to $\beta$, though, depends on what the true model/dgp actually is, ie on $f$.
Suppose $f$ really is linear. Then
$y_i = x_i^T\theta +\epsilon_i$ and $E[y_i|x_i]=x_i^T\theta$ and $b$ converges to $\theta$.
What if $f$ isn't linear? $b$ still converges to something, the thing it always converges to: the linear projection coefficient.
What is a linear projection? It is the population equivalent of the OLS estimator. The vector $\beta$ that minimises $E[ (y_i-x_i^T\beta)^T (y_i-x_i^T\beta)]$. Regardless of what the true relation between y and x is, this vector exists and OLS converges to it.
In the special case where the conditional expectation is linear, $\theta$ and $\beta$ are the same, and OLS recovers the conditional expectation function for you as the sample grows. If that function is not linear, OLS recovers just the linear projection coefficient for you, which could still be useful, because it is the mean square error minimising linear approximation of the conditional expectation function.
Answer: The Y-hats are obtained by projecting Y onto the column space of X:
\begin{equation*}
\hat{\beta} = \left(X^\prime X \right)^{-1} \, X^\prime Y
\end{equation*}
\begin{equation*}
\hat{Y} = X \hat{\beta} = X\,\left(X^\prime X \right)^{-1} \, X^\prime Y = P\,Y
\end{equation*}
where
\begin{equation*}
P \equiv X\,\left(X^\prime X \right)^{-1} \, X^\prime
\end{equation*}
is a projection matrix in the linear algebra sense.
I'm using $\hat{\beta}$ as the estimated coefficient vector in OLS, and $\hat{Y}$ as the fitted values.
Comment: Could you clarify the connection between your projection matrix and the definition of "linear projection" in the link provided in the question? That reference states, "The *linear projection* of $y$ on $x$ is the function $\hat{E}[y|x]=a+Bx$ [where] $a$ and $B$ are chosen to minimize $\mathbb{E}(tr((y-a-Bx)(y-a-Bx)^\prime))$." (I fixed some sign errors in that formula.) It goes on to give a formula "$\hat{E}[y|x]=\mu_y+\Sigma_{yx}\Sigma^{-1}_{xx}(x-\mu_x)$." (The $\mu$ are means and the $\Sigma$ are covariances.) Note that this reference asserts your OLS solution is *not* linear projection.
Comment: @whuber Could you please elaborate more on how's linear project is different from linear regression?
Comment: @symphony001 The reference appears to have changed substantially in the intervening 7+ years.  Its characterization is actually an *affine* projection.  It can be understood as a linear projection by enlarging the vector space spanned by the columns of $x$ to include all multiples of the vector $(1,1,\ldots, 1),$ which is implicitly done in the present answer.  Thus, my comment was not suggesting this answer is incorrect, but was pointing out there is a bit of a mismatch between it and the reference it offered, which readers might find confusing.
Answer: As an addition to @CloseToC's answer: Even if the DGS f is linear, there's a significant difference between linear projection and OLS. OLS requires that the error term, $\epsilon_i$, is uncorrelated with each of the independent variables. It guarantees the consistency of coefficient estimates. However, linear projection does not require that. Even if this assumption fails, i.e., some independent variables are endogenous, linear projection still exists (guaranteed by the Projection Theorem). By the way, one way to fix the OLS, in this case, is to use an instrumental variable.


Group by and aggregate the columns in pandas dataframe

Question: I have following dataframe which I would like to group by a certain column and aggregate the uniques values in other column of respective row by a separator like ' | '. Below is the sample rows:
col1                                                col2            col3                col4
THREE M SYNDROME 1  {3-M syndrome 1, 273750 (3)}    3-m syndrome 1  {3-M syndrome 1}    273750
THREE M SYNDROME 1  {3-M syndrome 1, 273750 (3)}    3-m syndrome 2  {3-M syndrome 2}    273750

I would like to group by 'col1' and aggregate the other unique values. The expected df is:
col1                                                col2            col3                       col4
THREE M SYNDROME 1  {3-M syndrome 1, 273750 (3)}    3-m syndrome 1 | 3-m syndrome 2 {3-M syndrome 1} | {3-M syndrome 2} 273750

I am using following lines of code.
join_unique = lambda x: ' | '.join(x.unique())
df2= df.groupby(['preferred_title_symbol'], as_index=False).agg(join_unique)

I get output but col4 is not included in the output.
col1                                                col2            col3
THREE M SYNDROME 1  {3-M syndrome 1, 273750 (3)}    3-m syndrome 1 | 3-m syndrome 2 {3-M syndrome 1} | {3-M syndrome 2}

Any help is highly  appreciated.
Comment: As you have a non-canonical DataFrame, please provide a constructor for clarity
Answer: It could be because col4 contains integers, therefore the join doesn't work. You could try with an if/else like this:
data = {'col1': {0: 'THREE M SYNDROME 1  {3-M syndrome 1, 273750 3)}',
  1: 'THREE M SYNDROME 1  {3-M syndrome 1, 273750 (3)}'},
 'col2': {0: '3-m syndrome 1', 1: '3-m syndrome 2'},
 'col3': {0: '{3-M syndrome 1}', 1: '{3-M syndrome 2}'},
 'col4': {0: 273750, 1: 273750}}

df = pd.DataFrame(data)

>>> df.groupby('col1').agg(lambda x: ' | '.join(x.unique()) if x.nunique()>1 else x.unique()[0]   )

Out:

                                                col2    col3    col4
col1
THREE M SYNDROME 1 {3-M syndrome 1, 273750 (3)} 3-m syndrome 1 | 3-m syndrome 2 {3-M syndrome 1} | {3-M syndrome 2} 273750


Counting the Number of Reps From a Rep Height

Question: I'm trying to calculate the number of reps from a rep height.
Example #1
Input: n = 2
Output: Result = 6
Because 1+2+2+1 = 6
--
Example #2
Input: n = 3
Output: Result = 12
Because 1+2+3+3+2+1 = 12
What formula could I use to get from input to output?
Answer: My way before is unnecessarily long. When you add $(1 + 2 + \dots + n) + (n + (n-1) + \dots + 1)$, line up the pairs $(n, 1)$, $(2, n-1)$, $(3, n-2)$, and you'll notice that they all sum to $n+1$. Since you have $n$ pairs, the sum is $n(n+1)$.
Comment: Now I just have to figure out how to read this. :)
Thank you Taisuke.
Answer: Let the 'output' be $S_n$. Then
$$S_n=1+2+...+n+n+(n-1)+...+1$$
$$=2(1+2+...+n)$$
(formula for triangular numbers)
$$=2\left(\frac{n(n+1)}{2}\right)$$
$$=n(n+1)$$


How to get the alt tag from an image field in twig?

Question: I have a page of field images which are coming out quite weirdly when I kint their values. I can't seem to get the image url and the alt tag.
The code in the twig file looks like this:
field--field-staff-gallery.html.twig
{% for item in items %}
    {{ kint(item) }}
{% endfor %}

It's output looks like this:

Now I can easily get to the url by doing:
{% for item in items %}
    {{ file_url(item.content['#markup']) }}
{% endfor %}

So how can I get the alt tag?
Answer: You can get the alt of image with:
item.content['#item'].value.alt

Comment: as you can see from the output above I don't seem to have the `#item` output on this field
Comment: In the field twig there is two foreach one for multiple and other for no multiple fields, and also check your field display settings from *admin/structure/types/manage/YourContentType/display* i have Image as formatter not url to image, what you have ?
Comment: ah, ok so that worked. i changed it to image. it was on url to image. not to be a bother, but how do I then get the url from this? `item.content['#url']` is `NULL`
Comment: The single field #item is only added by the image field formatter, but the field items `element['#items']` are added for all field formatters. For a single value field it doesn't matter and you can use both, for a multi value field you need to add a key to the loop to access each item.


Smart-cast and comparison inside When Expression after 'is' type-check

Question: According to the documentation for When Expression, it can replace "if-else if", so I tried implementing a function to return maximum of two variable of Any type:
fun maxOf(a: Any, b: Any) = when {
    a is Int && b is Int        -> if (a  if (a  if (a  if (a  if (a  null
}

The above implementation works but I thought it could be more concise:
fun maxOf(a: Any, b: Any) = when {
    (a is Int || a is Double) && (b is Int || b is Double) -> if (a  if (a  null
}

But I failed because the second implementation doesn't work; the error is in the first occurrence of if (a < b):

Unresolved references.
None of the following candidates is applicable because of receiver type mismatch
• public fun String.compareTo(other: String, ignoreCase: Boolean =...): Int defined in kotlin.text

Is this because smart-cast is not capable of casting a and b to their actual types after evaluating the expression (a is Int || a is Double) && (b is Int || b is Double)? Or am I missing something?
Update
The same error happens even if the type of a and b is changed to Number:
fun maxOf(a: Number, b: Number) = when {
    (a is Int || a is Double) && (b is Int || b is Double) -> if (a  null
}

Comment: why are you not using Comparable?
Comment: @njzk2 Could you be a bit more specific?
Comment: nvm, that wouldn't work for comparing ints to doubles
Answer: Why this happen?
It's not a problem of when expression. You should blame on the type system.
a and b are instance of Int and Double, so Kotlin will infer them as their LCA. For example:
open class A { fun a() = println("meow meow meow") }
class B : A()
class C : A()
if (a is B || a is C) a.a() // smart cast works

However, Int and Double are subclasses of Number and Comparable at the same time, and Kotlin doesn't know if you want a Number or a Comparable, so Kotlin treat it as an instance of Any.
if (a is Int || a is Double)
  if (a > 1) print("meow meow") // smart cast doesn't work

This is why the "bug" appears.
How to fix this?
 Use your original code, or use explicit cast (I know it sucks, but it is really an unavoidable problem).
I've came up with a beautiful solution! Look at it:
fun <T : Comparable<T>> maxOf(a: T, b: T): T? = when {
    (a is Int || a is Double) && (b is Int || b is Double) -> if (a  if (a  null
}

And in this way, you can apply any Comparable to it (instead of Int, Double and String only)!
fun <T : Comparable<T>> maxOf(a: T, b: T): T = if (a < b) b else a

Your original version will return null if input is invalid, and this version will raise compilation error if input is invalid, helping you find error at compile time.
Mention!
You've commented me and asked a further question. I want to make my reply more readable so I'll add it to my answer.
fun someFunction(a: Number) {
    if (a is Int || a is Double) println(a < 1) // still error! Why?!
}

Yeah, indeed, a is an instance of Number here.
But please do mention, <, or, compareTo, is not declared in Number. It's in Int or Double :).
Edit 2
You said:

using generics forces a and b to be the same type.

So try this:
fun <A : Comparable, B : Any> maxOf(a: A, b: B): Any = if (a < b) b else a

And you said:

explicit cast is not a solution if the type of a and b is Any

solution zero: create operator fun Any.compareTo
solution one: Give up casting.
Comment: "`Int` and `Double` are subclasses of `Number` and `Comparable`... Kotlin treat it as an instance of `Any`.", mentioned in your answer.

But if I enforce `a` to be a `Number`, the following still doesn't work: `fun printMeow(a :Number) { if (a is Int || a is Double) if (a > 1) print("meow") }`

So I'm not quite sure if that's true.
Comment: Edited and answered your question.
Comment: Hey! I've just came up with an extremely beautiful solution, please take a look! I feel super smart now :D
Comment: Well at least smart-cast is smart enough to know type `T` is the same as `T` and perform the comparison.
Comment: It's not smart cast's job. It's generics'.
Comment: interesting that all children of Number implement Comparable, but Number does not...
Comment: I think you're solution is useful to know but is not the solution to my problem. REASON: 1) using generics forces `a` and `b` to be the same type. 2) explicit cast is not a solution if the type of `a` and `b` is `Any` (i.e. I couldn't explicitly cast `a` or `b` to `Double` for instance to be able to perform the comparison)


is it valid to use pearson correlation in order to create new features?

Question: I'm relatively new to machine learning and I was wondering if I can use the correlation between features and the target value to manipulate the features.
i'm trying to do some manual feature construction by looking at correlation of each feature with target value, like it is used for feature selection but here i want to use this information to create a new feature, for example we have two features 'a' and 'b', by looking at the correlation we see that their correlation is a = 0.1 and b = 0.3, now am i allowed to give the something like a score like a = 1 and b = 2 and then create a new feature c = a+b.
my concern is that i'm looking at the target value to do this.
Is it valid? is it considered falling in the trap of looking at the target value?
if it is valid it should be done only on the training set, right?
Answer: I think that you're thinking about a clustering-type process, where you extract important subsets of the input space. Usually this is represented with finding shapes or patterns in the data to exploit. These patterns might not always emerge just looking at descriptive statistics. If you want to cluster the input based on purely observed inputs, the principle components analysis procedure can help you construct new variables that are linear combinations of the original input dimensions. If you want to incorporate the output in the clustering approach, you could use an active subspace linear or quadratic model to simillarly identify important directions in your input space.
Comment: thank you for your answer, i'm actually saving the PCA as the last resort. sorry i edited my question for more clarity, i appreciated if you could give me an answer based on that. is active subspace a good approach for dimensionality reduction of binary variables?
Answer: In general, using target values isn't a very sound procedure. I'm guessing you'll have to rely on an unsupervised method to generate target values for your test data. So you can imagine that your solution will depend on the strength of your unsupervised method, which is obviously sub-par, otherwise you would have just used the unsupervised method in the first place.
However, in practice, it's something that people do all the time. For example, speech recognition strongly relies on an estimate of the boundaries of phonetic units for its classification. The boundaries are then updated and fed back into the classifier for another iteration. This procedure usually converges to something.
In conclusion, it's alright if you decide to incorporate target values in your features. However, be aware that your system will need target values in the test stage. In that case you'll probably end up with an iterative procedure of generating targets and updating them to get "better" target values.
Comment: yes exactly, a and b originally are binary (0 or 1), and i want to give them a higher value based on their importance in regards to target values, and then add them to transform them to only one variable, where if originally 'a' and 'b'  both equal to 1 than 'c=3' and if only a=1 then c=1 and if only b=1 than c=2. so i really want to look at the correlation with target value when training the system and then for user to use it the default value of a and b in system will be 1 and 2.
Comment: Thanks for clarifying. In the simple case that we've considered here, I don't see any problem of using correlation. Essentially, you're using your expert knowledge to weight your features. However, keep in mind, that approaches like this are generally not desirable, since when you increase the number of features (instead of a, b imagine a1, a2, ..., a1000) it gets out of hand pretty quickly.
Comment: no it is in fact a supervised method. maybe i didn't ask my question properly so i edited. my problem is exactly this sentence : ' In general, using target values isn't a very sound procedure' although i'm not actually using the target values itself just its correlation with features.
Comment: If by "their correlation is a=0.1 and b-0.3" you mean, their correlation with the target is 0.1 and 0.3, my point still stands. Say you've trained your system with these features. How is the client (or user) going to be able to generate c to apply the model? Remember, in reality we don't have access to the target.
Comment: yes but we do have 'a' and 'b' which are our binary features, and we know that for training the system we have assigned a=1 and b=2, so can't we just write an algorithm for the client to generate c by looking at features a and b? sorry if i'm misunderstanding something obvious
Comment: That's alright. It's more likely that I'm having trouble understanding your question. The way I understand you setup is that, a=1 and b=2 given a certain target value. Otherwise a and b will have other values assigned to them. That's why I think you need the target values to generate a and b.


Docker swarm join as manager fails but succeeds as worker

Question: I'm working on creating a 3 manager Docker Swarm using Docker CE 19.03 and three CentOS 7 machines.
I've installed docker via yum, enabled the service and started it.
I've created a firewalld 'service' and allowed (per docker docs):

TCP port 2377 for cluster management communications
TCP and UDP port 7946 for communication among nodes
UDP port 4789 for overlay network traffic

I was able to init the swarm and join a worker. The third server I tried to join as a manager however and it failed with

Error response from daemon: manager stopped: can't initialize raft node: rpc error: code = Unknown desc = could not connect to the prospective new cluster member using its advertised address: rpc error: code = DeadlineExceeded desc = context deadline exceeded

So I backed out with docker swarm leave and tried to join as a worker. It succeeded no problem. Now why would I be failing to join as a manager but successfully joining as a worker?
I tried allowing 2376/tcp (per https://www.digitalocean.com/community/tutorials/how-to-configure-the-linux-firewall-for-docker-swarm-on-centos-7) and disabling firewalld on the one manager to see if it was a firewall issue but I got the same error.
Answer: So, lesson learned, trust the error messages.
I had applied my firewalld service template and forgotten to reload firewalld so the ports were not actually open. Apparently all those ports were not actually required to join as a worker but are as a manager.
I had noticed in my load balancer that my containers were frequently showing as failed on that host when they are not which led me to double check everything.
Answer: There is a default time limit for swarm token.
You can create the token again to join
Comment: AFAIK, the time limit is one hour. I used the token immediately after generating it. In fact, the manager token was generated after the worker token so if anything, the worker token should have expired first. But you can see from the error message that the problem is not the token but the connection to the advertised address.
Comment: worker node time limit is far higher than manager. Anyway, why don't you just try getting token again with [docker swarm join-token manager]  and run the join command generated with the output. Ref: https://devopsdiaryblog.wordpress.com/2020/05/02/join-command/
Comment: The error message does not indicate a problem with the token, it indicates a problem with the connection. Anyways, I rotated the manager token and immediately tried to rejoin as a manager and it gave the same error. I rotated the worker token and was able to join as a worker with no issues.


Poincaré-Hopf theorem using Stokes

Question: The wiki entry on the Poincaré-Hopf theorem claims that it "relies heavily on integral, and, in particular, Stokes' theorem". However, in the sketch of proof given there which is more or less the one in Milnor's Topology from the Differentiable Viewpoint there is no integration.
Does the proof become easier by using Stokes' theorem? Is there a good reference?
Comment: Do you mean the WikiPEDIA article?
Comment: @t.b. Thanks for including the link
Comment: That wasn't me, I only fixed some typos :) You can see what was changed by whom by clicking on [edited *x time* ago](http://math.stackexchange.com/posts/136250/revisions) above the last editor's name.
Answer: In step 3 of the scketch you read "the degree of the Gauss map". Now one has to look for the definition of the degree of a map $ f:M\to N$. But that map gives a linear map in de Rham cohomology $f^*:H^m(N)\to H^m(M), n=\dim(M)=\dim(N)$. Stokes theorem says that the integral of $m$-forms induces an isomorphism $\int:H^m\to R$ an this transforms  $f^*$ (by change of variables in the integral) into a linear map $R\to R$. Such a linear map is the product times an scalar $d$: this is the degree of $f$.

Poincaré-Hopf theorem using Stokes


'Media File Selector' blank screen

Question: To use already existing image, I choose 'Media File Selector' Widget.
But, it gives me blank page like this when I click on 'Library' to choose already existing image in Drupal-7.

Version of the Media:
1) Media: YouTube
(media_youtube) 7.x-2.0-rc4
2) Media
(media) 7.x-1.4
In Media browser settings, Allowed file extensions are
(jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp mp3 mov m4v mp4 mpeg avi ogg oga ogv wmv ico)
Thanks!
Comment: Hello. It looks like a bugreport, and "issues found in existing modules" are listed as something you shouldn't ask here. Are you trying to debug & fix it by yourself? If so, what have you tried so far? And have you seen [this question](http://drupal.stackexchange.com/q/7560/16495)? Got any results with methods posted there?
Comment: I am new to Drupal and I tried to search for the same question while I found this question here - http://drupal.stackexchange.com/questions/107809/upload-images-tab-blank-when-adding-media
But, I couldn't find answer so posted here.
Answer: I am not sure whether to making 'jQuery' version down to some level is good or not. But, I tried to downgrade the jquery version to 1.5 and it works well with my website.
I refereed this post:
Media 7.x-1 Library tab empty
Now, I can see all my images by selecting 'jQuery' version - 1.5.
To do so:
Go to
Home » Administration » Configuration » Development

Thanks!
Vidushi
Comment: Yes this also worked for me.

'Media File Selector' blank screen


A theoretical model of a flow network.

Question: I believe I've got a correct understanding of how flow network works.
Yet, I've bumped into a theoretical question that I'm not even sure if interpreted right. Here it is:

Provide an example of a network with n nodes and with integer
capacities such that there is an exponential (i.e. greater than $c^n$
for some constant $c \gt 1$) number of different integer maximal flows
in it. Two flows are considered different if they differ on at least
one arc of the network

Unfortunately, I cannot post picture of a graph that I've constructed (due to the lack of 10 reputation), so I'll describe it formally

$V = \lbrace S, 1, 2, 3, T\rbrace$
$C(S,1) = s1$
$C(S,2) = s2$
$C(S,3) = s3$
$C(T,1) = t1$
$C(T,2) = t2$
$C(T,3) = t3$
$C(1,2) = ?$
$C(S,1) = ?$

So, one thing that I understood about that excercise, is that in order to have sufficient input flow and output capacity $$t1 + t2 + t3 \ge c^n \le s1 + s2 + s3$$
But what about $C(1,2)$ and $C(2,3)$? Maybe I've got totally wrong idea about question itself?
It would be a huge help even to paraphrase the task, as I think I'm reading it wrong.
Comment: It's not the best use of this site, Glass, to ask people for help, and then refuse to engage when they attempt to help you.
Comment: Any thoughts on the answers that have been posted?
Comment: I am terribly sorry that I am ignoring proposed solutions. The reason being, I'm studying hard on my calculus midterm, so I don't have much time or brainpower to even read it. Though, I promise to do it ASAP (probably on 25th of December)
Comment: OK. Merry Xmas.
Comment: Yeah, thanks. Same for you.

I've read both of proposed solutions and I think that they equally can be an answer to this problem, yet I found the first one to be more general.I've contacted my lecturer, who came up with this problem. He confirmed, these are suitable.

And yeah, I thought it was all about constructing flow network that gives outputs of $c^n$ different capacities, depending on what path you take. It turns out, It's either my formal english is pants, or my lecturer's.
Answer: Since you want to have exponentially many maximal flows, one way to construct it is to give many choice at first then to make a bottleneck.
As the original question asked to construct a graph for an arbitrary $n$, we will give a whole family of graphs $(G_n)_n$ with $G_n$ having (roughly) $n$ vertices and around $2^n$ different maximal flows(the graphs will actually have $n+1$ vertices plus the source and the sink, but it doesn't matter for the asymptotic):
Le $G_n$ be  the following graph :

its quite clear that a maximal flow has a capacity of $n \over 2$, now, one as to chose which vertices $a_i$ to visit for the flow. Clearly there is $\binom{n}{n/2}$ possible choice, meaning that there are $\binom{n}{n/2}$ different maximal flows. The asymptotics of this number is $2^n$ (see limit of $2n$-th root of $2n$-th central binomial coefficient -- $\lim_{n\to \infty}{2n \choose n}^{\frac{1}{2n}}$ for instance)
You can get more precise estimate on the number of flows but I hope this is more or less what you've asked.
[EDIT]
rethinking about it, this construction is a bit of an overkill as we can find an answer that does not involve knowing the asymptotic of the binomial coefficient (we'll end up with a smaller constant $c$ though).
the following graph
has graph with $8=2\times 4$ vertices and $4=2^2$ maximal flows.
Using three times this diamond  shaped graph we end up with :
$3\times 4$ vertices and $2^3$ maximal flows" />
which has  $12=3\times 4$ vertices and $8=2^3$ maximal flows
Repeating $k$ times this diamond shaped graph give a graph  with $4k$ vertices and $2^k$ maximal flows, so $n= 4k$ vertices and  $2^{n/4} = (2^{1/4})^n$ maximal flows.
Answer: Let $N$ be a network with nodes named $1,2,3,\dots,n$ and with an arc, of capacity one, from node $a$ to node $b$ precisely when $a<b$. Then node $1$ is the source, node $n$ is the sink, every flow is maximal, and the number of flows is $2^{n-2}$, because every subset of $\{\,2,3,\dots,n-1\,\}$ corresponds to a flow.

A theoretical model of a flow network.


Expected Value in Lottery Game

Question: In a lottery game, a person selects a three digit number. If the person plays for \$1, he can win \$500 . Find the expectation.
In the same lottery, if a person boxes a number , he will win \$80. Find the expectation if the number $123$ is played for \$1 and is boxed.
(Boxed meaning in any order- $123$, $321$, $213$, $312$, etc.)
Answer: There are 1000 equally likely numbers from $0$ to $999$.
In the first part only one of those numbers will give a win.
Expected win $=-1\cdot \cfrac{999}{1000} + 500 \cdot \cfrac{1}{1000}$.
In the second part there are 6 possible conbinations of $123$ that can give a win
Expected win $= -1 \cdot \cfrac{994}{1000} + 80 \cdot \cfrac{6}{1000}$.
Comment: I suspect the $-1$ needs to be multiplied by $\dfrac{1000}{1000}$ as most lotteries do not refund the stake to prize winners

Expected Value in Lottery Game


Sort list of two types of object with multiple criteria

Question: I have two objects in the TransactionList as debit & credit
I need to sort TransactionList  in below orders
Date (in ascending order)
Transaction Type (Credits first, then Debits)
Amount (in ascending order)
Description (in ascending order)
This is what I'm trying
data.OrderBy(x => x.Date).ThenBy(x => <sort here by credit first>).ThenBy(x => x.Amount).ThenBy(x => x.Description);

But this does not seem to work (not able to sort by type of object). Please suggest.
Comment: Try to use:   `data.OrderBy(x => x.Date).ThenBy(x => x.GetType().Name).ThenBy(x => x.Amount).ThenBy(x => x.Description);`
Comment: `typeof(Credit)` is a compile-time constant. Do you mean `x.GetType()` ? Or just `c.DebitType`?
Comment: @IVAAAN123 sorry this is not working
Comment: @Blorgbeard i want to sort by credit first and then debit
Comment: @user3904811 your **credit** class looks like `public class Debit : Transaction`. Maybe you mean `public class Credit : Transaction` ?
Comment: @IVAAAN123 sorry that was a typo, I edited it.
Comment: @user3904811 show me data what you try to sort. My code works fine for me
Comment: @IVAAAN123 answer below works, but how do I cast result to TransactionList?
Comment: @user3904811 `TransactionList list = new TransactionList(sortresult.ToList());`
Answer: You could try:
var result = data.OrderBy( x => x.Date ).ThenBy( x => x.GetType().ToString() ).ThenBy( x => x.Amount ).ThenBy( x => x.Description );


nginx: [emerg] "server" directive is not allowed here in /usr/local/nginx/conf/nginx.conf:92

Question: I can't find my problem...
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  domain.net;

        return 301 https://$server_name$request_uri;

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

   # HTTPS server
   #
   server {
       listen       443 ssl;
       ssl on;
       server_name  domain.net;

       ssl_certificate      /etc/letsencrypt/live/domain/fullchain.pem;
       ssl_certificate_key  /etc/letsencrypt/live/domain/privkey.pem;

       ssl_session_cache    shared:SSL:1m;
       ssl_session_timeout  5m;

       ssl_ciphers  HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers  on;

       location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:8000;
        proxy_redirect off;
       }
   }

}

when I command
 sudo service nginx restart

* Stopping Nginx Server...                           [fail]
* Starting Nginx Server...
 nginx: [emerg] "server" directive is not allowed here in /usr/local/nginx/conf/nginx.conf:92
                                                     [fail]

line 92 is
# HTTPS server
#
server {
    listen       443 ssl;
    ssl on;
    server_name  domain.net;

    ssl_certificate      /etc/letsencrypt/live/domain/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/domain/privkey.pem;

server { line is 92,
please some body help me..
Comment: I'm voting to close this question as off-topic because it's just a typo.
Comment: @ceejayoz you solved my problem... it's my shy mistake... I will close this question, thank you !
Answer: You've screwed up your commenting:
#        location = /50x.html {
#            root   html;
        }


zsh, zmv mass rename sub directories nothing happening on large volume of directories

Question: I've set
autoload -U zmv
alias mmv='noglob zmv -W'

When on sample data (~20 folders with subfolders) I run
mmv images/**/advert images/**/notice

it just works as expected.
But if I run same command on real data (hundreds of thousands folders), nothing happends. I've run mmv -n to get some messages but no result. Even one directory name was changed so after I while I just ended the process.
Is zmv cache folder list as a first step and than it replace names? I expected that zmv will start changing names immediately dir by dir.
Should I run mvv and just wait for few hours?
Answer: zmv computes all the renamings before it starts acting, so the behavior you observed is normal.
One of the reasons it does this is that it'll error out if two files are to be renamed to the same name. It also errors out if a file is to be renamed to a name that already exists, and it tries to find out about errors early on rather than aborting in the middle with a hard-to-determine set of files already renamed.


Display Count in cell with Excel & VLOOKUP w/Contains for certain letters

Question: Phew, that was a lot to write as a title.
I'm looking to display a count within a cell, the count would source from a search of another sheet & column utilizing (I assume) VLOOKUP.
Example:
So, I want to look for all values in Sheet2/Column A that contain "SMITH"
Then, in Sheet1/A1, a count of all those values of "SMITH" would show up (let's just say 122)
So, I have 122 Smiths' in sheet2/ColumnA and the number, 122 (count) shows up in Sheet1/A1
I hope that makes sense. I'm pretty green (obviously) to Excel.
Thanks!
Answer: I believe you're looking for something like this:
<code>=COUNTIF(A:A,"*"&"Smith"&"*")
</code>
With column A being where the names are.
Comment: You also need the `Sheet2!`, as the OP requested the formula is on Sheet1 but the data is on Sheet2.
Comment: Scott, I bow down to you!

One other question, what if I wanted to double click on that number, and it take me to the filtered results? Is that possible? Kind of like when you do a count of a pivot table set.


JUnit + Mockito how to test DAO layer

Question: I am using Spring, SpringMVC, Mybatis in the project.
First time to play with Mockito.
Before using Mockito, the test code looked like this
@Test
@Transactional
@Rollback
public void setNewUnifyPriceRoom() throws Exception {
    Map reqMap = new HashMap();
    reqMap.put("typeId", 21);
    reqMap.put("roomId", 19);

    roomDockingsMapper.setNewUnifyPriceRoom(reqMap);

    String isUnifyPriceRoom = roomDockingsMapper.isUnifyPriceRoom(19, 21);
    Assert.assertEquals("Y", isUnifyPriceRoom);
}

Then I found Mockito since I did not want to touch database during testing. I tried to write a BeforeClass as a data provider. However, I got stuck when I tried to return something after I did the setNewUnifyPriceRoom action
 private static RoomDockingsMapper mockRoomDockingsMapper;
    @BeforeClass
    public static void setup(){
        Map reqMap = new HashMap();
        reqMap.put("typeId", 21);
        reqMap.put("roomId", 19);
        mockRoomDockingsMapper = mock(RoomDockingsMapper.class);
        when(mockRoomDockingsMapper.setNewUnifyPriceRoom(reqMap)).thenReturn(??????);
    }

Basically what I want to do is after do setNewUnifyPriceRoom, then in the thenReturn section to set isUnifyPriceRoom method return "Y".
Any help will be appreciated.
Comment: It is difficult to answer based on what you provided..can you add the code for your actual method which you are testing?
Answer: You don't want to mock out the very method that you are testing. You want to mock out the database interaction that happens inside setNewUnifyPriceRoom, so that you can verify that the rest of the code is working correctly.

JUnit + Mockito how to test DAO layer


Criar uma Sequence, através de uma trigger. Oracle

Question: Estou tentando criar uma sequence em uma trigger.
Ao tentar criar por Execute Immediate, estou tendo o seguinte retorno:

ORA: 4092 - Cannot commit in a trigger.

Por tudo que já pesquisei, usar o Execute Immediate em uma trigger não é possível, pois ele está em uma dll que emite um commit automático.
Gostaria de saber se existe alguma outra forma de criar uma sequence por uma trigger.
Segue o código da trigger
CREATE OR REPLACE TRIGGER "TR_TEST"
  AFTER UPDATE ON TEST_TABLE
  FOR EACH ROW
DECLARE
BEGIN
   BEGIN
     EXECUTE IMMEDIATE 'CREATE SEQUENCE SEQ01' ||
                       '      MINVALUE 1' ||
                       '      MAXVALUE 999999999999999999999999999' ||
                       '      START WITH 1' ||
                       '      INCREMENT BY 1' ||
                       '      NOCACHE';
   EXCEPTION
       WHEN OTHERS THEN
          RAISE_APPLICATION_ERROR(-20200, 'Error');
   END;
END

Comment: Inclua o código de sua tentativa
Comment: Editei e inseri o código
Answer: Um Trigger não deve criar um objeto. Cada vez que ele for disparado, tentará criar o objeto novamente...
Pelo o que eu entendi, você quer incrementar a sequência SEQ01 após a update da tabela TEST_TABLE. Certo?
Se for isso, dentro do execute immediate deve conter:
select SEQ01.nextval from dual;
Desde tenha criado a sequence anteriormente.
Comment: Na verdade, existira uma validação olhando o nome da sequence para ver se ela já existe, caso não exista, será criada.
Answer: Você pode criar a sequencia em uma procedure e chamar a procedure dentro da sua trigger assim será possível criar ou utilizar a sequencia.
De uma olhada nesse link: https://stackoverflow.com/questions/40016510/creating-and-using-sequence-in-oracle-stored-procedure-sequence-doesnt-exist
Mas acredito que a melhor prática seria criar a sequencia normal tendo em vista que você já sabe que ela deverá existir.
Comment: Então Uerlen, eu tentei fazer isso, joguei a criação da sequencia em uma procedure e chamei ela na trigger, porem retorna o mesmo erro.


I'm moving nodes around on a Cassandra cluster, and seeing "Back pressure disabled!" in the logs

Question: I'm moving nodes around on a Cassandra cluster, and seeing Back pressure disabled! in the log.  I'm also seeing (around a minute earlier) Back pressure enabled with average index queue size: 1106.
What do these mean?  Are they bad?
Thanks!
Answer: This is a safety mechanism in DataStax Enterprise Search to avoid overloading the system. When you have very fast producers that push data in for indexing, indexing may get backed up. The system will detect that at flush time and block new requests until the system has caught up.
So basically unless you see problems, this is part of normal operations. It might indicate temporary stress on the system, like when adding or removing nodes (as that will potentially cause reindexing of larger portions of the data), but unless you constantly see this and it won't go away the system will be reaching steady state again.
Hope this helps.
Sven


Guessing the chord by notes

Question: Most of the time I can figure out what chord is being played by just seeing the notes. I do this by looking at the first note (note in which I feel the chord is changed) when I think the chord changed, and then try to match it with all chord triads. For example, if the first note is G, I  assume it is the C or E chord by matching the triads. (This seems to be correct 85% of the time.)
There is one song I found, however, that doesn't seem to work with this theory. Say I have the following lyrics and their respective chords:
Am.                ..................     D.....
...............I love you .......
The chord changes from Am to D by the 'you' word lyrics.
I found the note melody when at 'you' word is note E but the chord is D. How can it be an E note? As far as I know, D chord triads is D F A and there's no E.
Comment: Naming chords is a more subtle art than as you describe; certainly _melody_ notes often stray from triadic harmony into the chord extensions (E is the 9th of a **D** chord), or even further into nonchord tones. It is true that _often_ the melody note lands on a 1 or 3 or 5 at a chord transition. It is also true that often there is more than one way to name the same chord, and often more than one chord that suits a melody. As with everything, practice....
Comment: In "if the first note is G, I assume it is the C or E chord by matching the triads", don't you mean the Em chord instead of the E chord? The E chord contains a G# instead of a G, while the Em chord actually contains a G.
Comment: What is the song that you are examining? As it is, there are many explanations without enough info to narrow it down...
Answer: The basic D triad (when not specifying major/minor, the default is major) consists of: D - F# - A (not an F, that would be a minor third, making it a D minor triad). However, we can stack many other notes on top of this and still talk about a 'major D chord'.
Take this chord symbol for example: Dmaj9. Read this as D major 9. This symbol tells us that this is a D major chord, with a major seventh and a major second. So the notes would stack as follows: D - F# - A - C# - E. The E, being the 9 in the chord symbol, is basically a 2 (major second) but an octave higher.
Very often a melody sings notes from the scale, not necessarily notes in the triad. So a melody that goes: D - E - F#, sounds perfectly fine while singing over a simple D major triad. You are right that the E note, doesn't belong in a simple D major triad. But that doesn't mean the two won't go together.

Guessing the chord by notes


How do I configure cron in Drupal 6

Question: In my GoDaddy control panel I have scheduled it to run this script every day:
/web/cgi-bin/php5 "$HOME/html/my_site/cron.php
However I cant figure out how I create tasks that will be run when cron.php is run. I have gone through all the documentation and can't find this anywhere (The D6 video tutorial link seems to be down).
For example how would a go about deleting the contents of a temporary folder?. Do I just add some PHP using the unlink command to the cron.php (in which case drupal is not really involved) or is there some setting page that I havent discovered that allows you to create tasks?
Answer: Use hook_cron, and implement your functionality in it. This functionality will get executed when the server will ping cron.php.
You just need to set specific time period on which cron will be executed.

How do I configure cron in Drupal 6


How to set Select2 value using initSelection?

Question: I am using jQuery Select2 for dropdown lists. The data is loading via AJAX call using in JSON format.
Here is my script:
$("#sub_lessons").select2({
     maximumSelectionSize: 1,
     placeholder: "Select Sublessons",
     allowClear: true,
     multiple:true,
        ajax: {
          url: "getData.action?lid="+lessonid,
          dataType: 'json',
          data: function (term, page) {
            return {
              q: term
            };
          },
          results: function (data, page) {
            return { results: data };

          }
        }
    });

My html snippet:
<input type="hidden" id="sub_lessons" style="width:300px"/>

When we clicking on the select2 box the data is loading perfectly,
but I have the function like setValue() when button is clicked.
<input type="button" onclick="setValue(1)"/>

And my function is:
function setValue(no)
{
 $('#sub_lessons').select2('val',no);
}

But the value is not being set. I searched in some sites and suggested to use initselection.I used initselection,but it does not work.please help me how to set value to select2 when button is pressed.
any help would be appreciated.
Comment: Did your Json is in id and text format ?
Answer: try something like this
$('#sub_lessons').select2('val','no');

Answer: I try this; work for me. You should add this to initSelection select2:
        initSelection: function (element, callback) {
        var id = $(element).val();
        $.ajax("url/" + id, {
            dataType: "json"
        }).done(function (data) {
            var newOption = new Option(data.title, data.id, true, true);
            $('#sub_lessons').append(newOption).trigger('change');
            callback({"text": data.title, "id": data.id});
        });
    },

Comment: how this initSelection will be called ?
Comment: What do you mean exactly? this initSellection call when we want to set a value of select input. In select input data load with ajax search on  typing some words.@AwaisUsmani


Proof of bijection between two infinite sets

Question: If $g:X \rightarrow Y$ is a bijection, and $X$ is an infinite set, how would I prove that $Y$ is also an infinite set, using the following proposition: $X$ is infinite iff there is an injection $f: X \rightarrow X$ such that $f(X) \subsetneq X \iff f(X) \neq X$?
Answer: The fact that you have a bijection between X and Y means that the sets have the same cardinality. So if one is infinite the other one is infinite as well.
Or if this makes more intuitive sense, you can prove the contrapositive: If Y would be finite, and have $n$ elements, then X would have $n$ elements as well, and thus be finite as well. Since X is infinite, Y can therefore not be finite and must be infinite as well.
Answer: Because $g$ is a bijection from $X$ to $Y$, $|X|=|Y|$ follows. Hence, $Y$ is also an infinite set.
Answer: Assume $Y$ has $n$ elements then take $n+1$ elements from $X$ by Pigeonhole principle principle at least two elements from $X$ have the same image in $Y$ hence function isn't injective (1-1).
Answer: Depends what you mean by infinite. If by infinite you mean not finite, you can do a proof by contradiction: Suppose $Y$ is finite; i.e., there exists a bijection $f:Y\rightarrow\{1,...,n\}$ for some natural number $n$. Then $f \circ g$ is bijection from  $X\rightarrow\{1,...,n\}$, so $X$ would be finite, a contradiction. Thus $Y$ is infinite.
If by infinite you mean that the set is in bijection with a proper subset of itself (such a set is called Dedekind-infinite), then suppose $i:X\rightarrow A$ is a bijection for some proper subset $A$ of $X$. Then consider the function $f=g \circ i \circ g^{-1}:Y\rightarrow Y$.  Since it is a composition of injections, it is injective. Further, its image is $g(A)$, which is a proper subset of $Y$.


How to render a View to the right of parent node in ARCore sceneform

Question: Using ViewRenderable I am rendering layout file. I gave fixed width and height for the layout file
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="500dp"
    android:layout_height="50dp"
    android:background="@android:color/transparent">
// Add design
</android.support.constraint.ConstraintLayout>

Now I am building layout as ViewRenderable
 // Build a renderable from a 2D View.
        CompletableFuture<ViewRenderable> meterOne =
                ViewRenderable.builder().setView(this, R.layout.meter).build();

     CompletableFuture.allOf(circle,
                meterOne, meterTwo)
                .handle(
                        (notUsed, throwable) -> {
                            // When you build a Renderable, Sceneform loads its resources in the background while
                            // returning a CompletableFuture. Call handle(), thenAccept(), or check isDone()
                            // before calling get().

                            if (throwable != null) {
                                DemoUtils.displayError(this, "Unable to load renderable", throwable);
                                return null;
                            }

                            try {
 Meters.add(meterOne.get());
 } catch (InterruptedException | ExecutionException ex) {
                                DemoUtils.displayError(this, "Unable to load renderable", ex);
                            }

After that I need to render this ViewRenderable Object into the node
        Node sunVisual = new Node();
        sunVisual.setParent(sun);
        sunVisual.setRenderable(Meters.get(0)); // View
        sunVisual.setLocalScale(new Vector3(0.5f, 0.5f, 0.5f));

Now I need to add another node to the right of sunVisual node
            Node node = new Node();
            node.setParent(sunVisual );
            node.setRenderable(Meters.get(1));
            node.setLocalPosition(new Vector3(2.0f, 0.0f, 0.0f));

This code works well on google pixel 2 devices but I am getting small space in nokia x6 device
Google pixel 2 screenshot
Nokia x6 screenshot
How to get the rendered view width and height in meter?
How to set local position to the right of parent node based on the parent node rendered view size
Help me to fix this issue thanks in advance
Answer: I found solution to fix the above mentioned issue that I faced.
    Node node = new Node();
    node.setParent(parent);
    Renderable renderable = Meters.get(i);
    renderable.setShadowReceiver(false);
    renderable.setShadowCaster(false);
 ((ViewRenderable) renderable).setSizer(new FixedWidthViewSizer(2));
    node.setRenderable(renderable);
    node.setLocalPosition(new Vector3(2.0f, 0.0f, 0.0f));

We can use setSizer to set width and height for ViewRendarable
 ((ViewRenderable) renderable).setSizer(new FixedWidthViewSizer(2));


How to assess performance when it greatly varies from year to year?

Question: We have an annual performance metric for a number of educational institutions.  The figure for any one institution varies a lot from year to year, as it depends very greatly on the student cohort, but there is a clear correlation between the metric for any two years (Pearson correlation coefficient varies from .22 to .36).  Is there a statistic that we can calculate which combines several years to estimate of how much of the variation between institutions is caused by the institution itself (the remainder being due to the cohort).
[note 1: We are fully aware that not all the factors are under the control of the institution, some are dependent on the environment where the institution is situated].
[note 2: There are over 100 institutions, but only 3 years data at present (5 years soon)].
[note 3: The naive approach is to average the three years, but I hope there is something better we can do].
[note 4: I have looked at multiple correlation, but that seems to be answering a different problem (multiple factors influencing the outcome); we have multiple values for the outcome].
Thank you very much!
James
Answer: If you're interested in the decomposition of variance into a between-institution and within-institution components a "mixed model" (also called multilevel model) is probably what you're looking for. If your performance metric is a continuous variable and is approximately normally distributed you could try a "linear mixed model", if the metric is discrete you'll need a "generalized linear mixed model". This is a general and powerful class of methods, but it is a bit more difficult than calculating a simple summary statistic. If you can assume that each institution's performance is constant over time then a "random intercept model" would probably be the first thing to try. (And with only 3 data points it would be difficult to determine if performance is changing over time. Assuming it's constant is probably reasonable)
Without knowing a fair bit more about your data and objectives it's difficult to give much more advice, but hopefully that gets you started on your search.
Comment: Yes! Thank you, David, that sounds like pretty much perfect.  Just the advice I was looking for.  Things will probably go quiet at my end for a while, but once I've looked into the methods you suggest I will hopefully get back and accept this answer.  Thanks again.  James.


determine if the following converges or diverges using limit comparison Test [solved]

Question: how would you show if this converges or diverges using limit comparison test
$$\sum_{n=1}^\infty   \frac{(3n+2)}{(4n^7-3)^\frac{1}{3}}$$
I know I must compare it to
$$\sum_{n=1}^\infty   \frac{1}{n^\frac{4}{3}}$$
however, I am still unable to determine how to show convergence or divergence. Please help
Comment: Are you familiar with the p-test?  $$\sum_{n=1}^\infty \frac 1{n^p}$$ converges for p>1.
Comment: yes, I am and because p is more than 1 it should converge but I would like to know how I would show it using the limit as n tends to infinite of the quotient of the two series.
Answer: Determining the order of growth of the summands as a function of $n$:
\begin{align*}
\frac{3n+2}{(4n^7 -3)^{1/3}} &= \frac{(3+2n^{-1})n}{((4 -3n^{-7})n^7)^{1/3}}  \\
    &= \frac{(3+2n^{-1})n}{(4 -3n^{-7})^{1/3}n^{7/3}}  \\
    &= \frac{(3+2n^{-1})}{(4 -3n^{-7})^{1/3}} \cdot \frac{n}{n^{7/3}}  \\
    &= \frac{(3+2n^{-1})}{(4 -3n^{-7})^{1/3}} \cdot \frac{1}{n^{4/3}}
\end{align*}
For the limit comparison test, we verify
\begin{align*}
3n+2 \geq 2 &> 0, \text{ if } n \geq 1,  \text{ and }  \\
(4n^7 -3)^{1/3} \geq (4-3)^{1/3} = 1 &> 0, \text{ if } n \geq 1,  \text{ so }  \\
\frac{3n+2}{(4n^7 -3)^{1/3}} &> 0, \text{ if } n \geq 1
\end{align*}
and also $1/n^{4/3} > 0$ for all $n \geq 1$.  Then we study
\begin{align*}
\lim_{n \rightarrow \infty} \frac{\frac{3n+2}{(4n^7 -3)^{1/3}}}{\frac{1}{n^{4/3}}}
    &= \lim_{n \rightarrow \infty} \frac{\frac{(3+2n^{-1})}{(4 -3n^{-7})^{1/3}} \cdot \frac{1}{n^{4/3}}}{\frac{1}{n^{4/3}}}  \\
    &= \lim_{n \rightarrow \infty} \frac{(3+2n^{-1})}{(4 -3n^{-7})^{1/3}}  \\
    &= \frac{3+0}{(4-0)^{1/3}}  \\
    &= \frac{3}{4^{1/3}}  \text{.}
\end{align*}
Since this is a positive, finite limit, either both series converge or both series diverge.
So, does $\sum_{n=1}^\infty \frac{1}{n^{4/3}}$ converge or diverge?
Comment: thank you very much. It makes sense now and I know it would converge as we are comparing with a p-series p > 1.


Find the surface area of part of cone $x^{2} = y^{2} + z^{2}$ which lies inside the sphere $x^{2} + y^{2} + z^{2} = 2z$.

Question: Find the surface area of part of cone $x^{2} = y^{2} + z^{2}$ which lies inside the sphere $x^{2} + y^{2} + z^{2} = 2z$
Intersection of both surfaces on $yz$ plane will be $ y^{2} + (z-1/2)^{2} = 1/4$
Surface area $= \int \sqrt{1 + (y/x)^{2} + (z/x)^{2}} dydz$
$= \int (\sqrt{ (x^{2} + y^{2} + z^{2}})/x) dydz$
$= \int ( \sqrt{ 2(y^{2} + z^{2})})/(\sqrt{y^{2} + z^{2}}) dydz$
$= \int \sqrt{2} dydz$
Since area of the circle $ y^{2} + (z-1/2)^{2} = 1/4$ is $ \pi /4$ so the surface area should be $( \sqrt{2} \pi)/4$
But answer is given $ \sqrt{2} \pi$
So where did I go wrong$?$
Comment: Given answer can't be correct. $\pi\sqrt{2}$ is the total area of the cone in $[-1,1]\times[-1,1]\times[0,1]$, of which the part that lies in the sphere is a subset.
Answer: The condition $ x^2 = y^2 + z^2 $ implies the existence of two cones
$x = \sqrt {y^2 + z^2}$ and $x = -\sqrt {y^2 + z^2}$ so the result should be doubled, as you only used the first cone.
However, the expected answer still remains different.
Comment: Yes, this is what I guessed. Then the result should be $\pi / \sqrt{2}$. But answer is given different.


WCF/Asmx dando timeout mas hardware do servidor está sussegado

Question: Boa noite.
Eu tenho uma aplicação que é integrada com mais de cem outras aplicações através de webservices, onde eu utilizo bastante threads para comunicação entre elas. Essa minha aplicação é utilizada por outras aplicações através de uma dll hoje. Estou tentando migrar essa dll para um serviço, para isso criei um serviço WCF (já tentei asmx tbm). O problema é que conforme vão entrando as requisições esse serviço começa a aumentar muito o timeout de resposta até começar a dar timeout em tudo. O que é estranho é que o hardware (memoria e cpu) estão abaixo dos 30% de consumo, então eu acredito que o problema são as threads lançadas, ou alguma configuração de iis ou do wcf/asmx. Queria saber se alguem já passou por isso ou tem alguma ideia de como resolver isso.
Obrigado.
Comment: Nikolas, como está os valores de `InstanceContextMode`, `ConcurrencyMode` e os valores de `Throttling`, tambem gostaria de saber se as suas aplicações clientes realizam requisições simultâneas internamente (a mesma aplicação realizando duas ou mais requisições ao mesmo tempo).
Comment: Eu já fiz diversos testes com esses parâmetros. Sim, realiza centenas de requisições.
Answer: Uma solução 'suja' (mas prática e que te dará tempo), seria diminuir o tempo entre recycle do pool que serve o wcf.
Neste meio tempo procurar o fornecedor para que junto consiga descobrir o que está acontecendo, já que pode ser desde um bug bobo no código da dll, até problemas mais sérios como 'gestão de concorrência'.


lilypond instrumentName breaks geometry

Question: I have a score which looks great, until I try to set the instrumentName:
Without instrumentName:

With instrumentName:

\score {
  \new StaffGroup <<
    \new Staff \with {
      instrumentName = "Baß Tube I&II in B"
    }{
      \transpose c bes
      <<
        \new Voice = "TenorIb" { \voiceOne \tenortubaib }
        \new Voice = "TenorIIb" { \voiceTwo \tenortubaiib }
      >>
    }
    \new Staff \with {
      instrumentName = "Baß Tube I&II in F"
    }{
      \transpose c f
      <<
        \new Voice = "basIf" { \voiceTwo \bastubaif }
        \new Voice = "basIIf" { \voiceOne \bastubaiif }
      >>
    }
    \new Staff \with {
      instrumentName = "Kontrabaß Tuba"
    }{
      \clef bass
      \tuba
    }
  >>
}

Answer: The paper block is used to set values such as the indention values.
To make enough room for those (long) instrument names you'll need to set the indentation value to something greater than the default (15\mm), say:
\paper {
    indent = 35\mm
}

If you are also using short instrument names (e.g. shortInstrumentName = "Btb.") you can set the short indent value (default 0\mm) in the paper block too, with say: short-indent = 10\mm.

You can use units other than \mm (millimetres), such \cm, \in, \pt.
Other paper block variables can be found here:
https://lilypond.org/doc/v2.24/Documentation/notation/horizontal-spacing-paper-variables
Comment: Another thing worth mentioning is I am integrating `lilypond` into `latex`.  It appears `latex` overrides the default paper indent to `0`, that is wonderful for single-staff excerpts, but caused this problem to be even worse.  Setting paper indent in `lilypond` is a really good solution, even if you are just setting it back to the `15\mm`
Comment: @Stewart I love LaTeX, but I haven't used it in a while.
When I compile you code, the left side of the page spills, rather than (as in your image) the right.  So I guess LaTeX is overriding more "page variables" than just the indentation.
Comment: This saved me.  After this, I also thought about those "long" names.  `instrumentName = \markup \right-column { "Tenor Tube" "I&II in B" }` let me split the long name onto two lines which helped me reduce the indent to `20\mm`.
Comment: I find something like this looks rather nice: `\markup { \hcenter-in #20 { \center-column { \vspace #+0.2 \line { "Clarinet" } \vspace #-0.3 \tiny \concat { "in B" \flat } } } \hspace #-1.7 \small \center-column { "1" "2" \vspace #-0.3 } }`, but it is a bit fiddly.

lilypond instrumentName breaks geometry


Rails 3.x How to properly define inflections

Question: I have a need to define an inflection for the word 'chassis' where the same word defines both singular and plural and I am really struggling with this.
I thought I was there with the initialize/inflections.rb definition
 ActiveSupport::Inflector.inflections do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person', 'people'
#   inflect.uncountable %w( fish sheep )
    inflect.uncountable(/.*chassis.*/i)
 end

Taking note of the example inflect.uncountable %w( fish sheep ) I tried to use inflect.uncountable %w( chassis ) when I first set up the scaffolding but that didn't work at all well as it didn't take into account leading parts in paths and caused problems with relationships and other tables like car_chassis and chassis_lookup.
Having looked at various solutions provided as answers to similar questions in Stack Overflow I eventually came up with inflect.uncountable(/.*chassis.*/i) Which seemed to take care of scaffolding but I'm having an issue with routes where <%= link_to "Chassis", admin_chassis_url%> gives me a no route for the show action error.
ActionController::RoutingError - No route matches {:action=>"show", :controller=>"admin/chassis"}

Which makes sense as I want the index action so I'm not passing an object to the path but Rails is obviously thinking I am requesting the show action
The other examples for regex's
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'

are just complete gobbledygook to me and learning regular expressions needs a lifetime of learning that I neither have the inclination or the sanity to get my head round and the rails documentation http://api.rubyonrails.org/classes/ActiveSupport/Inflector/Inflections.html on inflections is quite frankly pathetic.
I obviously haven't got the inflection right. Can anyone give me a complete solution as to exactly how I should define an inflection for the word "chassis" for me and for others please as none of the previous answers I've found provide a complete and proper solution
Answer: Your inflection seem to be correct.
Check what 'rake routes' tell you. In my case it was smart enough to detect that plural and single form of chassis was the same, so it generated admin_chassis_index instead of just admin_chassis for the #index action. Probably, the same is true for you. This is what I did:
In config/routes.rb
namespace :admin do
  resources :chassis
end

Running 'rake routes' gives (note the first path):
admin_chassis_index GET    /admin/chassis(.:format)          admin/chassis#index
                    POST   /admin/chassis(.:format)          admin/chassis#create
  new_admin_chassis GET    /admin/chassis/new(.:format)      admin/chassis#new
 edit_admin_chassis GET    /admin/chassis/:id/edit(.:format) admin/chassis#edit
      admin_chassis GET    /admin/chassis/:id(.:format)      admin/chassis#show
                    PUT    /admin/chassis/:id(.:format)      admin/chassis#update
                    DELETE /admin/chassis/:id(.:format)      admin/chassis#destroy

So, for #index I'd need to call:
<%= link_to "Chassis", admin_chassis_index_url%>

Comment: Awesome. God knows why I didn't check 'rake routes' I've been tearing my hair out for days over this


How can I create a newsletter with the last five news nodes?

Question: I need to create a newsletter where І can send the latest five news nodes in Drupal 8. Maybe you can recommend any module or custom method. I tried to use the Simplenews module, but with Drupal 8 nothing comes out.
Answer: 1/Create a view with the last new nodes (and their fields) with a block display
2/Make this view's display available as a variable for your newsletter by using a preprocess function in YOURTHEME.theme, something like:
<code>function YOURTHEME_preprocess_simplenews_newsletter_body(&$variables) {
$variables['latestnews'] = views_embed_view('latestnews', 'block_1');
}
</code>
Create a template for the newsletter body simplenews-newsletter-body--[newsletter_id].html.twig (newsletter_id = machine name).
and add your view in it where you'd like to:
<code>{{ latestnews }}
</code>
Then, on top of it, you may need to use Swiftmailer/Mimemail for better styling output. That requires another layer of configuration and template.
Answer: I would use free Mailchimp plan and create a campaign that uses an RSS feed to populate its content. The RSS feed can be created by Views. In the View, set a filter to select only News content type, sorted by created DESC, that are published, and set a limit to 5 results only. Then just select the fields from the content type that you want to output in the View.
I have never had a lot of luck trying to run newsletters out of Drupal itself. You wouldn't need any module to do this other than Views.
Mailchimp has a lot of tokens and helpers to help you inject the RSS feed content and work with it. Its how we run our own internal newsletters.