Runing a functions project locally

Question: I am truing to get a existing .Net functions app runing locally. It has been developed on Windows with Visual Studio, but I am on a Mac (M1 CPU) and using VS Code. I am pretty new to .Net I am struggeling to figure out what needs to be configured to get the project running.
I have added a launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Attach to .NET Functions",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command:azureFunctions.pickProcess}"
        }
    ]
}
and a local.settings.json:
{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
}
and there is a tasks.json already in the project:
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "clean (functions)",
            "command": "dotnet",
            "args": [
                "clean",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "type": "process",
            "problemMatcher": "$msCompile",
            "options": {
                "cwd": "${workspaceFolder}/Naboor.Statistics"
            }
        },
        {
            "label": "build (functions)",
            "command": "dotnet",
            "args": [
                "build",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "type": "process",
            "dependsOn": "clean (functions)",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": "$msCompile",
            "options": {
                "cwd": "${workspaceFolder}/Naboor.Statistics"
            }
        },
        {
            "label": "clean release (functions)",
            "command": "dotnet",
            "args": [
                "clean",
                "--configuration",
                "Release",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "type": "process",
            "problemMatcher": "$msCompile",
            "options": {
                "cwd": "${workspaceFolder}/Naboor.Statistics"
            }
        },
        {
            "label": "publish (functions)",
            "command": "dotnet",
            "args": [
                "publish",
                "--configuration",
                "Release",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "type": "process",
            "dependsOn": "clean release (functions)",
            "problemMatcher": "$msCompile",
            "options": {
                "cwd": "${workspaceFolder}/Naboor.Statistics"
            }
        },
        {
            "type": "func",
            "dependsOn": "build (functions)",
            "options": {
                "cwd": "${workspaceFolder}/Naboor.Statistics/bin/Debug/net6.0"
            },
            "command": "host start",
            "isBackground": true,
            "problemMatcher": "$func-dotnet-watch"
        }
    ]
}
Should I be able to run this project from the commandline somehow? Do I need to point to a task in the tasks.json?
If I run it with F5 in VS Code, I get this error:
Executing task: func host start

Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]

Azure Functions Core Tools
Core Tools Version:       4.0.4544 Commit hash: N/A  (64-bit)
Function Runtime Version: 18.104.22.16886

Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
[2022-05-25T12:24:12.674Z] Failed to initialize worker provider for: /opt/homebrew/Cellar/azure-functions-core-tools@4/4.0.4544/workers/python
[2022-05-25T12:24:12.682Z] Microsoft.Azure.WebJobs.Script: Architecture Arm64 is not supported for language python.
[2022-05-25T12:24:12.991Z] Failed to initialize worker provider for: /opt/homebrew/Cellar/azure-functions-core-tools@4/4.0.4544/workers/python
[2022-05-25T12:24:12.991Z] Microsoft.Azure.WebJobs.Script: Architecture Arm64 is not supported for language python.
[2022-05-25T12:24:13.118Z] A host error has occurred during startup operation 'a0f1f8a3-92f6-434a-9ab1-17055f0828f4'.
[2022-05-25T12:24:13.118Z] Microsoft.Azure.WebJobs.Script.WebHost: Secret initialization from Blob storage failed due to missing both an Azure Storage connection string and a SAS connection uri. For Blob Storage, please provide at least one of these. If you intend to use files for secrets, add an App Setting key 'AzureWebJobsSecretStorageType' with value 'Files'.
Value cannot be null. (Parameter 'provider')
The terminal process "/opt/homebrew/bin/zsh '-c', 'func host start'" terminated with exit code: 1.
I thought that was what the "FUNCTIONS_WORKER_RUNTIME": "dotnet" part of local.settings.json was for?
I am pretty new to this, can anybody guide me on the correct path?
Thank you
Søren
Comment: Check that you in the right directory that includes the project file.. not some top level or other directory. Then type dotnet restore and then type func start
Comment: Can you update your post with the contents of the .csproj file
Answer: As it was not explicitly mentioned, the effect of multiple output errors comes with the missing local.settings.json file. This answer is explicitly for Visual Studio 2022 users, NOT Visual Studio Code!
For reference the erroneous output:
Executing task: func host start

Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]

Azure Functions Core Tools
Core Tools Version:       4.0.4544 Commit hash: N/A  (64-bit)
Function Runtime Version: 220.127.116.1186

Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]

If you have added the file locally from another source (through the add existing item feature), Visual Studio will keep in the project, but will not copy it to the publish directory. This step is often necessary because this file is in .gitignore and hence not pulled from your repo.
In .csproj it will look like this:
<None Update="local.settings.json">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  <CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>

Just remove the line
  <CopyToPublishDirectory>Never</CopyToPublishDirectory>

and that it is. To prove it just run func host start in the project's root from command line and it will work, as this works on the project itself without the publishing step performed by Visual Studio.
It might als happen that the copy step is entirely missing, then either add the step or use the copy always feature in Property window (F4) of VS.
Comment: I tried this but it didn't work for me. My issue was I had nested objects in the local.settings.json and apparently looks like that is not allowed. After removing it outside of the nested, it worked. So yeah any minor issue like an extra ; or } would show up as this error.
Comment: Nesting in AppSettings, KeyVault, App Configuration and other tools that are organised as a key value struct (dictionary) is possible, indeed. However, to overcome the limitation it's usually organized by some special chars: Prop__NestedObj__Prop (double underscore in App Configuration) or Prop--NestedObj--Prop (double dash in KeyVault). Retrieve in code using the Prop:NestedObj:Prop syntax.
Answer: Create local.settings.json file:
{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
    }
}

Answer: We have tried the same in our local and able to run it successfully.
I believe that you are just missing the configuration in your local .
Here are the steps :-

Make sure the Azure function runtime , Dotnet sdk, storage emulator has been installed in your local . If not you can download from VS CODE extension called AZURITE instead of emulator as it has been deprecated.

In VS CODE install extensions Azure where all the tools will be available , c# (Any language that you want to prefer) & Azure function being installed.

.

If you want to create new project click f1> Select create new azure function . As you have existing file there is no need to point task.json file once the aforementioned has been done test your project by running :

. dotnet build once build succeed run ,
. func host start (If you have existing/new project don't run func init as it will create one more .csproj file and then it may occur to fail)
SNAPSHOTS FOR REFERENCE:-

STORAGE EMULATOR STARTED IN LOCAL:-

For more information please refer this MICROSOFT DOCUMENTATION| STEP BY STEP TUTORIAL TO CREATE AZURE FUNCTION IN VS CODE.
Alternatively, If you want to learn using Visual studio Create Azure function on Macos please refer this MICROSOFT DOCUMENTATION.
Answer: In order to configure VSCode launch tasks etc I would recommend installing the Azure Functions extension from the marketplace:
https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions
Once that is installed you can open the project and it will likely detect the functions project and ask if you want to initiliase for use with VSCode. If it does not then you can use the option from the command palette.

You may also be able to just run func init against the project to initiliase any files that may be missing.
Please ensure any files are tracked in git or backed up before making changes to the existing files
Having worked with Azure Functions on both Windows and Mac (non-M1) I would highly recommend using devcontainers for development. This means you don't have to have the SDK/Runtime/Functions Core Tools installed locally and means anyone using the project can just spin up the container and begin debugging without having to install a bunch of dependencies.
https://code.visualstudio.com/docs/remote/containers
Comment: Seems it could be an issue witht the `local.settings.json` as per this github issue: https://github.com/Azure/azure-functions-core-tools/issues/2050. I've only ever developed functions in VSCode so never had to deal with Visual Studio differences.
Comment: I did run "func init", that is what gave me the local.settings.json, and I just tried running the VS Code plugin init also, but still it gives the "Can't determine project language from files" error message?

Runing a functions project locally


Breusch-Pagan Test for ARIMA Model in R

Question: I am testing my model using the Breusch-Pagan Test, but have not been able to find anything online regarding how to calculate it for an ARIMA Model.
My AR1 Model is:
ar1 <- arima(x = datasource[, "Y"], order = c(1, 0, 0),
    xreg = datasource[, c("X1", "X2", "X3", "X4", "X5")])

Comment: Welcome to SE. I edited your post so that the code is readable (just space it over 4 positions, or use the "{}" icon in the compose window). Also, this might be better suited for StackExchange, as it's primarily about coding/programming and not about a statistical issue.
Comment: You can apply any script or function to the residuals `ar1$residuals`.
Answer: Your question makes me wonder why the Breusch-Pagan (BP) test is not available for the output from a fitted ARIMA model. Is the BP test applicable to ARIMA models? (This question fits better within the scope of this site.)
I don't see theoretical reasons that would invalidate the test in the context of an ARIMA model. The purpose and interpretation of the test are nonetheless more appropriate in the context of a regression model rather than in a model for the autocorrelation structure of a time series model.
You did not mention it in the question but I noticed in the sample code that you are including exogenous regressors in the ARIMA model, X1,...,X5. In this case, the BP test can be interesting in order to test whether there is a relationship between these regressors and the variance of the error.

Some ideas on how to code or obtain the BP test statistic with an ARIMA model in R (the software that you are using according to your sample code):
If you are using an AR model, then you can fit it as a linear regression model where lags of the dependent variable are included as regressors (along with the other explanatory variables). Then you can use the function ncvTest in package car or bptest in package lmtest. Example for an AR(1) model:
y <- datasource[, "Y"]
n <- length(y)
xreg <- as.matrix(datasource[, c("X1", "X2", "X3", "X4", "X5")])
fit1 <- lm(y[2:n] ~ 0 + xreg[2:n,] + y[1:(n-1)])
# alternatively the "dynlm" interface can be used
require(dynlm)
fit <- dynlm(y ~ xreg + L(y,1))
# lmtest::bptestreturns the Breusch and Pagan test statistic
require(lmtest)
bptest(fit)

Be aware of the differences between the linear regression model and the specification of AR model with exogenous regressors. See this post for details.
If you want to use the ARIMA model specification or if the model includes an MA part, you could include as regressors in the linear model lags of the residuals obtained in a previous step, but it is easier to implement the test upon the residuals of the fitted ARIMA model:
ar1 <- arima(y, order=c(1,0,0), xreg=xreg)
e <- residuals(ar1)
fitaux <- lm(e ~ 1 + xreg)
df <- ncol(xreg) - 1
bp.statistic <- (length(e) - df) * summary(fitaux)$r.squared
bp.pvalue <- pchisq(bp.statistic, df, lower.tail=FALSE)

Comment: Thanks a lot for your feedback! It helped me get the BP statistic. Now in the case of an AR(2) model, would the formulas you provided be different? I'm guessing n-1 would turn into n-2 and 2:n would become 3:n? Apologies for my ignorance in statistics.
Comment: For an AR(2) you should change the indices, `lm(y[3:n] ~ 0 + xreg[3:n] + y[2:(n-1)] + y[1:(n-2)])`. It may be easier and safer to use the `dynlm` interface.
Comment: Notice also that I have fixed in the answer the indices for  `xreg`, they should be the same that for the dependent variable (assuming they are not lagged regressors).
Answer: i think this can help:
adapted from: https://github.com/cran/car/blob/master/R/ncvTest.R
ncvTest.arima <- function(model, ...) {
    data <- getCall(model)$data
    model <- model
    sumry <- summary(model)
    residuals <- residuals(model)

    S.sq <- (length(residuals)-2)*(model$sigma2)/length(residuals)
    #cat("S.sq=",S.sq,"\n")
    .U <- (residuals^2)/S.sq
    #cat(".U=",.U,"\n")
    mod <- lm(.U ~ fitted.values(model))
    varnames <- "fitted.values"
    var.formula <- ~ fitted.values
    df <- 1
    SS <- anova(mod)$"Sum Sq"
    #cat("SS=",SS,"\n")
    RegSS <- sum(SS) - SS[length(SS)]
    Chisq <- RegSS/2
    result <- list(formula=var.formula, formula.name="Variance",ChiSquare=Chisq, Df=df, p=pchisq(Chisq, df, lower.tail=FALSE), test="Non-constant Variance Score Test")
    class(result) <- "chisqTest"
    #result
}

arima_model=auto.arima(time_series_data)
summary(arima_model)
ncvTest.arima(arima_model)

Breusch-Pagan Test for ARIMA Model in R


Can a Calendar, based on two different content types, output different html based on content type

Question: I built a calendar based on two different content type, let's call them A and B. For each type I output the Title field and, along with it, I'd like to have a link to the node if the Title field belongs to type A and just plain text if it belongs to type B. Is there a way to do this?
Answer: You could use the Views PHP module.
Then add the content type to the view. You can exclude both content type and title from the the view only display the title through the Global PHP field. With in that you can place a condition to display the complete link if it is of Type A and only the Title if it is of Type B. You could also add the path to the node as a views fields if you prefer so that it can be used in the as href for the link in php field.
Comment: Thank you very much, I managed to make it work with your method. I'm gonna wait to mark it as answer for one day in case someone else shows up with a "cleaner" solution. Thank you again!


find the maximum value of $xy + yz +zx$

Question: find the maximum value of $$xy + yz +zx$$given that $x+2y+z=4$
my attempt :
$(x+y+z)^2=x^2+y^2+z^2+2(xy+yz+zx) $
or $2S=2(xy+zx+zy)=(x+y+z)^2 -x^2-y^2-z^2=(4-y)^2-x^2-y^2-z^2$
$2S=-x^2-z^2-8y+16=-x^2-z^2+4x+4z$
from the the above we can say due to symmetry maximum value occurs at $x=z$
hence $S=-x^2+4x$ whose maximum is 4
is this right or/and is there a better way ??
Comment: Are $$x,y,z$$ assumed to be positive?
Comment: $4$ is the right result.
Comment: @MartinR The OP has a solution and asks for a confirmation. Not a dupe.
Comment: @Jean-ClaudeArbaut: You have a point. But the *"... is there a better way"* part has been answered before. Btw. none of the present answers addresses the *"is this right"* part of the question.
Answer: Using $$\color{red}{ab\leq \frac{1}{4}(a+b)^2}\;\forall\; a,b \in \mathbb{R}$$
Equality hold when $\color{red}{a=b}$
So $$(x+y)(y+z)\leq \frac{1}{4}\bigg[(x+y)+(y+z)\bigg]^2$$
$$xy+yz+zx+y^2\leq 4\Rightarrow \color{Red}{xy+yz+zx\leq 4-y^2\leq 4}$$
equality hold when $y=0$ and $x=z=2$
Comment: This is the solution https://math.stackexchange.com/a/2031107 to your own question https://math.stackexchange.com/q/2025356.
Comment: Elegant solution! (+1)
Answer: We have $$\frac{(x+2y+z)^2}{16}=1$$ so we have to prove that
$$4xy+4yz+4zx\le x^2+4y^2+z^2+2xz+4yz+4xy$$ and this is $$0\le (x-z)^2+4y^2$$
Answer: With a Lagrangian multiplier $\lambda$ in a Lagrangian $L:=xy+yz+zx+\lambda (4-x-2y-z)$, $0=\partial_x L=y+z-\lambda$ etc. gives $\lambda=y+z=\frac{z+x}{2}=x+y$. Comparing the first and last of these expressions for $\lambda$ gives $x=z$, so $y+z=z$ and $y=0$. Then $x=\frac{4-2\times 0}{2}=2$, so $z=2,\,xy+yz+zx=4$.

find the maximum value of $xy + yz +zx$


How can I apply the Poisson ($\mu$) distribution to two series of random draws?

Question: I have the following question:
A box contains 1000 balls, of which 2 are black and the rest are white. If two series of 1000 draws are made at random from this box, what approximately, is the chance that they produce the same number of black balls?
I believe it an exercise in applying The Poisson ($\mu$) Distribution: The Poisson distribution with parameter $\mu$ is the distribution of probabilities $P_{\mu}(k)$ over $\{0,1,2,...\}$ defined by
$$P_{\mu}(k)=e^{-\mu}\frac{\mu^k}{k!}$$
Let $\mu = 1000 \cdot \frac{2}{1000} = 2$ so that
$$P_{\mu}(k)=\sum_{k=0}^{\infty}P(k)\cdot P(k)$$
$$P_{\mu}(k)= \sum_{k=0}^{\infty} e^{-2}\frac{2^k}{k!} \cdot e^{-2}\frac{2^k}{k!}$$
$$=e^{-4}\cdot \sum_{k=0}^{\infty}(\frac{2^k}{k!})^2$$
And then I look up the answer and see that $\sum_{k=0}^{\infty}(\frac{2^k}{k!})^2$ translates to $I_0(4)$ which is a modified Bessel function. However I havn't learnt this, and Bessel isn't in the index of my textbook.
I thought maybe $$\sum_{k=0}^{\infty}(\frac{2^k}{k!})^2 = (e^2)^2$$ but that would make the whole thing =1... which maybe makes sense since they question didn't specify with replacement.
Comment: You can't interchange summation and squaring.
Answer: Comments: I'm not sure why you think you're supposed to use a Poisson
approximation.
Poisson approximation. With your Poisson method, approximating the (infinite?) sum with R:
f = dpois(0:10000, 2)
sum(f^2)
[1] 0.2070019

But I'm not sure why you'd sum the series beyond 1000 draws?
Actually, almost all of the probability is in the first few terms:
f = dpois(0:10, 2);  f.2 = f^2;  cf.2 = cumsum(f.2)
cbind(f, f.2, cf.2)  # 'binds' column vectors

                 f          f.2       cf.2
 [1,] 1.353353e-01 1.831564e-02 0.01831564
 [2,] 2.706706e-01 7.326256e-02 0.09157819
 [3,] 2.706706e-01 7.326256e-02 0.16484075
 [4,] 1.804470e-01 3.256114e-02 0.19740189
 [5,] 9.022352e-02 8.140284e-03 0.20554217
 [6,] 3.608941e-02 1.302445e-03 0.20684462
 [7,] 1.202980e-02 1.447162e-04 0.20698933
 [8,] 3.437087e-03 1.181356e-05 0.20700114
 [9,] 8.592716e-04 7.383478e-07 0.20700188
[10,] 1.909493e-04 3.646162e-08 0.20700192
[11,] 3.818985e-05 1.458465e-09 0.20700192

Simulating with 10 million iterations, result is $0.2071 \pm 0.0013.$
set.seed(1016)
x = rpois(10^7, 2)
y = rpois(10^7, 2)
mean(x==y)
[1] 0.207069      # aprx P(Same twice) = 0.2070019
2*sd(x--y)/sqrt(10^7)
[1] 0.001264853   # aprx 95% margin of simulation error

So provided the Poisson model is correct, the answer to four places is 0.2070.
Hypergeometric. If you choose without replacement, then you'll always get exactly 2 black balls.
Binomial. If you choose with replacement, the exact model is binomial.
f = dbinom(0:1000, 1000, 2/1000)
sum(f^2)
[1] 0.2071337

Maybe there is a nice binomial identity for summing the 1001 terms.
Simulation of binomial model gives $P(\text{Both Same}) = 0.2073 \pm 0.0003,$
which includes the exact value.
set.seed(1017)
x = rbinom(10^7, 1000, 2/1000)
y = rbinom(10^7, 1000, 2/1000)
mean(x==y)
[1] 0.207295
2*sd(x==y)/sqrt(10^7)
[1] 0.0002563777

Comment: FWIW, the Binomial answer can be expressed (with $n=1000$ and $p=2/1000$) as $(1-p)^{2n}\,_2F_1(-n;-n;1;p^2/(1-p)^2).$  It expands to a polynomial of degree $2n.$  Indeed, using the [`hypergeo` library](https://journal.r-project.org/archive/2015/RJ-2015-022/RJ-2015-022.pdf) `R` (a "scientific calculator" if there ever was one!) will compute `n <- 1000;
p <- 2/1000;
((1-p)^(2*n) * hypergeo(-n,-n,1,(p/(1-p))^2))` as 0.2071337, agreeing with the `dbinom` value to 15 significant digits.  Unfortunately there's only about 10% improvement in computation time.
Comment: On a calculator, if you had the patience to sum only 1st 11 terms of series, you'd get close: In R, `f = dpois(0:10, 2); sum(f^2)` returns
0.2070019 because the first few terms are the only large ones. You could see when the squares get too small to matter. // But you should start learning R if this isn't your last prob/stat course. Not _all_ of R. Maybe just a few dozen functions at the start, mostly intuitive.
Comment: FWW (again, now that we're edging toward giving final hwk solutions): For the first few terms of binomial:  `f = dbinom(0:10, 1000, 2/1000); sum(f^2)` returns 0.2071337. // IMHO unless undisclosed directions mandate Poisson aprx, I see no reason to avoid exact binomial computation.
Comment: This is the correct answer. For the first method (Poisson Approximation) - how could this calculation be done with a scientific calculator? Or would there be a table that would need to be consulted? Previous to this question I've figured out the probabilities of 1) Less than 2 black ball, 2) exactly 2 black balls, 3) more than 2 black balls - if that helps.


Why increment operator doesn't work?

Question:
Possible Duplicate:
Undefined Behavior and Sequence Points

int a=10;

a=a++;

a=++a;

a=(a++);

Can you guys please explain to me why none of these cases works?
Comment: They all work, they just don't work the way you expect.
Comment: @PeterLawrey: what do you mean by "They all work"? A code with undefined behavior can hardly be said to "work".
Comment: http://stackoverflow.com/q/4176328/20984
Comment: I just saw that the question was tagged `java` in addition to `C++`. If you are interested in answers for both languages, you should clarify that in your question (and probably remove the use of `cout` which make it seems like this question is only about c++).
Comment: @LucTouraille I think he means that they all behave as would be expected from the code, thus for the OP it is the expected behaviour that is wrong and not the code.
Comment: @LucTouraille, It is defined in `Java`, I forgot it wasn't defined in `C++` Perhaps in a later spec...
Comment: oops, i actualy wrote the code in c++ and tried to run in codepad.org , but it gave me warning/error and din work! while writing the question, i felt like its general in java and c++ , so i tagged them like that, nyways correctd :)
Comment: @PeterLawrey: Yes, sorry about the comment, I missed the `java` tag...
Comment: @PeterLawrey can you guys please say why it gives error when I run this in codepad.org (coded in c++) ?
Comment: @Sanjay, What is the error? Perhaps it give a hint. ;)
Comment: -1: When I try to run any C++ code on the web site I get "Internal Server Error" You need to ask the people supporting the site as to why it is down.  It has nothing to do with the code you are running.
Comment: Oh, it's Codepad once again. That unreliable thing that pukes errors on just about anything in any language.
Comment: @PeterLawrey Why -1 for "Internal Server Error" , i'm also not responsible for that ! :D btw, the error is "operation on 'a' may be undefined" , here is the link : http://codepad.org/cYXEuRuQ
Comment: Ok I take of -1 for the Internal error and add -1 for not stating that the WARNING (which has nothing to do with it working or not) is that you are trying to use an operation with an undefined behaviour, something we have been trying to tell you as well. The compiler is being run with an option to treat warnings as errors, which it also clearly states.  This is why you need to read messages carefully. If you want to know what they mean, state exactly what they say, not in terms even you don't understand.
Comment: How about READING the error message? "Operation on a may be undefined" is pretty clear to me - and correct at that..
Comment: @PeterLawrey Dear lord! I messed up a lot, and now I understood the thing! I was not able to run it in codepad, and I was eager to know why this may be an undefined behavior.I din think much and thought this might be the same with java and tagged such,my bad.
Comment: @PeterLawrey i mentioned in one of my previous comment "but it gave me warning/error" in which I meant It gave me a warning that turned out to be an error for me! :D never mind!
Comment: @Sanjay, We all make mistakes and we are all learning. Hopefully more learning than making mistakes. ;)
Comment: @PeterLawrey lol I learnt a lot today! can you guys help me to close this, so that I dont get anymore downvotes! :D
Comment: @PeterLawrey my bad, I initially tagged it as java, now I tagged it only c++, in this case I cannot accept your answer! Will you please edit your answer as in case c++ , so that I can accept the answer!
Answer: Use it the right way:
int a = 10;
a++;
cout << a;
++a;
cout << a;

Comment: I know the right way, i just wanted to know whats wrong with this :(
Comment: @Sanjay, You haven't explained what is wrong about it.
Comment: @PeterLawrey it gives error when i try to run it in codepad.org, coded in c++. Please edit the question if needed :) this is what i really mean!
Answer: In answer to the C++ question for this code at http://codepad.org/cYXEuRuQ
#include<iostream.h>
int main()
{
int a=10;
a=a++;
cout<<a;
cout<<"\n";
a=++a;
cout<<a;
cout<<"\n";
a=(a++);
cout<<a;
cout<<"\n";
}

when compiled prints
cc1plus: warnings being treated as errors
In function 'int main()':
Line 5: warning: operation on 'a' may be undefined
Line 8: warning: operation on 'a' may be undefined
Line 11: warning: operation on 'a' may be undefined

This is a warning stating that the operation used is undefined and should not be used if possible. This is because in C++ the order of evaluation of ++ relative to other expressions is not defined and not the same across all compilers. (Generally it doesn't matter and is not a problem except in edge cases like these)
The web site goes further and treats warnings as errors and does not run the code.

If you translate to Java it prints
10
11
11

as expected.  What do you mean by "doesn't work"?
The behaviour is defined in Java, but as LucTouraille points out its not defined in C++ so you can't expect a particular behaviour which is the same for all compilers.
Another example.
int a = 3;
a = a++ * a++;
System.out.println(a); // will always be 12 in Java.

it is the same as
{
    int t1 = a;
    a = a + 1;
    int t2 = a;
    a = a + 1;
    a = t1 * t2;
}

Comment: No, the last value is `11`. I just ran it.
Comment: I tried Java 6 and 7 and the second example produces `12` Why would you expect `a=a++` and `a=(a++)` to be any different?
Comment: @PeterLawrey: I think he's referring to `a=(a++);` which would return `11`.
Comment: @TheEliteGentleman, you are right, the question has been re-written. I previous assumes that each expression would be after `int a=10;`
Answer: The sequence for the algorithm:
    int a=10;

    a=a++;
    System.out.println(a);

    a=++a;
    System.out.println(a);

    a=(a++);
    System.out.println(a);

Is as follows:
a=++a; means that a is incremented first before assigning the expression to a. Thus a = 11.
a=(a++); means can be understood like
b = a;
a++;
a = b;

Hence why you receiving value as 11.
Answer: They all should work.
I'm not sure what language your on. But if your on C/C++ it should work.
Comment: This is not correct, the behavior of these statements is undefined in C++.

Why increment operator doesn't work?


How to include the same menu twice in a .tpl file

Question: I am working on a responsive design for a site I am building and I currently am having trouble including the menu twice in the header template file. I need the menu displayed inside the content wrapper for large devices and outside the template wrapper on small devices so I intende to use bootstrap classes to show/hide the correct menus. However when I include the menu twice in my template file only the second instance is ever displayed. How can I get the menu to render twice in the same template.

    <?php print render($main_menu); ?>

    <?php print render($content); ?>
    <?php print render($main_menu); ?>

Answer: You can probably use the show() function to un-hide the previously rendered element:

    <?php print render($main_menu); ?>

    <?php print render($content); ?>
    <?php show($main_menu); ?>
    <?php print render($main_menu); ?>

Comment: This didn't change anything, the menu is still only displayed where the last call to render it is made.
Comment: Sorry I missed that first time round. It doesn't really make sense that the 1st one fails to render and the 2nd doesn't, have you checked the page markup to confirm the menu isn't rendered?
Comment: I just discovered that the menu was being displayed because I had main menu included in the header block, removing that from the block removed the menu. I'm currently trying to figure out how to include the main menu in the header region template region--header.tpl.php or maybe structure the header differently.
Answer: I was mistaken where the menu was being rendered from. I had the main_menu block included in the header region and so it was being rendered in my header. Once I removed the main menu from the header region the menu was not displayed at all. To display the menu twice in the header region I created a new region for the menu named menu, I assigned the main menu block to that region, and then in my template.php file I store the content of that region as a variable.
function theme_preprocess_region(&$variables){
    $variables['menu_block'] = block_get_blocks_by_region('menu');
}

I can then use the variable $variables['menu_block'] to nest my menu region inside my header region (region--header.tpl.php) wherever I need.

    <?php print render($variables['menu_block']); ?>

    <?php print render($content); ?>
    <?php print render($variables['menu_block']); ?>

Answer: Store the rendered main menu in a variable and then output it twice.
Sounds like the easiest solution unless there are considerations I'm not aware of.
Cheers.
<?php $rendered_main_menu = render($main_menu); ?>

    <?php print $rendered_main_menu; ?>

    <?php print render($content); ?>
    <?php print $rendered_main_menu; ?>

Answer: An alternative answer:
Personally I would say only print the menu once as bootstrap does. This way you don't have the extra markup. If you look at the way Bootstrap has the menu setup you will see what I am referring to there. They target showing the original menu and not a copy of the original menu. You can then restyle their implementation to achieve the same goal as you are needing.


Generalized linear models and central limit theorem

Question: If a comparison of treatment means can be made with ANOVA or GLM because it is assumed errors are normally distributed as suggested by the central limit theorem, why would it be necessary to implement a generalized linear model with non-normal errors?  Does the central limit theorem not apply?
Comment: The CLT has no applicability whatsoever to the distributions of the *errors*.  It tells us only about the distributions of certain of their statistics, such as their means or group means.
Answer: In short: CLT alone isn't sufficient; $n$ isn't always near enough to infinity; and the shape of the distribution of the sample mean isn't the only consideration

If you're using a hypothesis test in your comparison of treatment means in ANOVA, you rely on the distribution of a ratio of two quantities having an F-distribution. You need the numerator and denominator to both be scaled chi-square, and you need them to be independent. If you don't have normality, this won't be the case, and the Central limit theorem on its own doesn't get you there; it's a theorem about what happens in the limit as $n\to\infty$
GLMs and ANOVA are not always carried out at sample sizes for which you could simply assert normality of quantities like sample means (small sample sizes can be a problem with inference in GLMs for a similar reason -- the usual inference relies on other asymptotic results).
GLMs not only deal with non-normality, there are issues like heteroskedasticity, and not all uses of GLMs are direct comparisons of treatment means, so there's often need to deal with nonlinearity as well (which GLMs do via the link function).


Inheritance Example in java

Question: In the example below :
class Parent{
    void fun() {
        System.out.println("Parent class");
    }
}

class Child extends Parent{
}

public class Main {
    public static void main(String[] ar) {
        Child ch = new Child();
        ch.fun();
    }
}

inheritance example,while instantiating object,we can create an object as Parent ch = new Child(); which is valid but why can't we have something like this Child ch = new Parent();
           Thanks in advance.
Comment: every Child is a Parent, not every Parent is a Child. if you had chosen your classnames in a more logical way, it might have been more clear that way.
Comment: @Dragonthoughts Actually it's vice versa - a `Child` is a `Parent` and `Parent` is not a `Child`
Comment: `Parent ch = new Child();` is called polymorphism, used to call the proper implementation at runtime, what you try to do has no sense
Comment: let's simplify it... `class Apple extends Fruit` - every apple is a fruit, but not every fruit is an apple.
Comment: In your inheritance, a `Child` is a `Parent`, but a `Parent` is not a `Child`
Answer: Child ch = new Parent() is invalid because not every Parent is a Child.
Suppose you had a third class:
class AnotherChild extends Parent {int age = 2;}

The following would also be valid:
Parent otherChild = new AnotherChild();

If Cild child = new Parent() were to be made valid, then for the same reason
Child child = new AnotherChild()

Would also have to be made valid because AnotherChild is a Parent.
Now clearly, that is problematic, because Child is different from AnotherChild.
This example is chosen to make it obvious, but even a simple Parent object (new Parent()) is not a Child instance, because it wasn't instantiated with the Child class or any of its sub-classes.
All this is compile-time type checks, which ensures code safety and object/variable compatibility. One can use allowed casts to go around the problem, but if runtime objects are in fact of incompatible types, the execution would still fail.
Answer: In your example you have class Child extends Parent{. This means that a Child is a Parent but Parent is not a Child. Parent is the more generic parent class (Ironic) and Child is the more specific sub class. So you can do something like this:
 Parent ch = new Child();

Because you are declaring the generic Parent object, and then instantiating it as a Child object. However you cannot do:
Child ch = new Parent();

Because you cannot declare it as the more specific Child object and then instantiate it as the less specific Parent object

Inheritance Example in java


Migration syntax errors when adding utf-8 and InnoDB instructions in Rails

Question: I am trying to create this rails migration
class CreateFormats < ActiveRecord::Migration
  def self.up
    create_table (:formats , :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8' ) do |t|
      t.name
      t.description
      t.company

      t.timestamps
    end
  end

  def self.down
    drop_table :formats
  end
end

And I get errors during execution that look like this:
syntax error, unexpected ',', expecting ')'
    create_table (:formats , :options => 'ENGINE=InnoDB D...
                            ^
syntax error, unexpected ')', expecting keyword_end
...=InnoDB DEFAULT CHARSET=utf8' ) do |t|
...                               ^
syntax error, unexpected keyword_end, expecting $end
Any idea why this happened?  I can't find any problems with my syntax..most likely because I am new to Rails :)
Answer: Your syntax is incorrect:
create_table (:formats , :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8' ) do |t|

should be
create_table(:formats , :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8' ) do |t|

i.e: without the space. Otherwise you are simply grouping :formats with :options => ... as the first argument to the function.
You probably also need to change
t.name
t.description
t.company

to something like
t.string :name
t.string :description
t.string :company

Comment: the initial errors got fixed, but now I have this one: undefined method `name' for #
Comment: I just added a note about that to my answer, but the remainder of your table definition syntax is a bit off as well.


entityform email multilingual

Question: I am using drupal 7 and entityform module and also using this : https://www.drupal.org/node/1679794
instruction to sending email after submitting form.
the only problem I have is I want my email body to be translatable in different languages.
I already translated form labels here :
admin/config/regional/translate/translate
I also should add my form is a custom form not user sign up form ! I already know that I can change email body of sign up email here :
admin/config/regional/i18n/variable
using rules module and After saving a new entityform submission event was also useless. it's like the event is not equal to form submission event . happens nothing after form submission.
I also thought it would be helpful if I just could add some varibles to drupal default variables ! but I don't know how .
Answer: This is not answer to your question - but a tip on the way...
There is a good possibility to use Rules + some rules contrib module to do this, maybe in a better way because rules is also able to send node-fields-values trough Tokens id, and also capable to act on site-current-user:language from the users own default language and send mail in preferred user language. Rules can be triggered on different actions at the site.
One of my Rules setting sending mail, where all fields-name are translated together with the fields value, based on user-default-language settings.
Comment: can you be a little more specific . I used RULES tab on entityform and when I add 3 rule for my 3 languages and I make condition for one of them . the other 2 rules change too.
Comment: when suggesting a module, please include a link to the module

entityform email multilingual


Finding matrix relative to a polynomial basis and basis in R2?

Question: Let U be the space of polynomials with basis E=[1,t,t^2], let V=R2 have the basis F=[(1,0),(1,1)] and define a linear map T: U->V by T(f)= (f(3),f'(3)).

Determine the matrix representing T relative to the basis E and F.
What is the Rank of T?
Exhibit a basis for the kernel of T.

I understand how to determine a matrix relative to a single basis in R2, but I've never done it relative to two basis, and never with a polynomial as a basis. Can anyone walk me though how to go about solving this type of problem?
Comment: Please use mathjax to format your question
Answer: HINT
Polynomial of degree 2 in this case are a vector space in the sense that at each polynomial $f(t)=a+bt+ct^2$ we can associate the vector $v=(a,b,c)$.
The linear map $T$ maps a polynomial $f(t)=a+bt+ct^2$ in $(a+3b+9c,b+6c)$. Since we are requeste to use the basis F we need to write $(a+3b+9c,b+6c)$ in this basis that is

$x+y=a+3b+9c\implies x=a+3b+9c-b-6c=a+2b+3c$
$y= b+6c$

Then
$$T(a,b,c)=(a+2b+3c,b+6c)$$
Can you proceed from here?
Comment: Thank you, but I'm having trouble wrapping my head around it... could you go a step further?
Comment: Can you derive the matrix for T from the last step?
Comment: I know I need to turn that into a system of linear equations but I'm confused by the x + y part and how to use it to get to the matrix
Comment: @BrandonGrothe Did you solve the problem? the matrix representation in the standard basis is $\begin{pmatrix}1&3&9\\0&1&6\end{pmatrix}$ with the bais F is $\begin{pmatrix}1&2&3\\0&1&6\end{pmatrix}$


Fisher.test alternative problem in R

Question: I found a weird thing about the "alternative" argument in fisher.test in R
fisher.test(matrix(c(10,5,30,60), 2,2), alternative="greater")$p.value
# [1] 0.01587719
fisher.test(matrix(c(10,5,30,60), 2,2))$p.value
# [1] 0.02063292

fisher.test(matrix(c(3, 10, 2, 37), 2, 2),alternative = "greater") $p.value
# [1] 0.09276711
fisher.test(matrix(c(3, 10, 2, 37), 2, 2)) $p.value
# [1] 0.09276711

Why does the latter matrix return the same p-value, while the former return different p-value?
Answer: According to Wikipedia:

For a two-tailed test we must also consider tables that are equally extreme, .... An approach used by the fisher.test is to compute the p-value by summing the probabilities for all tables with probabilities less than or equal to that of the observed table.

And the probability of each table can be calculated by hypergeometric distribution.
For the first matrix matrix(c(10,5,30,60), 2,2), we can plot the probability against all possible values of the top-left cell (from 0 to 15):

So the two.sided p-value = the sum of the 8 points below the dash line. The alternative greater p-value = the sum of the right most 6 points.
However, for the second matrix matrix(c(3,10,2,37), 2, 2), the points on the left are above the dash line. So there's no difference in two.sided and greater p-values.

The code for the plot:
hypergeometric <- function(x) {
  a <- 0:min(x[1]+x[2],x[1]+x[3])
  prob <- dhyper(a, x[1]+x[2], x[3]+x[4], x[1]+x[3])

  plot(a, prob, xlab='first cell', main='Hypergeometric')
  abline(h=prob[which(a==x[1])], lty=2)

  two_sided <- sum(prob[prob<=prob[a==x[1]]])
  greater <- sum(prob[a>=x[1]])
  less <- sum(prob[a<=x[1]])

  return(c(two_sided, greater, less))
}
hypergeometric(matrix(c(10,5,30,60),2,2))
# two_sided    greater       less
#0.02063292 0.01587719 0.99670182
fisher.test(matrix(c(10,5,30,60),2,2), alternative='two.sided')$p.value
#0.02063292
fisher.test(matrix(c(10,5,30,60),2,2), alternative='greater')$p.value
#0.01587719
fisher.test(matrix(c(10,5,30,60),2,2), alternative='less')$p.value
#0.9967018

hypergeometric(matrix(c(3,10,2,27),2,2))
# two_sided    greater       less
# 0.1623877  0.1623877  0.9741121

Fisher.test alternative problem in R


Are the chart maps of a complex manifold necessarily biholomorphic?

Question: I know that the transition maps of a complex manifold are biholomorphic, but are the chart maps themselves also biholomorphic? I know that it is the case for real smooth manifolds (here the chart maps are diffeomorphisms). Thanks for your help!
Comment: What does it mean to say the chart map is a diffeomorphism if you have an abstract smooth manifold?
Answer: By definition, if $g:U\subset\mathbb{C}\to g(U)\subset X$ is a chart, then the function $g^{-1}:g(U)\to U$ is holomorphic, because $g^{-1}\circ g:U\to U$ is holomorphic for being the identity function on $U$. Likewise, $g:U\to g(U)$ is holomorphic because $g^{-1}\circ g\circ i:U\to U$ is holomorphic, where $i$ is the identity function on $U$, which is also a chart of $\mathbb{C}$. It is a bit redundant because the definition of what functions are holomorphic on $X$ is made such that the charts are iso morphisms between their domain and their range in the corresponding category.
Comment: Thanks for your answer! What about the case where the complex projective space $\mathbb{C}\mathbb{P}^n$ is the complex manifold we consider? I have constructed chart maps from $\mathbb{C}\mathbb{P}^n$ to $\mathbb{C}^n$. Are they biholomorphic?
Comment: @mathismath The chars' domain and its range, not the whole manifold and the domain of the chart.


Certificate Chain with AWS ELB & GoDaddy Certs


Drop data Vs fill data. Which one least hurts the integrity of the data?

Question: I have a dilemma for an analysis I'm currently on. I doing some GARCH modelling of bitcoin and a fiat currency.
There are some null values with the fiat datasets in comparison with bitcoin data as cryptos trade on weekends. The R package I'm using rugarch won't accept null values
Now, I believe I have two choices:

Drop weekend rows of bitcoin
Fill weekend rows of the fiat currency

My question is, are there statistical justifications for either option and which option least hurts the integrity of my model?
Answer: There are plenty of imputation methods but the best is to drop data if you have enough data...
Imputation methods -> http://www.stat.columbia.edu/~gelman/arm/missing.pdf
Example of R package -> https://cran.r-project.org/web/packages/imputeR/imputeR.pdf
Another idea is to use algorithms that can deal with missing values such as XGBoost for example...
For your special case of time series, see -> How to fill in missing data in time series?
And the R package : ImputeTS -> https://cran.r-project.org/web/packages/imputeTS/vignettes/imputeTS-Time-Series-Missing-Value-Imputation-in-R.pdf
In a nutshell, if you can drop periodic data, you may adjust your interpretation either try imputation...
Comment: The model works fine by dropping the weekend data. I am only worried if that invalidates the accuracy of my model and it's predictions. That's why I'm on the lookout for statistical justifications that the drops doesn't invalidate my results
Comment: -1. I think your answer is missing a crucial point: dropping data changes the time dependence structure that is an *essential* feature of time series data. Moreover, your answer would better fit as a comment as the links and terms you provide do not answer the question directly. The direct answer to the actual question is *the best is to drop data if you have enough data*, but that is quite short and needs some elaboration and justification. @Mysterio
Comment: @RichardHardy I know that that's why I have the dilemma. I'm looking at how to overcome this dilemma. What do you recommend?
Comment: @RichardHardy any short answer or links that could help?
Comment: @Mysterio, sorry, cannot remember any good sources right now.
Comment: @RichardHardy would be great if you could provide an expansive answer when you get time. I'm stuck with this dilemma


Under which domain transformations are the eigenvalues of $-\Delta$ invariant?

Question: Let $d\in\mathbb N$, $\Omega\subseteq\mathbb R^d$ be bounded and open, $$\mathfrak a(u,v):=\langle\nabla u,\nabla v\rangle_{L^2(\Omega,\:\mathbb C^d)}\;\;\;\text{for }u,v\in H_0^1(\Omega)$$ and $$P:=-\Delta:C_c^\infty(\Omega)\to C_c^\infty(\Omega).$$ By the Lax-Milgram theorem, $$\forall f\in L^2(\Omega):\exists !v_f\in H_0^1(\Omega):\forall u\in H_0^1(\Omega):\mathfrak a(u,v_f)=\mathcal l_f(u):=\langle u,f\rangle_{L^2(\Omega)}.$$ The map $$S:L^2(\Omega)\to H_0^1(\Omega)\;,\;\;\;f\mapsto v_f$$ is

a bounded linear operator from $L^2(\Omega)$ to $H_0^1(\Omega))$;
a compact linear operator on $L^2(\Omega)$;
a self-adjoint bounded linear operator on $L^2(\Omega)$.

Remember that if $f\in L^2(\Omega)$, then $u\in L^2(\Omega)$ is a weak solution of the symbolic equation $Pu=f$ if $$\langle u,P\varphi\rangle_{L^2(\Omega)}=\langle f,\varphi\rangle_{L^2(\Omega)}\;\;\;\text{for all }\varphi\in C_c^\infty(\Omega).\tag1$$ It's easy to see that $u\in H_0^1(\Omega)$ is a weak solution of $Pu=f$ iff $$Sf=u\tag2.$$
By the spectral theorem, $$S=\sum_{i\in I}\mu_ie_i\otimes e_i,$$ where the sum converges in $\mathfrak L(L^2(\Omega))$ and $I:=\mathbb N\cap[0,\operatorname{rank}S]$, for some $(\mu_i)_{i\in I}\subseteq(0,\infty)$ nonincreasing and some orthonormal basis $(e_i)_{i\in I}$ of $\overline{\mathcal R(S)}^{L^2(\Omega)}$. Moreover, if $$\mu_n:=0\;\;\;\text{for }n\in\mathbb N\setminus I,$$ then $$\mu_n\xrightarrow{n\to\infty}0\tag3.$$ As usual, $(e_i)_{i\in I}$ can be supplemented to an orthonormal basis $(e_n)_{n\in\mathbb N}$ of $L^2(\Omega)$ by an orthonormal basis $(e_n)_{n\in\mathbb N\setminus I}$ of $\mathcal N(S)$.
If $$\lambda_n:=\left.\begin{cases}\displaystyle\frac1{\mu_i}&\text{, if }\mu_i\ne 0\\\infty&\text{, otherwise}\end{cases}\right\}\;\;\;\text{for }n\in\mathbb N,$$ we immediately see that $e_i\in H_0^1(\Omega)$ and $e_i$ is the unique weak solution of $Pu=\lambda_ie_i$ for all $i\in I$.

Let $\tilde\Omega\subseteq\mathbb R^d$ be bounded and open. Assume $\tilde\Omega=\iota(\Omega)$ for some $\iota:\Omega\to\tilde\Omega$. Under which assumption on $\iota$ will the eigenvalues $\tilde{\lambda_i}$ of $$\tilde P:=-\Delta:C_c^\infty(\tilde\Omega)\to C_c^\infty(\tilde\Omega),$$ obtained in the same way as the $\lambda_i$, coincide with the eigenvalues $\lambda_i$ of $P$?

Clearly, if $\iota$ is a $C^1$-diffeomorphism with $$\left|\det{\rm D}\iota\right|=1\tag4,$$ we easily see that $$\tilde e_n:=e_n\circ\iota^{-1}\;\;\;\text{for }n\in\mathbb N$$ is an orthonormal basis of $L^2(\tilde\Omega)$. I guess that's the least we need to assume.

But what do we need to assume further? Do we need $\iota$ to extend to a linear isometry on $\mathbb R^d$ or something like that?
Answer: The question when two domains have the same Laplacian eigenvalues has been popularized as "Can one hear the shape of a drum" by Kac and has received a lot of research interest.
Some (increasingly less) simple observations:

It is clearly sufficient that $\iota$ is an isometry, because in this case $f\mapsto f\circ \iota$ is a unitary operator from $L^2(\tilde\Omega)$ to $L^2(\Omega)$.
You cannot expect to extract too much information on the map $\iota$ itself, because the input data only fix the range of $\iota$. The better question would be when there exists a map between $\Omega$ and $\tilde \Omega$ with nice properties.
To get an interesting result, you should make at least some minimal assumptions on the boundaries of the domains. Otherwise, you can always just remove a set of capacity $0$ from $\Omega$ without changing the eigenvalues of $\Delta$. For example, the Laplacian on the disk and the Laplacian on the disk with countably many points removed have the same eigenvalues. In this case, the domains are not even homeomorphic.
Even for Lipschitz domains, there does not need to exist an isometry between $\Omega$ and $\tilde \Omega$. The existence of isospectral domains that are not isometric was first proven by Gordon, Webb and Wolpert building on previous work most notably by Sunada. You can find pictures of a pair of such domains in the wikipedia article linked above.
To the best of my knowledge, the question whether isospectral domains are are necessarily isometric is open for some very natural classes such as convex domains and domains with $C^\infty$-boundary.
$\Delta$ and $\tilde \Delta$ have the same eigenvalues if and only if there exists a unitary $U\colon L^2(\Omega)$ to $L^2(\tilde \Omega)$ such that $U\Delta=\tilde \Delta U$. The reason why this question often has a negative answer is that there are just too many isometries of $L^2$. If in contrast $V\Delta_p=\tilde \Delta_p V$ for the Laplacians acting on $L^p$ and a surjective isometry $V\colon L^p(\Omega)\to L^p(\tilde \Omega)$, then $\Omega$ and $\tilde \Omega$ must be isometric under minor regularity assumptions by work of Arendt.
Comment: I've almost figured it out, but I'm still not able to see why it is sufficient to have an isometry $\iota$. Please take a look at the question I've asked for that: https://math.stackexchange.com/q/4034335/47771.


Error in the proof for scaling the period of a function that leads to $f(x + p) = f(x) \Rightarrow f(x + p / k) = f(x)$

Question: The question is about scaling the period of a periodic function. This question has been asked and answered. What bothers me is something else:
For $k \ne 0$
$f(x + p) = f(x) \Rightarrow f(kx + p) = f(kx)$ (1)
$f(kx) = f(k (x + p / k))$ (2)
$f(x) = f(kx / k) = f(x + p / k)$ (3)
I must have misunderstood something, because (3) is definitely not valid for every $k\ne0$. Counter example for (3): $cos(0) \ne cos(0 + 2\pi/100)$.
Answer: You're mixing up $f$ and $g$ from that answer. It's true that $g(0) = g(0 + 2\pi/100)$ does not hold for $g = \cos$, but it holds for $g(x) = \cos(100x)$.
Comment: @tmaric, because (the second equation in) 3 does not follow from any of the previous statements. It seems that you are reaching that conclusion by applying an implication like $f(x) = f(y) \implies f(x/k) = f(y/k)$, which is certainly *not* true. In fact, you have given the counterexample yourself, with $f = \cos, x = 0, y = 2\pi, k = 100$.
Comment: Thanks. I wanted to see what would happen if I wouldn't use $g(x)$ in the proof, hence this question. I still can't see the specific error in the statements and I know that 3 is not valid. If the statements that lead up to 3 are true, how come 3 is false?
Comment: Thanks a lot! That is what I was missing.
Answer: $(3)$ is not valid of course, because it claims that $f$ is $\frac{p}{k}$-periodic $\forall k \ne 0$, which is cleary an absurd condition.
On the contrary the new function $g(x) := f(kx)$ has period $\frac{p}{k}$ because $g$ is simply a dilation/contraction of $f$:
$$g\left(x+\frac{p}{k}\right) = f\left(k\left( x+\frac{p}{k}\right)\right) =  f\left(k x+p\right)  = f\left(k x \right) = g(x)$$
Comment: Thanks. I understand that, but check out my comment to Mees de Vries.


Ajax envia consulta php em Mysql

Question: Olá amigos estou estudando Ajax estou tentando fazer essa execução de código funcionar, mas ainda não consegui.
Estou tentando fazer após formulárioprodutos ser selecionador é enviado para consultarcor.php via Ajax as informações para consultar as cores de cada produto selecionado consultarcor.php verifica e o resultado devolvido paracores como <option> para seleção em outro formulário.
Alguém pode verificar o que cometi de errado pois o Ajax não funciona.
 function showHint(str) {
   if (str.length == 0) {
    document.getElementById("produto").innerHTML = "";
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    var vasr="cor=";
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("produto").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("POST", "consultacor.php"+str, true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(vasr);

Formulario Html

     <input type="text" size="2" maxlength="2"name="quant" placeholder="Quant." onkeypress="return maskKeyPress(event)"/>
     <input list='produtos' name='produto' onchange="showHint()"/>
     <datalist id='produtos'><?php
      $sql= mysqli_query($conn,"select DISTINCT descricao from produtos  order by descricao");
      while ($resp = mysqli_fetch_array($sql)) {

     $group=$resp['descricao'];
      echo "

         ";
          }
      ?> </datalist>

      <input list='cor' name='cor'/>

Codigos dentro de consultacor.php
    <?php
    include "conecta.inc";
    $q[]= $_POST['produto'];
    $q = array_filter($q);

    $query.= "select * from produtos where descricao='$q'";

    $x = mysqli_query($conn,$query );

    while($prt=mysqli_fetch_array($x)){
    $cor[]=$prt['cores'];

    echo "
    <datalist id='cores'>
    <option value='$cor'>
    </datalist>";
     }
     ?>

Este é o erro apresentado "console"
ficha.php:110 Uncaught TypeError: Cannot read property 'length' of undefined
Comment: Olha no console do navegador, para ver qual erro é
Comment: não apresenta o erro apenas não executa a consulta.
Comment: muda `$query.= "select * from produtos where descricao='$q'";` por `$query = "select * from produtos where descricao='$q'";`
Comment: vc chegou ver se existe algum valor em `$_POST`, da um `print_r()`nele.
Answer: A quantidade de incoerências no código é grande.
No HTML não existe um elemento cujo id seja produto, você esta usando a tag getElementbyId para pegar uma id que não existe ao longo do código, e analisando o mesmo, você deveria usar getElementsByName("produtos"), assim, para tentar recuperar o valor do teu produto selecionado e então seguir adiante.
Já no PHP, o <datalist id="cores"> não equivale ao <input list="cor" /> seguido disso, imagino que o while iria imprimir muitos <datalist> ao invés de carregar uma lista de <option> dentro do <datalist>.
Sugiro dar uma boa revisada no código, e pra trabalhar com ajax comece a  utilizar o "console" do navegador para identificar os erros de forma mais rápida.
Comment: Estarei revisando o código e farei as correções sugeridas

Ajax envia consulta php em Mysql


Do we need hash in Config Sync Directory if outside root

Question: If we set the config directory to be outside root and plan on committing the configuration to git, do we need (or is it recommended) to use hash in the config folder name?
Answer: The only purpose of the hash is to make it impossible to guess the location of the exported config. This is an additional access control in case .htaccess in the sync folder fails to do this.
If the config folder is outside of the root of the webserver you don't need the hash.


Find Coordinates in One Dataset That Match A Buffer of Coordinates in Another Dataset in R

Question: I have two datasets, one smaller dataset (4000 rows) that contains information about different stores with each shops lat/long coords and one large dataset(600K Rows) that contains information about people who live in the area with their lat/long coordinates.   Im trying to find how many people live within a certain distance from each store. I also want to do this for multiple distances.   IE- for every store find how many people live within 200 meters, 500 meters, 1KM, 2M from the store.
How can I go about doing this efficiently using R?
Brief pseudocode is below
for(store in stores){
  for(distance in distances){
    store[distance] <- find_people_within_distance(store,distance)
  }
}

find_people_within_distance(store,distance){
  # Return number of People in People dataset who's geocoordinates fall within the distance range from stores
}

Thanks!
Comment: Have you already looked at answers like: https://stackoverflow.com/questions/31668163/geographic-geospatial-distance-between-2-lists-of-lat-lon-points-coordinates and https://stackoverflow.com/questions/21977720/r-finding-closest-neighboring-point-and-number-of-neighbors-within-a-given-rad ?
Comment: Yes unfortunately when I try these solutions my memory limit is exhausted.  My laptop is only 8gb ram.
Comment: Well that's certainly going to be a problem for data that size.
Comment: take a look at `fuzzyjoin::geo_join()`
Answer: I think that if you are not interested in the actual distance between people and stores but only in counting how many people live within a certain threshold distance from each store you can adopt the following approach.
# packages
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1

The example is based in Milan and the points are sampled at random from that area.
milan <- osmdata::getbb("Milan, Italy", format_out = "sf_polygon") %>%
  magrittr::extract2("polygon") %>%
  st_transform(crs = 3003) %>%
  st_geometry()

simulate data for the stores and the people
stores <- st_sample(milan, size = 4000)
system.time({
  people <- st_sample(milan, size = 600000)
})
#>    user  system elapsed
#>  127.50    1.80  142.74

Buffer the store points
system.time({
  stores_buffers <- st_buffer(stores, dist = units::set_units(200, "m"))
})
#>    user  system elapsed
#>    0.68    0.01    0.75

Check how many people lie within each buffer:
system.time({
  people_ids <- st_contains(stores_buffers, people)
})
#>    user  system elapsed
#>   15.02    0.36   16.44
head(lengths(people_ids))
#> [1] 430 427 410 393 438 274

Maybe there are more efficient approaches for this problems (for example you can check the R package polyclip) but, at the moment, it takes less than 20 seconds to estimate how many people live in those buffers.
Created on 2020-07-06 by the reprex package (v0.3.0)


Spring4d - Automatic factory with service name

Question: I am trying to use the automatic virtual factory functionality of Spring4d. Though, I would like to be able to pass the ServiceName I want to resolve inside the factory Build() function. Like so : AFactory.Build(AServiceName)
For example
TMyComponent1 = class(TInterfacedObject, IMyService)
public
  constructor Create(AArgument : TObject);
end;

TMyComponent2 = class(TInterfacedObject, IMyService)
public
  constructor Create(AArgument : TObject);
end;

TMyComponent3 = class(TInterfacedObject, IMyService)
public
  constructor Create(AArgument : TObject);
end;

// Registering components

AContainer.RegisterType<TMyComponent1, IMyService>('Service1');
AContainer.RegisterType<TMyComponent2, IMyService>('Service2');
AContainer.RegisterType<TMyComponent3, IMyService>('Service3');

// Factory interface

IMyFactory = class(IInvokable)
[Guid]
  function Build(AArgument : TObject; AServiceName : string) : IMyService;
end;

// Factory registration

AContainer.RegisterType<IMyFactory>.AsFactory();

// Use factory

AContainer.Resolve<IMyFactory>(AObject, 'Service1'); // Should resolve TMyComponent1

I would like the factory to resolve the TMyComponent1 when AServiceName = 'Service1', TMyComponent2 when AServiceName = 'Service2', etc.
How can I acheive this?
Answer: You currently can't. Parameters all go through to the resolver being used as potential constructor parameters.
It might be worth a feature request to be able to annotate a parameter of the factory interface to use that as the requested service type.
However this will not be implemented any time soon as for 1.3 I have some changes to the system planned which will make contextual injection and registration possible. This will then possibly enable not only to determine the resolved service by its name but by any possible meta information provided.


Drupal Newbie - Upgrade Questions

Question: I am a Drupal newcomer and have been tasked with updating a Drupal site.
The currently installed version is 7.2.1
I have taken a full backup of both SQL and files so I am safe if anything goes wrong.
My question is the upgrade for Drupal a manual one, as in, do I have to download the update and FTP it over?  I am used to Wordpress being a one-click affair!
Also, is there anything I should be aware of?
Answer: Yes, the update is manual. (As someone new to Drupal, you may not know about the command line tool drush, which is as close as we get to being a one-click affair. Drush is awesome, and once you get more familiar with Drupal, you should learn it. It makes your work much more efficient.)
Re the previous answer, 'Download these updates' only works for contributed modules and not for core.
The instructions on drupal.org are excellent.  But before you start, here are a couple of pieces of useful information.

Do not get confused by the instructions at the top of the page sending you to upGRADE instructions.  An upGRADE means moving from one version of Drupal to another, e.g., Drupal 6 to Drupal 7, and is a much bigger deal. An upDATE moves you up by minor versions, e.g., Drupal 7.2.1 to 7.28.
Because you are new to Drupal, it would probably be a good idea to make sure the previous developer did not make the classic error of putting contributed modules and themes in with core modules.  When you do the update you will delete all files EXCEPT [drupal root]/sites, which is where contributed modules, and site-specific files live. On your site, go to admin/reports/updates/list. Open another window in whatever file browser you use, and look at the Drupal file structure.  The list of modules in the update list should match up to folders in [drupal root]/sites/all/modules.  If instead you find those folders in [drupal root]/modules, you have bigger problems than can be answered here.  (Same goes for themes.)
If you have a development and/or staging site in addition to the live site, do the updates there first.  If you don't have non-live sites, you should create them.  You can do updates on a live site, but it's much preferable to test them first.

Sorry, long answer.  There's a lot more good stuff on drupal.org, but it can be hard to find.  I usually use Google to search drupal.org.
Comment: Ok, i've carried out the update and run the update.php, now everything looks like the style sheet is missing.  Dashboard, main site, everything!  I have changed the theme to a default one and it still looks broken.  any ideas?
Comment: Without actually seeing your site it's hard to know. Two things to try: 1.  Go to admin/config/development/performance and click Clear Caches.  2.  On that same page, uncheck aggregation for CSS and JS files.  If those don't work, see if you can find someone to look at the site with you.  Too many variables to diagnose from here.
Answer: You can use Update manager module (enable it on admin/modules) and then go to admin/modules/update to see what needs to be updated and then get it automatically updated with 'Download these updates' button (after ticking the checkboxes for modules/core that you desire to update).
As a rule of thumb, if your site is not extensively complicated or it does not rely heavily on some version-specific code, you should be safe to update.

Drupal Newbie - Upgrade Questions


Macro just for specific cell range

Question: I got the following macro in my workbook:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Clear the color of all the cells
Cells.Interior.ColorIndex = 0
If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub
Application.ScreenUpdating = False
With ActiveCell
    ' Highlight the row and column that contain the active cell, within the current region
    Range(Cells(.Row, .CurrentRegion.Column), Cells(.Row, .CurrentRegion.Columns.Count + .CurrentRegion.Column - 1)).Interior.ColorIndex = 8
    Range(Cells(.CurrentRegion.Row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.Row - 1, .Column)).Interior.ColorIndex = 8
End With
Application.ScreenUpdating = True
End Sub

But I would like it to work just on the cells F8:IR254, which is a region matrix.
Currently it works in every cell which contains a region name, also outside the matrix.
Would that be possible?
Thanks in advance.
Kind regards,
S
Answer: Yes, it is possible.
You must add those lines of code at the beginning of your Sub:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rng As Range: Set rng = Range("F8:IR254")
    If intersect(Target, rng) Is Nothing Then Exit Sub

Answer: You must use the function Application.Intersect() to know if two (or more) ranges have a common part or not.
Please find your amended code :
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub

If Not Application.Intersect(Target, Me.Range("F8:IR254")) Is Nothing Then
    'Clear the color of all the cells
    Cells.Interior.ColorIndex = 0
    Application.ScreenUpdating = False
    With ActiveCell
        ' Highlight the row and column that contain the active cell, within the current region
        Range(Cells(.Row, .CurrentRegion.Column), Cells(.Row, .CurrentRegion.Columns.Count + .CurrentRegion.Column - 1)).Interior.ColorIndex = 8
        Range(Cells(.CurrentRegion.Row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.Row - 1, .Column)).Interior.ColorIndex = 8
    End With
    Application.ScreenUpdating = True
Else
    'Outside of matrix
End If

End Sub

Comment: Thanks, this also worked just like Mielks answer. For me as a newbie with VBA, Mielks answer is easier to follow. Thanks anyway!

Macro just for specific cell range


Execute cron job automatically after a specific interval of time in windows

Question: I've created a custom module in drupal and implemented hook_cron. My hook is working perfectly, when I click on run cron button from admin interface.
How can I automatically execute my hook after a specific time interval is passed,  without clicking on the Run cron button from the administrative interface?
Answer: Drupal supports two types of cron jobs:
Poormanscron
This is the default Drupal 7 cron, where at the end of a page request after a certain amount of time, hook_cron is called. This is controlled by the Run cron every ... setting at admin/config/system/cron.
This means that if cron is configured to run every 3 hours, the first user to visit the page after 3 hours will trigger cron. This also means on a low-traffic site that it can many more hours before cron is actually called.
Scheduled cron
This is a much more reliable method which does not involve the user. The principle is that the cron page is called from an external source (usually crontab on the server) at a set interval. As long as the server is up, it will run guaranteed every 3 hours.
In order to enable this, make sure to disable Poormanscron at admin/config/system/cron (set it to run never). And create a cron job (General and Linux manual).
In case of a Windows environemt, one can use Windows' built in scheduled tasks. Please refer to this manual page.
UPDATE
Be aware that the manual is a little outdated, since Drupal 7 the cron script is protected by a token (to prevent DDoS). So where you see to call http://www.example.com/cron.php, add your site specific token. This can be found on your site's status page and looks like this: http://www.example.com/cron.php?cron_key=xxxxxxxxxx.
Answer: Create a Drupal 7 Module. Then add this following function.
function my_sample_module_cron() {
    $sample_module_rule =  60 * 60; //Second * Minute [You can d0 60 * 60 * 2 for running cron in every two hours
    $date = date("Y-m-d H:i:s", time());
    if ((time() - variable_get('sample_module_rule ', 0)) > $sample_module_rule ) {
        variable_set('sample_module_rule ', time());
        sample_function();
    }
}

Now visit admin/config/system/cron in Administrator Login.

From Run cron every option select the time gap for each cron run. In there you will find option from "One Hour" to "1 Week".
If you need smaller timegap install Ultimate Cron Module - https://www.drupal.org/project/ultimate_cron .
Where you will be able to setup Advance Cron settings.


Perform PCA Transformation with N_components = Original_num_of_Dimensions

Question: I'm currently studying the Principal Component analysis. I got a rough idea on how it works and I was wondering if applying PCA on a Dataset of n Dimensions make sense if you set the number of principal components = n.
Thanks
Answer: If you did center the data in the first step (which is required), then PCA with all dimensions is "only" a rotation of the dataset without loss of Information.
After the rotation (if you sort the eigenvectors descending regarding their Eigenvalues) the first Dimension is the one with the highest variance of data.
If it does make sense depends on what you expect.
An example could be the picture from the german Wikipedia site for PCA


How to avoid caching in sqlalchemy?

Question: I have a problem with SQL Alchemy - my app works as a constantly working python application.
I have function like this:
def myFunction(self, param1):
   s = select([statsModel.c.STA_ID, statsModel.c.STA_DATE)])\
                        .select_from(statsModel)

   statsResult = self.connection.execute(s).fetchall()

   return {'result': statsResult, 'calculation': param1}

I think this is clear example - one result set is fetched from database, second is just passed as argument.
The problem is that when I change data in my database, this function still returns data like nothing was changed. When I change data in input parameter, returned parameter "calculation" has proper value.
When I restart the app server, situation comes back to normal - new data are fetched from MySQL.
I know that there were several questions about SQLAlchemy caching like:
How to disable caching correctly in Sqlalchemy orm session?
How to disable SQLAlchemy caching?
but how other can I call this situation? It seems SQLAlchemy keeps the data fetched before and does not perform new queries until application restart. How can I avoid such behavior?
Comment: How are you changing the data in the database ? Is that changed committed ?
Comment: I change it manualy. The database engine is MySQL. Yes, the change is committed.
Comment: http://stackoverflow.com/a/15788051/497208 can be useful
Answer: Calling session.expire_all() will evict all database-loaded data from the session.    Any access of object attributes subsequent emits a new SELECT statement and gets new data back.  Please see http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#refreshing-expiring for background.
If you still see so-called "caching" after calling expire_all(), then you need to close out transactions as described in my answer linked above.
Answer: A few possibilities.

You are reusing your session improperly or at improper time.  Best practice is to throw away your session after you commit, and get a new one at the last possible moment before you use it.  The behavior that appears to be caching may in fact be due to a session lifetime being very long in your application.
Objects that survive longer than the session are not being merged into a subsequent session.  The "metadata" may not be able to update their state if you do not merge them back in.  This is more a concern for the ORM API of SQLAlchemy, which you do not appear so far to be using.
Your changes are not committed.  You say they are so we'll assume this is not it, but if none of the other avenues explain it you may want to look again.

One general debugging tip: if you want to know exactly what SQLAlchemy is doing in the database, pass echo=True to the create_engine function.  The engine will print all queries it runs.
Also check out this suggestion I made to someone else, who was using ORM and had transactionality problems, which resolved their issue without ever pinpointing it.  Maybe it will help you.
Answer: You need to change transaction isolation level to READ_COMMITTED
http://docs.sqlalchemy.org/en/rel_0_9/dialects/mysql.html#mysql-isolation-level

How to avoid caching in sqlalchemy?


SSL - subjectaltname vs. commercial

Question: I'm reading about how to install SSL in the linode.com library.   Why would one choose the commercial approach over the subjectaltname approach?  The subjectaltname approach allows the flexibility to host multiple secure DNS while the commercial approach does not.  So why not just stick with the subjectaltname approach?
Answer: If you have multiple sites to secure on one server, using SubjectAltNames (with a SAN or UC SSL certificate) is a great solution. It is slightly more secure to use separate certificates for each site, but the difference is negligible in most cases.
Comment: Sometimes in Firefox, I get a warning message about an SSL and it asks me to make an exception before proceeding.  Do you know if issues of this nature will exist with the subjectaltname approach?
Comment: No, they won't exist.

SSL - subjectaltname vs. commercial


elementary abelian 2-groups extension

Question: $2^n$ denotes elementary abelian 2-groups of rank n.
I am reading a paper which has $2^4.2^3 = 2^5.2^2$
Are these two extensions equal? Are there any facts I am not aware of? Because I checked an example: $Z_p$ extended by $Z_p$ x $Z_p$ can be nonabelian. So what if the left is elementary abelian and the right is not abelian.
Answer: $2^4.2^3$ does not denote a single group, it denotes an arbitrary group $G$ with an elementary abelian normal subgroup $N$ of order $2^4$, such that $G/N$ is elementary abelian of order $2^3$.
Similarly for $2^5.2^2$, and the set of isomorphism classes of groups with structure $2^4.2^3$ is certainly not equal to the set with structure $2^5.2^2$, although of course some groups, such as an elementary abelian group of order $2^7$ lie in both sets.
I suspect that in the paper that you are reading there is more information about the specific group in question, which might well fall into both classes.

elementary abelian 2-groups extension


Properly adding an action to a ContentEntityForm

Question: I've created an add/edit form for a custom entity type, which extends Drupal\Core\Entity\ContentEntityForm. By default this form always comes with a "Save" button, and a "Delete" button if editing. I've been asked to add a "Cancel" button as well, but can't figure out how this is supposed to be done in Drupal.
I've seen plenty of answers about using hook_form_alter(), but nothing that is really working. My current solution is to add
$form['cancel'] = array(
    '#type' => 'submit',
    '#weight' => 10001,
    '#submit' => array('cancel_submit'),
    '#value' => t('Cancel'),
);

to the form's form() function, where cancel_submit() is a custom function, but that renders like  which looks awful.
How can I get the two buttons to be in line with each other? Is there a way to properly add a button to the form actions?
Answer: This is relatively simple when you define the form class yourself and one of the reasons Drupal 8 has gone all out on OOP. What you need to do is to extend the form class and implement the ::actions method. This would look like this:
class CustomEntityForm extends ContentEntityForm {
  ...

  protected function actions(array $form, FormStateInterface $form_state) {
    $actions =  parent::actions($form, $form_state);
    $actions['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelSubmit'],
    ];
    return $actions;
  }

  public function cancelSubmit($form, FormStateInterface $form_state) {
    // Du custom submit validation
  }

}

You could also achieve this with normal form alter, but would need to place the submit button inside the actions element, which is usually called actions, fx
$form['actions']['cancel'] = array(
  '#type' => 'submit',
  '#weight' => 10001,
  '#submit' => array('cancel_submit'),
  '#value' => t('Cancel'),
);

Comment: Thanks for the answer. I'm attempting your first method, but it's crashing my site with this message: "The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 1 passed to Drupal\Core\Render\Element::children() must be of the type array, null given, called in {directory}\core\lib\Drupal\Core\Entity\EntityForm.php on line 206 and defined in Drupal\Core\Render\Element::children() (line 71 of core\lib\Drupal\Core\Render\Element.php)."
Comment: @saramm1 I updated the code in the first method, you should note that code is mostly example code, not meant for copy/paste without edits


The union of any directed set of the closed sets of algebraic closure operator is closed?

Question: In "Notes on Lattice Theory" J. B., there is a theorem such that

Let $\Gamma$ be a closure operator on a set $X$. The following are equivalent.
(1) $\Gamma$ is an algebraic closure operator.
(2) The union of any up-directed set of $\Gamma$-closed sets is $\Gamma$-closed.
(3) The union of any chain of $\Gamma$-closed sets is $\Gamma$-closed.

and A subset $D$ of an ordered set $P$ is said to be up-directed if for every $x,y \in D$ there exists $z \in D$ with $x \leq z$ and $y \leq z$.
The definition of algebraic closure operator

A closure operator $\Gamma$ on a set $X$ is said to be algebraic if for every $B \subseteq X$,
$$\Gamma(B) = \bigcup \{\Gamma(F): F\ \text{is a finite subset of}\ B\}.$$

How to proof this theorem? like (1) $\Rightarrow$ (2), i cant figure out whats the up-directed set of closed set here.
Comment: what is the definition of an algebraic closure operator on $X$?
Comment: [this classical paper](https://www.ams.org/journals/tran/1948-064-02/S0002-9947-1948-0027263-2/S0002-9947-1948-0027263-2.pdf) seems to be the basis..
Comment: Added the definition of algebraic closure operator.
Comment: @HennoBrandsma thanks!!!
Answer: For 1 to 2, let $\mathscr{C}$ be a an up-directed family of $\Gamma$-closed sets.
(This means that $\Gamma(C)=C$ for all $C \in \mathscr{C}$ and $C_1,C_2 \in \mathscr{C}$ implies that there is a $C_3 \in \mathscr{C}$ that contains them both (the up-directed part). Let $\hat{C}= \bigcup \mathscr{C}$ and we have to show $\hat{C}$ is closed.
Now take any finite $F \subseteq \hat{C}$. So for any $f \in F$ we have some $C_f \in \mathscr{C}$ so that $f \in C_f$. Now we apply the up-directedness (which we can extend to finitely many sets by induction) and find some $C_0 \in \mathscr{C}$ such that $C_f \subseteq C_0$ for all $f \in F$ and so $F \subseteq C_0$. It follows that $\Gamma(F) \subseteq \Gamma(C_0) = C_0 \subseteq \hat{C}$ (by $\Gamma$-closedness of $C_0$ and monotonicity of $\Gamma$ under inclusion).
So this holds for all finite subsets of $\hat{C}$ and now using the fact that $\Gamma$ is an algebraic closure:
As $$\Gamma(\hat{C}) = \bigcup \{ \Gamma(F)\mid F \subseteq \hat{C} \text{ finite }\}\} \subseteq \hat{C} \subseteq \Gamma(\hat{C})$$
so $\hat{C}$ is $\Gamma$-closed.
(2) implies (3) is trivial as a chain of subsets is an up-directed family.
Comment: According to hint in the exercise in the notes, (3) to (1) must be shown by transfinite induction on the cardinality of the set $S$ we're taking the closure of.
Comment: thanks very much! i was wondering how to whats the up-directed set here, now i can understand the relation here is set inclusion!
Comment: @maplgebra yes that's common usage for families of subsets.


wind instrument tone - good practice routine?

Question: I understand that to get a good tone the best exercise is to play long tones. There are tons of variations of long tone exercises:
a) starting pianissimo and ending fortissimo for as long as you can hold it (ideally over 10 seconds) over the whole range
b) starting fortissimo and ending pianissimo over the whole range
c) Do a constant volume long tone over the whole range
d) Do long tone scale work
And I can imagine tons of other variations. What would you recommend as a routine for tone improvement?
Does it matter much which specific long tone exercise you pick? Or it's more important to do it for longer periods of time? Is 10 minute long tone daily enough to see improvement in a few months?
Comment: I'll answer a question you didn't ask: "Is there an amount of time that's too much?" Yes. You're not just learning a skill in this case, you're also making physiological change, expanding your lungs, and there is such a thing as over-training. (Though I imagine your _lips_ will tell you they've had enough first!)
Answer: There's a lot in your question. I'm going to relay what my teacher told me recently which is that excellent tone takes a long time, maybe five to fifteen years. No matter what you do, if you practice clarinet in some way every day, and you build up to around an hour of practice or more every day, you will definitely improve in many areas over a period of six months.
One thing is as the student, it's hard to notice your improvement so you might get frustrated more easily if you don't record yourself and listen back weeks or months later. Another option is to have a teacher who reminds you of how far you've come.
All of that said, your most efficient progress will come by not focusing on only one aspect of playing for long periods (like only tone or only fingering or only articulations). By practicing broadly, all of those things will slowly improve together.
Combining my experience with my teacher's comments suggests that better tone comes from multiple little areas. Those include proper breathing, strength and endurance of your embouchure, precise control of your embouchure, and even fingering to some extent. Along with embouchure strength comes the ability to play the appropriate reed stiffness. Finally, the quality of the reed and the instrument itself make noticeable contributions.
To summarize my point, there isn't an exercise that mainly develops tone. The upside is that all of your playing will slowly lead to better tone, especially if you spend some time listening to your tone every time you play and make tiny adjustments to improve it. As your upper range extends and your lips and tongue develop strength, flexibility, and muscle memory of the precise positions, your tone will improve while you work on other things. And it won't help to be impatient about it - it takes time.
All of that said, there are long tone exercises that can help in several areas at once and long tones are one good type of warmup. My teacher has run me through various long tone exercises in the last six months, each focusing on one or more problem areas that I've had.
Many, if not most, teachers will happily give you a lesson over the Internet and won't mind giving you a single lesson every few months, so you don't need to spend hundreds a month on weekly lessons to get some professional advice. Consider reaching out on Facebook or online classifieds to find a teacher, who could be anywhere in adjacent time zones to find a teacher who is willing to do a one hour lesson to hear you play a bit and suggest a practice routine for the next several months.
Answer: The advantage of doing long tones, especially the pp -- ff -- pp kind, is that you can concentrate solely on tone quality (and breath control of course).
As Todd W suggests, it's equally important to be doing the correct things to achieve that tone, which is why having a good teacher observe your mechanics is critical.
But, to paraphrase  several band directors I've known, "tone quality practice ends when practice ends."  Which is to say, as much as possible try to be aware of your tone during all aspects of practice.  If nothing else, a collapse of tone can be a good indicator of the passages which cause you the most difficulty in rhythm, mechanics, or something else.
Comment: My experience with long tones (on both clarinet and French horn) that vary in dynamics is that I've learned to control dynamics but even more to refine my embouchure. There are notes where it's easy to play them ff but as I go to pp I have to fix embouchure problems to keep the note, and at least on the lower range of the clarinet a few notes that are easier at pp than ff in the same way.


How do I convert a multi-line string of numbers into a 2d array of integers?

Question: I'm doing a Project Euler problem (https://projecteuler.net/problem=18) and want to paste in the triangle as a multi-line string and convert it into a 2d array of integers. I assume you use list comprehension with string splitting and the int() function but everything I try either turns it into a 1d array or doesn't compile.
Comment: You read line by line and map `string.split()` to int and append to an list
Answer: A nested list comprehension will work. First, split on '\n', then split on ' ', then convert each of those numbers to an integer.
triangle = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"""

triangle_lst = [[int(num) for num in row.split(' ')] for row in triangle.split('\n')]


The website encountered an unexpected error. Please try again later. as shown in body

Question: I tried to set up my drupal 8 full project on localhost but after set up when I run project
getting error as shown below:-
The website encountered an unexpected error. Please try again later.
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "node" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 150 of core\lib\Drupal\Core\Entity\EntityTypeManager.php).
Drupal\Core\Entity\EntityTypeManager->getHandler('node', 'storage') (Line: 208)
Drupal\Core\Entity\EntityTypeManager->getStorage('node') (Line: 187)
Drupal\Core\Entity\EntityRepository->getCanonicalMultiple('node', Array, Array) (Line: 180)
Drupal\Core\Entity\EntityRepository->getCanonical('node', '1', Array) (Line: 149)
Drupal\Core\ParamConverter\EntityConverter->convert('1', Array, 'node', Array) (Line: 100)
Drupal\Core\ParamConverter\ParamConverterManager->convert(Array) (Line: 45)
Drupal\Core\Routing\Enhancer\ParamConversionEnhancer->enhance(Array, Object) (Line: 260)
Drupal\Core\Routing\Router->applyRouteEnhancers(Array, Object) (Line: 131)
Drupal\Core\Routing\Router->matchRequest(Object) (Line: 92)
Drupal\Core\Routing\AccessAwareRouter->matchRequest(Object) (Line: 113)
Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest(Object, 'kernel.request', Object)
call_user_func(Array, Object, 'kernel.request', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request', Object) (Line: 127)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 708)
Drupal\Core\DrupalKernel->handle(Object) (Line: 20)
Comment: Welcome to Drupal Answers!  Please always add the steps to reproduce an issue. Like: how did you setup the site exactly? What OS? How do you access the site? What URL? What version of PHP/Composer and so on. Many thanks
Answer: If the "node" entity type does not exist, you have a fundamentally broken installation, but it's not possible to say exactly how it's broken based on the information given.
There are a couple things I would inspect at this point:

Is your local database complete? Did the import perhaps fail?
Is the cache out-of-date? Try truncating every database table with a name that starts with cache_, or if you have Drush, running drush cr


switching display suite view modes based on context or user location, show/hide fields based on user location

Question: The Drupal 7 site i'm working with needs to have a services directory, each service needs to have a general description and a description for health professionals.
So I've created a new content type and called it service, and create 2 custom fields one for general description and one for the health description.
Now the the general services will create their own menu items (this part is fine), the healthcare ones will need to be available in a sortable list as pictured below
https://i.stack.imgur.com/fpVCF.png
Now here's the tricky part.
(I know I could just create 2 content types, one of general and one for healthcare but i'd like to reduce the double handling and maintenance as much as possible - so if there is
a way to have all the data entered in one content type that would be ideal)
Using display suite I can hide one of the fields, and using views I can create the directory listings but the directory listings created by views all just link back to the node.
So far I haven't been able to figure out a way to manipulate which fields are displayed (or even switch between display suite views) based on where the user is in the site.
This could be context, a link, or block on a page, i'm open to anything at this point.
Hopefully this is starting to make sense:
Services Content Type (takes all the data, field 1& field 2)
Viewing Content through general services (/services/service-name/service-item)
Display field 1
Viewing Content through health care (/services/health-care-professionals/service-item)
Hide Field 1
Display Field 2
I was hoping you could give me some pointers, I've looked into using the context module, rules module, even had a thought about having 2 content types and using rules to copy the data from
Content Type 1 Field 2, to Content Type 2 Field 2 upon saving..
Comment: Maybe this? https://drupal.org/project/vcd
Answer: I was able to do this using Display Suite Extras, I found this tutorial very useful.
Display Suite Extras has a switch view mode by URL option, if you add ?v=view_name to the end of the url it will render that view. So I created the needed view types and used views to rewrite the URL of the titles to include the url parameter.
Answer: Better yet I was able to figure it out entirely using views.
First I created a page with a glossary type view, but most importantly some linked titles. I altered the link path, look under the Rewrite Results tab, and click  'output this field as a link'
Now you'll be able to set link paths, tokens are available for use as well BUT you have to add them as a field in views first (and they must be placed above the linked title field)
I ended up using this path: health-professionals/[field_servicetype]/[title]
You'll also want to check 'replace spaces with dashes' to make the url friendly.
(also on a side note if you are using url aliases you'll need to go to the configuration and remove the words from the strip filter (eg, for, a, and, the) - because views has no option to do this, and your url needs to match with the actual alias. So remove those, and delete all the aliases and regenerate)
So now we have the altered linked titles setup. Now create another page, but this time look under Format > Show: and select rendered entity.
Now here's the good part, in rendered entity settings you can select 'view mode' which for me was one of the previously created modes I'd setup in display suite earlier, but you'll still be able to select from 'Full Mode','Teaser', etc.
Page Settings > Path: Needs to be the url and token, so mine was /health-professionals/%
Pager settings : Needs to be set to 'display a specified number of items' and set the number to 1 - so in essence what we're creating is an alternate way of viewing the actual node content through views.
Now the hard part
Contextual filters > add one for Content:Title
When filter value is NOT in the url - whatever, I've just left it as 'page not found' but when testing it can be a bit annoying so display all results is fine too.
When filter value IS in the URL: Override title: %1 (or %2, %3, etc depending how many filters  you have an what they are)
Apply that, and now if you look down to the 'preview with contextual filters' form go ahead and input a node title, so if you have a node called 'services' you'd put services in. If it's setup right you should get the node content for that page and nothing else.
Better still you'll also have a way to link to it, and a linked index (previous page created)
this absolutely did my head in... but good result in the end :)