How to generate license key of widevine from azure

Question: I have searcherd on azure media-service, but don't get any option to generate license key for widevine. I have checked also docs, but I can't understand where to generate. I don't find the option "content protection" anywhere.
Answer: By using Azure Media Services (AMS) for streaming, you do not need to generate the license by yourself, you need to configure it and it will generate it for you.
In general you need to do the following:

Create a Content Key Policy, where you put the encryption key, audience and issuer, any other claims, license capability, ...
Create a streaming locator with proper Streaming Policy. If you wish to use Widevine, you can choose Predefined_MultiDrmCencStreaming which give you the ability to support Widevine and PlayReady.
When someone which to playback the video by using the streaming locator you generated in step #2, you need to generate a JWT token so AMS can verify him and deliver the license.

You can find more information in the official documentation here Dynamic Encryption, Content Key Policy, and Streaming Policies. From here you can find .Net examples .Net examples
I should mention here that AMS has 2 API versions v2 and v3, v2 deprecation has been announced to be 29 February 2024, so it's better to use the newer v3 version.
Comment: oww.. I will try and let you know. Thanks for your response...


How to show product of two nonmeasurable sets is nonmeasurable?

Question: How can I show that the cartesian product of a nonmeasurable set in $\mathbb R$ and a nonmeasurable set or a measurable set with nonzero measure in $\mathbb R$ is nonmeasurable? I have only learned some basic measure theory (i.e. the definitions and some very basic theorems like measure continuity). Can anyone give me a hint?
Comment: By "product" do you mean living in the product space, or do you mean you take the pointwise product of pairs of elements in the sets? (Assuming these sets are subsets of the real numbers)
Comment: well i'm talking about the cartesian product, so pairwise product i guess.
Comment: Ok. Sorry if I was unclear, by "pairwise product" I meant "multiplication". When I said "product space", I meant "cartesian product".
Comment: ahh ok ok. sorry i misundertood. well perhaps i should edit my question because i'm talking about the cartesian product.
Answer: To get the measurable subsets of $\mathbb{R} \times \mathbb{R}$, you do the following steps:

Take all cartesian products $A \times B$, where $A$ and $B$ are measurable subsets of $\mathbb{R}$.
Take countable unions of sets of the type listed in $1$. Now you have a $\sigma-$algebra, call it $\mathcal{F}$. You should verify that, if $E$ is in $\mathcal{F}$, then the projections $\pi_1$ and $\pi_2$ of $E$ onto the coordinates should be measurable subsets of $\mathbb{R}$.
Now, you "complete" $\mathcal{F}$. ie, you consider all sets $S$ such that: For all $\varepsilon > 0$ there exists $E_1 \subset S \subset E_2$, with $E_1,E_2 \in \mathcal{F}$, such that $\mu(E_1) - \mu(E_2) < \varepsilon$ ($\mu$ is our measure).

Now you should have shown that, for instance, a product of two non-measurable sets $A \times B$ cannot be in $\mathcal{F}$. So you just have to show that it cannot be "boxed between" two sets in $\mathcal{F}$. To do this, notice that the property described in $3$ holds for non-measurable sets in $\mathbb{R}$. In other words, since $A$ is nonmeasurable we cannot find measurable sets $E_1 \subset A \subset E_2$ with $\mu(E_2) - \mu(E_1)$ arbitrarily small. This fact should help you prove that you cannot "box" $A \times B$ in between two sets in $\mathcal{F}$.
Comment: Taking countable unions of rectangles of measurable sets doesn't give you a $\sigma$-algebra.
Comment: Hm, yeah I think you're right. Dang.
Answer: Assuming you mean Cartesian product and that $(X_i, \mathcal{M}_i)$ are measurable spaces for $i=1, 2$.
Suppose that $A_1\notin \mathcal{M}_1$ and $A_{2}\notin \mathcal{M}_2$ but their product $A_1\times A_{2}\in\mathcal{M}_1\bigotimes\mathcal{M}_2$ where $\mathcal{M}_1\bigotimes\mathcal{M}_2$ is the collection generated by subsets $S_1\times S_2$ where $S_i\in\mathcal{M}_i$ for $i=1, 2.$
Then the product measure would be:
\begin{equation}
(\mu_1\times\mu_2)(A_{1}\times A_2)=\mu_1(A_1)\mu_2(A_2).
\end{equation}
But for the RHS to make sense that is, the measures are well defined, then it means that $A_1$ and $A_2$ must have been measurable. This is a contradiction.
Comment: Note also even if just $A_1$ or just $A_2$ was measurable the above argument would lead to a contradiction.
Comment: hmm isn't the product measure only defined on the the cartesian product of $M_1$ and $M_2$? so it wouldn't make sense in the first place to say $(\mu_1 \times \mu_2)(A_1 \times A_2)$?
Comment: ...wherein lies the contradiction. If $A_1\times A_2\in \mathcal{M}_1\bigotimes\mathcal{M}_2$ that is it is measurable then it must be because it's a union or intersection or complement of sets in $\{S\times T\ \vert\ S\in\mathcal{M}_1, T\in\mathcal{M}_2\}$ but because the $A_i$'s are not measurable then  this is not possible so the product measure is not defined on them. Also note that $\mathcal{M}_1\bigotimes\mathcal{M}_2$ is not really a Cartesian product of two sets. It is a collection sets whose members are cartesian products of sets from $\mathcal{M}_1$ and $\mathcal{M}_2$


A variation in the construction of the tensor product of modules

Question: Let $A$ be a ring, $E$ a right $A$-module and $F$ a left $A$-module. Consider the free $\mathbf{Z}$-module $\mathbf{Z}^{(E\times F)}$ which comes with the injective canonical mapping $\phi:E\times F\rightarrow\mathbf{Z}^{(E\times F)},\,(x,y)\mapsto e_{x,y}$, where $e_{x,y}:=(\delta_{(x,y),z})_{z\in E\times F}$ for $(x,y)\in E\times F$.
Bourbaki defines the tensor product of $E$ and $F$ as the quotient $\mathbf{Z}$-module $(\mathbf{Z}^{(E\times F)})/C$, where $C$ is the submodule of $\mathbf{Z}^{(E\times F)}$ generated by the elements of the form $(e_{x_1+x_2,y}-e_{x_1,y}-e_{x_2,y})$, $(e_{x,y_1+y_2}-e_{x,y_1}-e_{x,y_2})$ and $e_{x\lambda,y}-e_{x,\lambda y}$ for $x,x_1,x_2\in E$ and $y,y_1,y_2\in F$ and $\lambda\in L$.
Elsewhere, I have seen the element of the form $ne_{x,y}-e_{xn,y}$, with $x\in E$, $y\in F$ and $n\in\mathbf{Z}$, added to the list above. Is this necessary? Why does Bourbaki leave it out?
Comment: I suppose I would have to show that $ne_{x,y}-e_{xn,y}$ is a linear combination of the family of elements $(e_{x_1+x_2,y}-e_{x_1,y}-e_{x_2,y})$, correct?
Comment: It's a consequence that these will be also in $C$.
Comment: Yes, see my answer.
Answer: It's indeed not necessary, as these elements will already be in $C$ even for Bourbaki's definition.
Specifically, for $n\ge 1$, use induction to see it (let $x_1=nx$ and $x_2=x$ in the induction step).
For $n\le 0$, use the rule $e_{x\lambda, \, y} -  e_{x,\, \lambda y} \in C$ with $\lambda=0$ and $\lambda=-1$.
Comment: For $n>0$ use again the condition for addition: we have $e_{nx, y} - ne_{x,y}\in C$, and $e_{0, y}—e_{nx,y}-e_{-nx, y} \in C$, and also $e_{0,y}\in C$, hence also $e_{-nx,y}+ne_{x,y} \in C$
Comment: Can you please clarify the induction step for me? I have $e_{x(n+1),y}-(n+1)e_{x,y}=e_{xn+x,y}-ne_{x,y}-e_{x,y}$. By induction hypothesis, $e_{xn,y}-ne_{x,y}\in C$. If I take $x_1=xn$ and $x_2=x$, then $e_{xn+x,y}-e_{xn,y}-e_{x,y}\in C$ by definition. But here I have $e_{xn,y}$ instead of $ne_{x,y}$. I am not sure how to utilize the induction hypothesis.
Comment: You're just there: $(e_{xn+x,\,y}-e_{xn, y} - e_{x,y})\, +\, (e_{xn, y} - ne_{x,y})\ \in C$.
Comment: Sorry to bother you again–I am not clear about where you got the rule "$e_{x\lambda,y}-\lambda e_{x,y}\in C$" from. I have $e_{x\lambda,y}-e_{x,\lambda y}\in C$ instead. Is that a typo?
Comment: Hmm.. You're right, it's my mistake. In this form they are present in the commutative setting only..
Comment: Last query (I promise): If $n<0$, then $0<-n$ and we have $e_{x(-n),y}-(-n)e_{x,y}=e_{(-x)n, y}+ne_{x,y}\in C$. How do you exactly propose to combine this with $e_{x\lambda,y}-e_{x,\lambda y}\in C$ (with $\lambda\in A$) to show that $e_{xn,y}-ne_{x,y}\in C$? Thank you for your help.


How to set default group permission in Ubuntu for www-data (apache's user)?

Question: I have not been able to set a umask for www-data (apache's user).
I tried to put umask 002, like in many other examples I found, in /etc/init.d/apache2 script, or in /etc/apache2/envvars....  Then I restart my apache server.
As an example, after restarting, if I do:
sudo su - www-data
touch file

The file gets always the default rw-r--r-- permissions (umask 022), while I want rw-rw-r-- (umask 002).
Changing this has been up to now an impossible task in Ubuntu Hardy (8.04).
Can anybody help me please ?
Thanks
Comment: Please review your old questions with answers, accept any valid answers.  If there are no valid answers, then add comments or update your questions so that someone can provide valid answers.
Answer: The umask is specific to a process, not to a user.  For example, setting the umask in /etc/init.d/apache will likely make files created by apache umask 002 (assuming the process doesn't enforce specific permissions, or change the umask after you configure it in the init.d script).
However, when you sudo su - www-data, you're not setting a umask in any of the files you've sourced into your shell.  You're getting the default umask at this point.
Comment: "The umask is specific to a process, not to a user" : so why then is it possible to adapt the umask to a specific user in /etc/.profile ?
Comment: Sure, you can adjust the configuration of /etc/profile to set the umask for a particular user, but it only takes place for the processes created after that change is made.  Other processes that are already running have their own umask - regardless of the changes you make elsewhere or running the 'umask' command after starting a shell, etc.
Comment: indeed, I did a little php program to write a new file and it set correctly the group permissions...


Assumptions of additive model

Question: An additive model takes the form:
$y=\alpha+f_1(x_1)+f_2(x_2)+...+f_p(x_p)+\epsilon$
If I've understood correctly, there are only two assumption on the errors:
- errors have mean zero
- errors are homoschedastic
Since an additive model is a generalization of the linear model, are $Y|X$ supposed to be normal too? Are errors supposed to be uncorrelated as in the linear model?
Thank you.
Comment: this depends on the context. additive noise can be anything...
Answer: There's only a requirement of normality if, say
(a) you want least squares to be optimal (in the sense of say achieving a Cramer-Rao lower bound); or
(b) you want to apply a test or construct an interval that assumes it. (For example, if you want to get a prediction interval, you might try to assume it then.)
Conversely, if your data are highly non-normal, your estimates will be inefficient (as would any linear estimator), and in that case you generally wouldn't want to try to base tests or intervals off a normality assumption.
Answer: @Glen_b's answer is good to review to correct the premise of your question.
Specifically concerning $Y|X$, by which I presume you mean the conditional mean: no there are no requirements about the "distribution" of the $\hat{Y}$ or consequently the $X$. These are considered fixed in OLS, hence do not follow a distribution. It is no different for AMs.
The errors should be uncorrelated, also similar.

Assumptions of additive model


Converting Laravel's AES 256 Encryptor to C#

Question: I need to create the same results when using Crypt::Encrypt('secret') from Laravel, in C#.
I found this thread Rijndael 256 Encrypt/decrypt between c# and php?
and it seemed to be what I need, but I'm having some trouble with the third argument the, initialization vector :(.
Laravel using Rijndael AES to encrypt the data. All the user has to input is a secret key, in the config folder, that is totally random and 32 characters long.
The encyrption method looks like this:
public function encrypt($value)
    {
        $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer());

        $value = base64_encode($this->padAndMcrypt($value, $iv));

        // Once we have the encrypted value we will go ahead base64_encode the input
        // vector and create the MAC for the encrypted value so we can verify its
        // authenticity. Then, we'll JSON encode the data in a "payload" array.
        $mac = $this->hash($iv = base64_encode($iv), $value);

        return base64_encode(json_encode(compact('iv', 'value', 'mac')));
    }

The full Encryptor.php can be found here: http://pastebin.com/yfWLPxGn
Any idea as to what I would have to input to get the same results? :)
Answer: Initialization vector is an input that is typically random. So, algorithm always creates a different value using the same input, key and the different IV. If you'd like to generate same result using both PHP and C# code, you need to use the same IV value.
Laravel's encrypt() does not return the encrypted value only. The value encrypt() generates a base64 encoded string which has json encoded values of iv, mac and encrypted value.
So the steps you need to apply in your C# encode() method:

Encode the string using the code in the link you gave.
base64_encode() the encrypted value. We will use this value in the further steps.
Create MAC (Message Authentication Code) using base64_encoded IV as the value, encrypted value as the key and sha256 as the algorithm. Take a look at this one
Now we have encrypted value, mac and iv.
Create a json string like this:
{
    iv: iv value (base64 encoded),
    value: encrypted value (base64 encoded),
    mac: mac value created in 3rd step
}

base64 encode your this json string.
You're all set.
Answer: You would want to not apply padding and not apply any specific mode of operation. There is a pseudo-mode called ECB which basically applies the bare cipher over many blocks and applies no padding. It requires full blocks to be used.
If you don't have a full block to encrypt, you need to figure out what padding mode is used.
If that doesn't work, then you need to figure out what mode and what initialization vector is used. An initialization vector is usually prepended to a message as a unique value that varies per message, as a way to prevent some mathematical attacks on bare ciphers applied over many blocks.
Comment: the function "addPadding($padding)", should be the padding,right?
Comment: @Jazerix Looks like it.


Limits - Direct Substitution - with 1/3 power functions

Question:

First image is the question from my textbook in Latex form.
Second image shows the actual question from my book along with the solution.
What i am actually confused about is that how did they open the power 1/3 and got the following result on each step.
Is there anyone who can help me more to understand each step of this question? Or help me understand a new way to do this question? Or something like this.
Help will be highly appreciated.
Regards,
Ballu Miaa
Comment: http://en.wikipedia.org/wiki/Taylor_series
Comment: The poster below explained it in a better way. Still thanks to you.
Answer: They did the Taylor expansion of it:
$$(1+h)^{1/3}=1+\frac{1}{3}h+o(h^2)$$
$$(1-h)^{1/3}=1-\frac{1}{3}h+o(h^2)$$
Then, they use the fact that
$$\lim_{h\rightarrow0}\frac{o(h^2)}{h}=0$$
So they just keep the first power (the $1$s cancel)
Comment: Looks good. Actually solved my question. But Taylor expansion is used to do what actually? It is a way to expand an algebraic expression? Also there were no other ways to do this kind of question?

Thanks a lot man. Much Love. You're a saviour.
Comment: Also can you tell me how to use Latex in a post? The way you write the formula over here above you know.
Comment: @BalluMiaa, there are other ways to solve such problem, see http://math.stackexchange.com/questions/569230/cant-find-the-limit-of-the-following
Comment: Ohh thats a good way too. Thanks a lot Bhattacharjee. I will look at both of these methods for future references.
Comment: @BalluMiaa. Taylor expansion is a very good tool to approximate, even very accurately, very complex functions around a given point. Look at the Wiki page mentioned above.
Comment: @ClaudeLeibovici - Thanks a lot. Well i been away from Maths since some years and started it again to pass my uncleared exams. Therefore its hard for me grasp the language used in that wiki article. Well you helped me enough to understand it.
Comment: @BalluMiaa. Happy and glad of being able to help you. Cheers.


Java: Pegar nome e número de série de celular conectado ao computador

Question: Caros, em primeiro lugar: Essa não é uma questão envolvendo desenvolvimento Android.
Estou fazendo automação no java, e gostaria de saber se há alguma forma de guardar em strings o nome e o número de série do dispositivo ao conectá-lo via USB no computador. Atualmente faço isso manualmente entrando no "Meu computador > Selecionando o celular com botão direito > Propriedades" e então copiando essas informações.
Há alguma maneira de fazer isso via Java?
Desde já,
Obrigado!
Comment: Veja esta [resposta](http://stackoverflow.com/a/23469703/2556111)
Answer: Fala Luís,
O serial é simples, é só chamar o build, exemplo:
String deviceSerial;

try {
   deviceSerial = (String) Build.class.getField("SERIAL").get(null);
 } catch (IllegalAccessException e) {
      e.printStackTrace();
 } catch (NoSuchFieldException e) {
      e.printStackTrace();
 }

Log.d("serial", deviceSerial);

E pra pegar o nome, é um pouquinho mais complicado, exemplo:
public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return capitalize(model);
    }
    return capitalize(manufacturer) + " " + model;
}

private static String capitalize(String str) {
    if (TextUtils.isEmpty(str)) {
        return str;
    }
    char[] arr = str.toCharArray();
    boolean capitalizeNext = true;

    StringBuilder phrase = new StringBuilder();
    for (char c : arr) {
        if (capitalizeNext && Character.isLetter(c)) {
            phrase.append(Character.toUpperCase(c));
            capitalizeNext = false;
            continue;
        } else if (Character.isWhitespace(c)) {
            capitalizeNext = true;
        }
        phrase.append(c);
    }

    return phrase.toString();
}

Ai pra chamar o resultado, você faz:
String deviceName = getDeviceName();

Abraços.
Comment: primeiramente, muito obrigado pela ajuda..!

Tentei o primeiro, para pegar o serialNumber, porém está retornando null...Eu simplesmente abri uma classe no java, importei o android pelo maven, e inseri essa string num system.out pra ver o que dava.

Será que eu deveria ter feito algo antes?
Comment: Estranho estar vindo como nula, alterei a minha resposta com um novo código pra pegar o serial, da uma conferida.


Support Vectors Not Falling on Margin Lines for e1071 and kernlab packages in R?

Question: In a previous thread, Computing the Decision Boundary of a linear SVM model(Computing the decision boundary of a linear SVM model), the following R code was given as a way to compute the formula of the hyperplane and it's margins, given an input set of hyperparameters:
library(kernlab)
set.seed(101)
x <- rbind(matrix(rnorm(120),,2),matrix(rnorm(120,mean=3),,2))
y <- matrix(c(rep(1,60),rep(-1,60)))
svp <- ksvm(x,y,type="C-svc")
plot(svp,data=x)
alpha(svp)  # support vectors whose indices may be found with alphaindex(svp)
b(svp)      # (negative) intercept
plot(scale(x), col=y+2, pch=y+2, xlab="", ylab="")
w <- colSums(coef(svp)[[1]] * x[unlist(alphaindex(svp)),])
b <- b(svp)
abline(b/w[1],-w[2]/w[1])
abline((b+1)/w[1],-w[2]/w[1],lty=2)
abline((b-1)/w[1],-w[2]/w[1],lty=2)

However, in the resulting plot, none of the support vectors actually fall on either margin line.
If
abline(b/w[1],-w[2]/w[1]) #is supposed to be the maximum-marginal hyperplane and
abline((b+1)/w[1],-w[2]/w[1],lty=2) #is supposed to be the yi = +1 margin and
abline((b-1)/w[1],-w[2]/w[1],lty=2) #is supposed to be the yi = -1 margin

then why don't the support vectors, alpha(svp), fall on either the +1 or the -1 margin?
Now before you say it's because kernelf = "rbfkernel" by default and our hyperplane and margins have not been transformed according to the rbfkernel, I can explicitly call the linear kernel with kernelf = "vanilladot" (i.e svp <- ksvm(x,y,type="C-svc",kernelf="vanilladot")) and the hyperplane and margins are even farther from the support vectors defined by alpha(svp) then when kernelf="rbfkernel".
Note that I find similar results when I use the e1071 package (which is perhaps not surprising as they both based on the LIBSVM library).
If I am doing something wrong, or missing a crucial point (like perhaps ksvm() uses a soft margin by default and is hiding the slack variables from me), please let me know!
Here is my code for the linear kernel with the kernlab package:
library(kernlab)
set.seed(101)
x <- rbind(matrix(rnorm(120),,2),matrix(rnorm(120,mean=3),,2))
y <- matrix(c(rep(1,60),rep(-1,60)))
svp <- ksvm(x,y,type="C-svc",kernelf="vanilladot")
plot(svp,data=x)
plot(x, col=y+2, pch=y+2, xlab="", ylab="")
w <- colSums(coef(svp)[[1]] * x[unlist(alphaindex(svp)),])
b <- b(svp)
plot(svp,data=x)
abline(b/w[1],-w[2]/w[1])
abline((b+1)/w[1],-w[2]/w[1],lty=2)
abline((b-1)/w[1],-w[2]/w[1],lty=2)

Answer: I am not an R user, but I suspect it is because you are using the soft-margin support vector machine (which is what I presume "C-svc" means).  The support vectors will only lie exactly on the margins for the hard margin SVM (where C is infinite).  Essentially the C parameter penalises the degree to which the support vectors are allowed to violate the margin constraint, so if C is less than infinity, the support vectors are allowed to drift away from the margins in the interests of making the margin broader, which often leads to better generalisation.
Comment: Thanks Dikran Marsupial - your answer is completely correct.  When type is set to C-svc, a soft margin SVM is being implemented.  By definition, anytime you have a Cost (C) hyperparameter, the SVM is soft-margin.


Private NuGet package server hosted on AWS returns 403 Forbidden error for just one NuGet package

Question: Many years ago I set up a NuGet server on an AWS instance to host NuGet packages for my team's software projects. It has been working great, until today.
I had a project that belonged to a larger solution that was puyblishing a NuGet package to my server when its Jenkins job ran. I needed to move that project to its own Git repo with its own solution and its own build script with its own Jenkins job. Everything was fine. The new Jenkins job builds from the new repo and publishes the NuGet package to my server.
However, when I then tried to add that NuGet package to another project using Visual Studio 2019, I got a credential prompt for my NuGet server which never happens (the project already uses other NuGet packages from that server). At a loss, I tried entering the Windows administrator account password for the AWS server. The prompt went away and has not come back.
The Manage NuGet Packages in Visual Studio shows the package with the version from the latest build, but when I try to add that package to my project I get a 403 Forbidden error. This is the only NuGet package on that server that has this problem. All others work successfully.
I have checked folder permissions on the NuGet server website's \Packages folder as well as the specific folder for this NuGet package. Nothing seems out of place. I have removed and replaced the NuGet package's folder from the \Packages directory for the website. There is nothing in the web.config file for the server that I can see that would cause this. I don't know what else to check. Google searches for 403 Forbidden errors on NuGet servers have not revealed anything that seemed relevant. I am not using TFS. All other packages work correctly. Why does one package have this issue?
UPDATE: When I tried using command line to install this package, this is the output:
PM> install-Package MyPackage -Version 3.0.0-devbuild0229
Attempting to gather dependency information for package 'MyPackage.3.0.0-devbuild0229' with respect to project 'MyProject', targeting '.NETFramework,Version=v4.8'
Gathering dependency information took 320 ms
Attempting to resolve dependencies for package 'MyPackage.3.0.0-devbuild0229' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'MyPackage.3.0.0-devbuild0229'
Resolved actions to install package 'MyPackage.3.0.0-devbuild0229'
Retrieving package 'MyPackage 3.0.0-devbuild0229' from 'MySource'.
GET http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229
Forbidden http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229 1647ms
Error downloading 'MyPackage.3.0.0-devbuild0229' from 'http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229'.
Response status code does not indicate success: 403 (Forbidden).
GET http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229
Forbidden http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229 667ms
Error downloading 'MyPackage.3.0.0-devbuild0229' from 'http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229'.
Response status code does not indicate success: 403 (Forbidden).
GET http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229
Forbidden http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229 645ms
Install failed. Rolling back...
Package 'MyPackage.3.0.0-devbuild0229' does not exist in project 'MyProject'
Package 'MyPackage.3.0.0-devbuild0229' does not exist in folder 'C:\MyProject\packages'
Executing nuget actions took 3.78 sec
install-Package : Error downloading 'MyPackage.3.0.0-devbuild0229' from 'http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/mypackage/3.0.0-devbuild0229'.
Response status code does not indicate success: 403 (Forbidden).
At line:1 char:1

install-Package MyPackage -Version 3.0.0-devbuild0229

CategoryInfo          : NotSpecified: (:) [Install-Package], Exception

FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

Time Elapsed: 00:00:04.4888243
Comment: Hi friend, did you try to use command line to install that package?  Run `Install-Package xxx(package name) -Version xxx -ProjectName xxx` on the [package manager console](https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-powershell#opening-the-console-and-console-controls). Besides, you could add a `packageSourceCredentials` under global `nuget.config` file.Like [this format](https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#packagesourcecredentials).
Comment: Or you could check your nuget server and make sure that your account has the right to install this package. Please let us know if it helps or not.
Comment: Perry - I tried using Install-Package from the command line and received the same error: See my update above.
Comment: I think the issue is not related to VS. I think you should check whether the current windows administrator has the right to download the package.You should check on your `NuGet server` and make sure that your account has the permission. If it is a new version, you can just wait for a while. When a new version of the package is released, it is going to take some time because there's a delay. So you can try after a while.
Answer: As it turns out, our IT department recently put in place some additional restrictions on accessing AWS servers using an application called Zscalar. By clicking on the link in the Forbidden message in the Output window in VS my browser opens to a Zscalar web page that indicates:
You tried to visit: http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/api/v2/package/myPackage...
Proceeding to visit the site may violate your company policy. Press the "Continue" button to access the site anyway or press the "Back" button on your browser to go back
Clicking the Continue button on this page allows Visual Studio to successfully download the NuGet package, but only temporarily, so this process has to be repeated regularly.
I am working with our IT department to resolve the issue.


How to compute the composition of a function and a piece-wise function?

Question: I understand function composition with normal functions. I don't really get it when one of those functions is piecewise.
When do I need to change the condition of the piecewise bit, or do I even do that at all?
Here are the two functions that I want to find the composition of.

Let $f$ and $g$ be ${\bf N}\to {\bf N}$ functions defined by
  $$
f(n) = 2^n, ~~~~\mbox{and}~~~~ g(n) = \begin{cases}
5n & \mbox{if}~~n > 10,\\
6n & \mbox{if}~~0\leq n \leq 10
\end{cases}
$$

Specifically $f(g(x))$ and $g(f(x))$ are challenging.
Thank you.
Comment: mybew you should try some values of n, e.g(f(n) for n=1,2,3,4,5 and f(g(n)) for n=1,3,5,7,9,11,13
Answer: In this case the composition $f(g(n))$ is easier since the piecewise function is $g$, and you only have to split between the cases $n\leq 10$ and $n>10$. More generally, if you have
$$
g(n)=\begin{cases}
g_1(n), &\text{if }n\leq 10,\\
g_2(n), &\text{otherwise},\end{cases}
$$
then you can deduce
$$
f(g(n))=\begin{cases}
f(g_1(n)), &\text{if }n\leq 10,\\
f(g_2(n)),&\text{otherwise}.\end{cases}
$$
The case $g(f(n))$ is more involved, since you first have to find the values of $n$ for which $f(n)\leq 10$ and $f(n)>10$, and then compose the functions. I hope you can carry on from here, and if you have any further doubt just ask.


How to target elements set from innerHTML or .html() using jquery

Question: I have a div whose content gets dynamically generated from innerHTML and I cant seem to target those elements using jQuery for validation, Eg This is the page:

Alert1
<input type="button" value="Click Me" id="button1" />

and this is the js code:

The alert for the span with id alert1 works but for id alert which is set using innerHTML or .html() does not work so how to fix this?
Thank you in advance

Answer: The problem here is that when you write like this..
    $("#element").click(function() {
        alert("Alert!");
    });

.. it will only create events handlers for elements that exist when you execute the code. It won't create event handlers for future elements even if they have the same jQuery selector ("#element" in this case).
What you need to do is bind with .on(event, selector, function) on a parent element, as the events "bubble up" the hierarchy. That way you can handle future events from the specified selector. Personally I would do it like this:
$(document).ready(function() {
     $('#button1').click(function() {
         var html = "<insert lots of html stuff here>";
         $('#empty').html(html);
    });

    $(document).on("click", "#alert", function() {
        alert("Alert!");
    });

    $(document).on("click", "#alert1", function() {
        alert("Alert1!");
    });
});

Answer: you should use delegate
$(elements).delegate(selector, events, data, handler);

as per your code
$(document).ready(function() {
  $("yourdiv").delegate("#alert, #button, #Alert1", "click", function() {
    alert('Alert');
  });
});

Answer: Use .on() instead of .click() to bind events at run-time. You may try .live() but it is deprecated.
Here's the fiddle : http://jsfiddle.net/Akyrk/
Answer: you have to attach the listeners AFTHER you added the objects to the dom!
so afther .html(...)


Apple Pay Payment Token Decryption in Java


Show $(N, ≤)$ is a partial order with least upper bounds (lubs) and greatest lower bounds (glbs) of all pairs.

Question: does anyone have any solution or a good hint?
Let $(\mathbb{N}, ≤)$ be the set of natural numbers with the relation $m ≤ n$, meaning $m$ divides $n$. Show $(\mathbb{N}, ≤)$ is a partial order with least upper bounds (lubs) and greatest lower bounds (glbs) of all pairs. What are these lubs and glbs in
more traditional terms? If $\mathbb{N}$ is replaced by $\mathbb{Z}$, does the divides
relation still yield a partial order?
Ok, this is what I got:
I have the set of all divisors for n,  $(N,≤)=(m_1,…,m_k│m_i  divides n)$,where $i=1,2,…,k$. In order for $(N,≤)$ to be of partial order it need to be: reflexive (each element is comparable to itself), antisymmetric (no two different elements precede each other and transitive (the start of a chain of precedence relations must precede the end of the chain).
Reflexive: $m_i$  divides $m_i$
Antisymmetric:if $m_i |m_j$,where $i≠j$,then $m_j∤m_i$ since $m_j$ must be greater than $m_i$.
Transitive:if $m_i|m_j$ and $m_j|m_k$, then $m_i|m_j*q=m_k$ for some $q∈N$.
Here is where it gets tricky. I'm reasoning like this:
Take any pair say m_i and m_j, then I have the union of the set of all divisors for m_i and the set of all divisors for m_j. The union is not empty, because it contains 1, and every non-empty subset of the natural number has a least member. Also, any common divisor c satisfies c≤m_i and c≤m_j, so the set has a greatest member. The greatest member has to be the least upper bound since the union of divisors is finite. 1 must always be a lower bound of the union since 1 is less than or equal to all elements in the union. It must also be the greatest lower bound since 1 is the greatest lower bound for the natural numbers (and the union is a subset, containing 1, of the natural numbers).
I'm sure this is wrong, help please.
Comment: Why don't you start by thinking about some concrete case, say $m_1-6$ and $m_2=10$? What are the lower bounds and the upper bounds for the set $\{m_1,m_2\}$?
Comment: What about greatest common divisor and least common multiple?
Comment: Ok, I'm doing something wrong. I can prove that it is of partial order. But then I think I'm out of my league.

Take any pair say m_i and m_j, then I have the union of the set of all divisors for m_i and m_j. The union is not empty, because it contains 1. Also, any common divisor c satisfies c≤m_i and c≤m_j, so the set has a greatest member. The greatest member has to be the least upper bound since the union of divisors is finite. 1 must always be a lower bound of the union since 1 is less than or equal to all elements in the union.
Comment: Do you mean $m_1 = 6$?

I'm so lost, lol.
Comment: Picking on bof's comment, what are the divisors of 6? and what are the divisors of 10? Is there one which is larger than the others (in the sense that it is multiple of the others)? If so, it is the greatest lower bound (hint: it is also the greatest common divisor; see my comment above). Do the same for multiples. Is there a smaller one (perhaps the least common multiple)? If so, it is the least upper bound. Generalize for other pairs.
Comment: Also please read about lattices - `https://en.wikipedia.org/wiki/Lattice_(order)`
Answer: I'll continue the good example, given by @bof. Let's consider the pair $\{6, 10\}$.

GLB. All the divisors of $6$ are $\{1,2,3,6\}$. All the divisors of $10$ are $\{1,2,5,10\}$. Intersection (by the way, you wrote union in your question) of these two sets will give you a set $\{1,2\}$ of all the lower bounds. Then you can choose $2$ as the greatest lower bound, because $1\le2$ (but not because $1$ is less than $2$ in arithmetical sense). Note now that $GCD(6,10)=2$.
LUB. Number of all the upper bounds for the pair $\{6,10\}$ is infinite, but you can choose a most evident one - $60$, because it's a product of $6$ and $10$. However it won't be the least one. You need to represent both $6$ and $10$ as products of prime factors. So, $6=2\cdot3$ and $10=2\cdot5$. The least upper bound, represented as product of prime factors, must contain all the prime factors of $6$ and $10$ - so we get $30=2\cdot3\cdot5$. Note now that $LCM(6,10)=30$.

The picture below shows a piece of the lattice $(N,\le)$, where partial order is induced by divisibility:

And now you need to generalize all this for any pair of natural numbers - good luck!
As for your second question about the $\mathbb{Z}$ - please think about antisymmetry axiom. If $(-n)$ divides $n$ and $n$ divides $(-n)$, then what?


Cisco VPN Concepts - Connection Profiles and Group Policy

Question: I was wondering could someone please explain the main concepts of how Cisco ASA Firewalls implement VPNs please? Specifically what are Connection Profiles and Group Policies used for? i.e. What they do, how they work.
I've a strong theoretical understanding of VPNs but no pratical experience. At present I'm just learning the basics using a Cisco ASA Simulator.
Thanks for any help.
Answer: Connection Profiles are used to assign DHCP servers, Global Addresse Pools, AAA and generic VPN settings. (How to connect to the VPN)
It will also be "linked" to a Group Policiy"
The Group Policy will specify network ACL, DNS and Routing (Split Tunneling) once the VPN connection is established. (What are you privileges once you are connected)
Therefore, you can have multiple ways to connect to your VPN endpoint but still have the same policies attributed to the different VPN clients.


Is a v-VI♭ progression in a minor key still a deceptive cadence?

Question: I was just listening to a rock song that is in a minor key, and the phrase ends with a v moving to a VI♭ chord.
Since the dominant chord is taken from the natural minor and doesn't contain the leading tone, is this still a deceptive cadence?
My theory textbook says that a deceptive cadence needs a chord with the leading tone followed by any chord but the tonic. It also says a chord without the leading tone followed by any chord but the tonic is a half cadence. Because the roots follow that of a deceptive cadence, does it make more sense to analyze it as that rather than a half cadence?

From 28-32 seconds. Song is in A minor, chord progression is Am-G-Em-F.
Comment: For context: what are the actual chords (or link to song)?
Comment: https://www.youtube.com/watch?v=iqyBq4vnuvc
Answer: Since in rock, you can put together any 4 diatonic triads (the diminished triad usually excluded), loop them, and call it a chord progression, I'm hesitant to use functional labels here. To call the cadence "deceptive" is to imply that the alternative progression Am-G-Em-Am was expected, or at least would work. What do you think? The classical trick of first writing a deceptive and then resolving to the corresponding authentic cadence: it is quite foreign to this style, which instead chooses a chord progression and sticks to it.
That said, there are popular songs that use deceptive cadences where the dominant chord lacks a leading tone, see e.g. In Every Age (youtu.be/nR3I-McnF5c), 0:15: VII-VI is deceptive, VII-i is authentic.


If $G = GL(2,3)$, $G/Z(G) \cong S_4$

Question: Let $G = GL(2,3)$, the group of all invertible $2 \times 2$ matrices over the field of $3$ elements. Show that $G/Z(G) \cong S_4$.
I know that $G/Z(G)\cong Inn(G)$, where $Inn(G)$ is the inner automorphism group of $G$. But it's difficult for me to construct an isomorphism from $Inn(G)$ to $S_4$ -- how to enumerate the inner automorphisms of the matrix group, for example, is a tough idea for me to see.
I'd rather construct a surjective homomorphism $\phi: G \longrightarrow S_4$ such that $ker(\phi) = Z(G)$, so that the result follows from the First Isomorphism Theorem. But I'm not sure how such a map can be constructed. I do know that, for the desired result to hold, $Z(G)$ has order $2$ -- so I think that $ker(\phi)$ should only contain two matrices, the identity matrix along with one other matrix in $G$ (which, I believe, would have to be the identity matrix multiplied by $2$).
How can I construct the above homomorphism ?
Thanks!
Answer: Group $\mathrm{GL}_2(\mathbb{F}_3)$ acts on one-dimensional subspaces of space $\mathbb{F}_3^2$. There are precisely four one-dimensional subspaces of $\mathbb{F}_3^2$. This gives a homomorphism $\phi:\mathrm{GL}_2(\mathbb{F}_3) \rightarrow S_4$. You can verify that $\phi$ is surjective and $\mathrm{ker}(\phi) = Z\left(\mathrm{GL}_2(\mathbb{F}_3)\right)$.
Comment: Thank you. Very clever. (=

If $G = GL(2,3)$, $G/Z(G) \cong S_4$


How do you deduce the possible algebraic structures of a group from its order?

Question: For a finite group G with order 99, G contains the subgroups of order 1, 3 and 11 since they divide 99 and there exist a sylow p subgroup of order 9. Apart from this, what is the relation of order to direct products and isomorphism?
    I dont know if I framed my question well but any help will be appreciated.
Comment: It in fact has a normal subgroup of order 11 and a normal subgroup of order 9 (Sylow subgroups). Since both these subgroups have trivial intersection, are  abelian and  the group is their direct product it follows the group itself is abelian. In this case it is pretty simple.
Answer: Let $G$ be a group of order $99$. From the Sylow theorems it follows that there is only one $3$-Sylow subgroup and only one $11$-Sylow subgroup. Let's say $P$ is a $3$-Sylow subgroup, $Q$ is an $11$-Sylow subgroup. Hence both $P$ and $Q$ are normal in $G$. More than that, $P\cap Q=\{e\}$ and since $|PQ|=\frac{|P||Q|}{|P\cap Q|}=\frac{9\times 11}{1}=99=|G|$ we conclude that $G=PQ$. So we have all the conditions of a direct product, so $G\cong P\times Q$.
Now, the only group of order $11$ up to isomorphism is $\mathbb{Z_{11}}$, and the only groups of order $9$ are $\mathbb{Z_9}$ and $\mathbb{Z_3}\times\mathbb{Z_3}$.Hence we get that $G\cong \mathbb{Z_9}\times\mathbb{Z_{11}}$ or $G=\mathbb{Z_3}\times\mathbb{Z_3}\times\mathbb{Z_{11}}$, so we actually found all groups of order $99$ up to isomorphism. Of course that can't be easily done for any order, but for order $99$ it is possible as you can see.


Inequality : $ \sqrt{\frac{a}{b+1}} + \sqrt{\frac{b}{c+1}} +\sqrt{\frac{c}{a+1}} \le \frac{3}{2} $

Question: $a+b+c =1$ ,  $a, b, c>0 $
Prove
$$ \sqrt{\frac{a}{b+1}} + \sqrt{\frac{b}{c+1}} + \sqrt{\frac{c}{a+1}} \le  \frac{3}{2}$$
When I meet the inequality with square root symbols, I don't have any idea. It's my tragedy. I know the triangular inequality : $$\cos A + \cos B + \cos C  \le \frac{3}{2}  $$
But I failed to find a link between the two inequalities. I want some another hints. Thank you.
Comment: The inequality toolbox consists of quite a lot of methods. But the first few to know would be "Sum of Squares", "AM-GM(-HM)" and "Cauchy-Schwarz". Do learn them and try to apply them here. (In my opinion, not objective fact)
Comment: Thanks your words..I think that there are too many inequalities in the world.
Answer: In eliminating square roots, a well chosen CS is your friend, (and for higher roots, often Holder).  Note by Cauchy-Schwarz inequality,
$$\sum_{cyc} (a+1) \cdot\sum_{cyc} \frac{a}{(a+1)(b+1)}\geqslant \left(\sqrt{\frac{a}{b+1}}+\sqrt{\frac{b}{c+1}}+\sqrt{\frac{c}{a+1}} \right)^2$$
Hence it is enough to show that
$$\sum_{cyc} \frac{a}{(a+1)(b+1)} \leqslant \frac9{16}$$
$$\iff 16\sum_{cyc} a(c+1) \leqslant 9\prod_{cyc} (a+1)$$
$$\iff 9abc+2 \geqslant 7(ab+bc+ca)$$
In symmetric form this is:
$$2(a+b+c)^3 + 9abc \geqslant 7(a+b+c)(ab+bc+ca)$$
$$\iff 2(a^3+b^3+c^3) \geqslant \sum_{cyc} ab(a+b)$$
which is true by Muirhead's theorem.
Comment: Very nice and smart answer.. thank you.
Comment: That's a very overpowered theorem at the end. (lol) Nice usage of CS there.
Comment: @the4seasons Thanks. Instead of Muirhead, AM-GM suffices too, one just has to add several of $\frac23a^3+\frac13b^3\ge a^2b$.


gym package not identifying ten-armed-bandits-v0 env

Question: Environment:

Python: 3.9
OS: Windows 10

When I try to create the ten armed bandits environment using the following code the error is thrown not sure of the reason.
import gym
import gym_armed_bandits

env = gym.make('ten-armed-bandits-v0')

The error:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:158, in EnvRegistry.spec(self, path)
    157 try:
--> 158     return self.env_specs[id]
    159 except KeyError:
    160     # Parse the env name and check to see if it matches the non-version
    161     # part of a valid env (could also check the exact number here)

KeyError: 'ten-armed-bandits-v0'

During handling of the above exception, another exception occurred:

UnregisteredEnv                           Traceback (most recent call last)
Input In [6], in <module>
----> 1 env = gym.make('ten-armed-bandits-v0')

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:235, in make(id, **kwargs)
    234 def make(id, **kwargs):
--> 235     return registry.make(id, **kwargs)

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:128, in EnvRegistry.make(self, path, **kwargs)
    126 else:
    127     logger.info("Making new env: %s", path)
--> 128 spec = self.spec(path)
    129 env = spec.make(**kwargs)
    130 return env

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:203, in EnvRegistry.spec(self, path)
    197     raise error.UnregisteredEnv(
    198         "Toytext environment {} has been moved out of Gym. Install it via `pip install gym-legacy-toytext` and add `import gym_toytext` before using it.".format(
    199             id
    200         )
    201     )
    202 else:
--> 203     raise error.UnregisteredEnv("No registered env with id: {}".format(id))

UnregisteredEnv: No registered env with id: ten-armed-bandits-v0

When I check the environments available, I am able to see it there.
from gym import envs
print(envs.registry.all())

dict_values([EnvSpec(CartPole-v0), EnvSpec(CartPole-v1), EnvSpec(MountainCar-v0), EnvSpec(MountainCarContinuous-v0), EnvSpec(Pendulum-v1), EnvSpec(Acrobot-v1), EnvSpec(LunarLander-v2), EnvSpec(LunarLanderContinuous-v2), EnvSpec(BipedalWalker-v3), EnvSpec(BipedalWalkerHardcore-v3), EnvSpec(CarRacing-v0), EnvSpec(Blackjack-v1), EnvSpec(FrozenLake-v1), EnvSpec(FrozenLake8x8-v1), EnvSpec(CliffWalking-v0), EnvSpec(Taxi-v3), EnvSpec(Reacher-v2), EnvSpec(Pusher-v2), EnvSpec(Thrower-v2), EnvSpec(Striker-v2), EnvSpec(InvertedPendulum-v2), EnvSpec(InvertedDoublePendulum-v2), EnvSpec(HalfCheetah-v2), EnvSpec(HalfCheetah-v3), EnvSpec(Hopper-v2), EnvSpec(Hopper-v3), EnvSpec(Swimmer-v2), EnvSpec(Swimmer-v3), EnvSpec(Walker2d-v2), EnvSpec(Walker2d-v3), EnvSpec(Ant-v2), EnvSpec(Ant-v3), EnvSpec(Humanoid-v2), EnvSpec(Humanoid-v3), EnvSpec(HumanoidStandup-v2), EnvSpec(FetchSlide-v1), EnvSpec(FetchPickAndPlace-v1), EnvSpec(FetchReach-v1), EnvSpec(FetchPush-v1), EnvSpec(HandReach-v0), EnvSpec(HandManipulateBlockRotateZ-v0), EnvSpec(HandManipulateBlockRotateZTouchSensors-v0), EnvSpec(HandManipulateBlockRotateZTouchSensors-v1), EnvSpec(HandManipulateBlockRotateParallel-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensors-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensors-v1), EnvSpec(HandManipulateBlockRotateXYZ-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensors-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensors-v1), EnvSpec(HandManipulateBlockFull-v0), EnvSpec(HandManipulateBlock-v0), EnvSpec(HandManipulateBlockTouchSensors-v0), EnvSpec(HandManipulateBlockTouchSensors-v1), EnvSpec(HandManipulateEggRotate-v0), EnvSpec(HandManipulateEggRotateTouchSensors-v0), EnvSpec(HandManipulateEggRotateTouchSensors-v1), EnvSpec(HandManipulateEggFull-v0), EnvSpec(HandManipulateEgg-v0), EnvSpec(HandManipulateEggTouchSensors-v0), EnvSpec(HandManipulateEggTouchSensors-v1), EnvSpec(HandManipulatePenRotate-v0), EnvSpec(HandManipulatePenRotateTouchSensors-v0), EnvSpec(HandManipulatePenRotateTouchSensors-v1), EnvSpec(HandManipulatePenFull-v0), EnvSpec(HandManipulatePen-v0), EnvSpec(HandManipulatePenTouchSensors-v0), EnvSpec(HandManipulatePenTouchSensors-v1), EnvSpec(FetchSlideDense-v1), EnvSpec(FetchPickAndPlaceDense-v1), EnvSpec(FetchReachDense-v1), EnvSpec(FetchPushDense-v1), EnvSpec(HandReachDense-v0), EnvSpec(HandManipulateBlockRotateZDense-v0), EnvSpec(HandManipulateBlockRotateZTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateZTouchSensorsDense-v1), EnvSpec(HandManipulateBlockRotateParallelDense-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensorsDense-v1), EnvSpec(HandManipulateBlockRotateXYZDense-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensorsDense-v1), EnvSpec(HandManipulateBlockFullDense-v0), EnvSpec(HandManipulateBlockDense-v0), EnvSpec(HandManipulateBlockTouchSensorsDense-v0), EnvSpec(HandManipulateBlockTouchSensorsDense-v1), EnvSpec(HandManipulateEggRotateDense-v0), EnvSpec(HandManipulateEggRotateTouchSensorsDense-v0), EnvSpec(HandManipulateEggRotateTouchSensorsDense-v1), EnvSpec(HandManipulateEggFullDense-v0), EnvSpec(HandManipulateEggDense-v0), EnvSpec(HandManipulateEggTouchSensorsDense-v0), EnvSpec(HandManipulateEggTouchSensorsDense-v1), EnvSpec(HandManipulatePenRotateDense-v0), EnvSpec(HandManipulatePenRotateTouchSensorsDense-v0), EnvSpec(HandManipulatePenRotateTouchSensorsDense-v1), EnvSpec(HandManipulatePenFullDense-v0), EnvSpec(HandManipulatePenDense-v0), EnvSpec(HandManipulatePenTouchSensorsDense-v0), EnvSpec(HandManipulatePenTouchSensorsDense-v1), EnvSpec(CubeCrash-v0), EnvSpec(CubeCrashSparse-v0), EnvSpec(CubeCrashScreenBecomesBlack-v0), EnvSpec(MemorizeDigits-v0), EnvSpec(three-armed-bandits-v0), EnvSpec(five-armed-bandits-v0), EnvSpec(ten-armed-bandits-v0), EnvSpec(MultiarmedBandits-v0)])

Comment: Hi @Bonson, have you made `pip install -e .` after installing the `gym_armed_bandits` library?
Answer: It could be a problem with your Python version: k-armed-bandits library was made 4 years ago, when Python 3.9 didn't exist. Besides this, the configuration files in the repo indicates that the Python version is 2.7 (not 3.9).
If you create an environment with Python 2.7 and follow the setup instructions it works correctly on Windows:
git clone gym_armed_bandits
cd gym_armed_bandits
pip install -e .

Comment: I somehow missed this. It worked on Python 3.9 as well. Need to see if all the functionalities work as required. Thank you for this.


Why would some backup schedules work and others not?

Question: I have several backup schedules set up:

Every 15 minutes (keeping 12)
Every 8 hours (keeping 9)
Daily Backup (keeping 31)
Weekly Backup (keeping 52)
Yearly Backup (keeping 5)

The perplexing problem is that some of them seem to be working and some not, even though they're all using the default profile, and they're all enabled, and they're all being saved to the scheduled backups directory.
Here are the backups that are appearing:
<code>sitename-2012-11-10T18-10-05 Sat, 11/10/2012 - 18:10 25 min  311.12 KB
sitename-2012-11-10T18-03-58 Sat, 11/10/2012 - 18:03 31 min  305.58 KB
sitename-2012-11-10T17-48-49 Sat, 11/10/2012 - 17:48 46 min  308.19 KB
sitename-2012-11-10T16-43-06 Sat, 11/10/2012 - 16:43 1 hour  303.99 KB
sitename-2012-11-10T16-43-05 Sat, 11/10/2012 - 16:43 1 hour  303.99 KB
sitename-2012-11-10T15-43-02 Sat, 11/10/2012 - 15:43 2 hours 304.01 KB
sitename-2012-11-10T14-43-00 Sat, 11/10/2012 - 14:43 3 hours 303.99 KB
sitename-2012-11-10T13-38-00 Sat, 11/10/2012 - 13:38 4 hours 303.95 KB
sitename-2012-11-10T12-33-00 Sat, 11/10/2012 - 12:33 6 hours 303.95 KB
sitename-2012-11-10T11-28-01 Sat, 11/10/2012 - 11:28 7 hours 303.94 KB
sitename-2012-11-10T10-23-00 Sat, 11/10/2012 - 10:23 8 hours 303.95 KB
sitename-2012-11-10T09-18-02 Sat, 11/10/2012 - 09:18 9 hours 303.94 KB
</code>
The fact that there are 12 (which is the number mentioned in one of the schedules) makes me think that perhaps the Backup & Restore module has a major bug: perhaps it assumes you'll only have one or two schedules, and my 5 overwhelmed it.
Is there any other reason for the behavior you're seeing?
Comment: You should override the name to include the schedule the schedule name so you can figure out what is going on.
Answer: By creating different destinations for each schedule, the problem goes away.
Apparently Backup & Migrate simply assumes each schedule has a separate destination (although the UI gives no hint that this would be the case, and in fact gives reason to expect that there's no problem with sharing a destination).
For instance, one of my schedules is set to keep 12 copies.  Rather than keeping track of which backups belong to which schedule, it merely deletes all but the last 12 backups in the directory.
At any rate, isolating each backup allows everything to work as expected.


Need help with proof in elementary set theory

Question: At the risk of stretching the patience of readers here, I will try this once more. (See: Need help with proof about Dedekind-infinite sets for my initial debacle.)
Suppose we have

$C \subseteq B \subseteq A$
Bijection $f:A\rightarrow C$
$\forall x (x\in A \wedge x\notin C \rightarrow \neg\exists y (y\in A \wedge f(y)=x))$  (Edit: Turns out to be redundant)

Can we prove there exists bijection $g:B\rightarrow C$?
Hopefully without invoking the convoluted machinery of the Cantor-Bernstein-Schroder proof?
Comment: @GitGud Changed $\subset$ to $\subseteq$ if that is more commonly used.
Comment: @BrianM.Scott Don't you mean $f^{-1}(y)=x$?
Comment: Never mind: I misread the direction of the bijection.
Answer: Condition 3 follows from 2, as the codomain of $f$ is $C$.
Now, if you have a proof that 1 and 2 imply that there is a bijection between $B$ and $C$, then you would have a proof of Cantor-Bernstein. And no one has been able to prove Cantor-Bernstein without the "convoluted machinery".
Comment: I personally find this version of Cantor-Bernstein somewhat easier to deal with than the usual one (where you have injections of two sets into each other). The "convoluted machinery" is still pretty much the same, but my mental picture of it is somewhat simpler.
Comment: OK, I can see how 3 follows from 2. So, 3 is redundant. Thanks.
Answer: Let me try to describe the mental picture that I mentioned in my comment to Martin Argerami's answer.  (Unfortunately, I have no idea how to produce an actual picture here, so I'll have to settle for a description.  I assure you the picture can be drawn more quickly than the description can be read.)  Imagine $A$ as a long horizontal rectangle; imagine $A-B$ as a small sub-rectangle $A_1$ at the right end; and therefore imagine $B$ as a long (but not quite so long as $A$) subrectangle of $A$, extending from the left end of $A$ to well beyond the middle.  Imagine $B-C$ as a small rectangle $B_1$ at the left end of $B$; so $C$ is a (still rather long) rectangle occupying the middle of $A$.  The given bijection $f$ maps $A$ into this sub-rectangle.  Let $A_2=f[A_1]$ and imagine it as occupying the right end of $C$, adjacent to $A_1$; similarly, imagine $B_2=f[B_1]$ as occupying the left end of $C$, adjacent to $B_1$; so $f[C]$ is the middle part of $C$.  $A_2$ and $B_2$, being part of $C$, are mapped by $f$ into this middle part $f[C]$.  Imagine $A_3=f[A_2]$ at the right end of $f[C]$, $B_3=f[B_2]$ at the left end, and $f^2[C]$ (by which I mean $f[f[C]]$) in the middle.  Continue in this way with $A_n=f[A_{n-1}]$ at the right and $B_n=f[B_{n-1}]$ at the left end of $f^{n-2}[C]$, with $f^{n-1}[C]$ in the middle.
So we have, starting at the right end, the sequence of sets $A_1,A_2,\dots$, each mapped to the next by $f$; similarly, starting at the left end, we have $B_1,B_2,\dots$ each mapped to the next by $f$.  In the middle, there might be some points in $\bigcap_{n\in\mathbb N}f^n[C]$.
Now we can biject $B$ to $C$ by applying $f$ to everything in the $B_n$'s (shifting each $B_n$ one step to the right) while leaving everything else ($A_n$'s and $\bigcap_{n\in\mathbb N}f^n[C]$) fixed.
Answer: I don't know what's so convoluted about the proof of the Cantor-Bernstein theorem. It's a corollary of Knaster's fixed-point theorem:
For any function $\varphi:\mathcal P(C)\rightarrow\mathcal P(C)$ such that $X\subseteq Y\subseteq C\Rightarrow\varphi(X)\subseteq\varphi(Y)$, there is a set $X\subseteq C$ such that $\varphi(X)=X$.
The proof of Knaster's theorem can't require all that much "convoluted machinery", because it was a Putnam problem in 1956 or 1957. (It must have been the easiest problem on the Putnam that year, because it's the one I solved, not on the exam but by the next day.) To prove it, just define $X=\bigcup\mathcal S$ where $\mathcal S=\bigcup\{Z:Z\subseteq\varphi(Z)\}$, and show that $\varphi(X)=X$.
To see this, note that if $Z\in\mathcal S$ then $Z\subseteq X$ and so $Z\subseteq\varphi(Z)\subseteq\varphi(X)$. Since the elements of $\mathcal S$ are subsets of $\varphi(X)$, it follows that $X=\bigcup\mathcal S\subseteq\varphi(X)$ and so $\varphi(X)\subseteq\varphi(\varphi(X))$, which means that $\varphi(X)\in\mathcal S$, whence $\varphi(X)\subseteq X$.
Now suppose that $C\subseteq B\subseteq A$ and that $f:A\rightarrow C$ is an injection. Define $\varphi:\mathcal P(C)\rightarrow\mathcal P(C)$ by setting $\varphi(X)=C\setminus f(B\setminus X)$. Seeing as $X\subseteq Y$ implies $B\setminus X\supseteq B\setminus Y$ implies $f(B\setminus X)\supseteq f(B\setminus Y)$ implies  $C\setminus f(B\setminus X)\subseteq C\setminus f(B\setminus Y)$ implies $\varphi(X)\subseteq\varphi(Y)$, it follows by Knaster's theorem that $\varphi(X)=X$ for some $X\subseteq C$, i.e., $C\setminus f(B\setminus X)=X$, or in other words, $f(B\setminus X)=C\setminus X$. Thus we get a bijection $g:B\rightarrow C$ by defining $g(x)=x$ for $x\in X$ and $g(x)=f(x)$ for $x\in B\setminus X$.
Comment: Any hints on proving $\varphi(X)=X$ in Knaster's theorem?


How do I calculate in the background1 DoWork event so the ReportProgress(percentage) will get to 100% and the progressBar1 will get to the end?

Question: Thats what I did in the DoWork event and in the ProgressChanged event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    double total = streamlength;
    int counter = 0;
    int percentage = 0;
    BackgroundWorker bgw = (BackgroundWorker)sender;
    int i = 0;

    for (double x = 0; x < streamlength; x += dt)
    {
        streamDouble[0] = x;
        SaveFramesFromVideo(strVideoFile, streamDouble, sf + i.ToString("D6") + ".bmp");
        i++;
        counter += 1;
        percentage = counter * 100 / (int)total;
        bgw.ReportProgress(percentage);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

I see the progressBar1 progress with the green color from left to right but in the middle im getting exception in the ProgressChanged event:

ArgumentOutOfRangeException: Value of '133' is not valid for 'Value'.
  'Value' should be between 'minimum' and 'maximum'. Parameter name:
  Value

The error is on the line: progressBar1.Value = e.ProgressPercentage; in the progressChanged event.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExtractFrames.Properties;
using ExtractFrames;
using JockerSoft.Media;
using JockerSoft;
using Interop.qedit;
using Interop;
using System.Runtime.InteropServices;
using System.IO;

namespace ExtractFrames
{
    public partial class Form1 : Form
    {
        double dt;
        FolderBrowserDialog fb;
        OpenFileDialog openFileDialog1;
        private bool _connect = false;
        private bool _rightButton;
        List<LinePoint> _points = null;
        private float _circleWidth = 10;
        DirectoryInfo dir1;
        FileInfo[] fi;
        double streamlength;
        MediaDet mdd;
        double x;
        string sf;
        double[] streamDouble ;
        string strVideoFile;
        public Form1()
        {
            InitializeComponent();
            fb = new FolderBrowserDialog();
            openFileDialog1 = new OpenFileDialog();
            mdd = new MediaDet();
            streamDouble = new double[1];
            sf = @"d:\Frames\";
            dir1 = new DirectoryInfo(sf);
            fi = dir1.GetFiles("*.bmp");
            if (fi.Length == 0)
            {
                trackBar1.Enabled = false;
            }
            else
            {
                trackBar1.Minimum = 0;
                trackBar1.Maximum = fi.Length - 1;
                trackBar1.Value = 0;//fi.Length - 1;
                Bitmap newImage;
                newImage = new Bitmap(fi[0].FullName);
                pictureBox1.Image = newImage;
            }
        }

        private  void getFrameRate()
        {
            // Get framerate
            MediaDet md = new MediaDet();
            md.Filename = strVideoFile;
            //md.CurrentStream = 0;                     // choose the video stream
            x = md.FrameRate;
            double i = md.StreamLength;

        }

        public static void SaveFramesFromVideo(string videoFile, double[] positions, string outputBitmapFiles)
        {
            if (videoFile == null)
                throw new ArgumentNullException("videoFile");

            double streamLength;

            IMediaDet mediaDet = null;
            try
            {
                _AMMediaType mediaType;
                if (openVideoStream(videoFile, out mediaDet, out mediaType))
                {
                    streamLength = mediaDet.StreamLength;
                    Size target = getVideoSize(mediaType);
                    int iteration = 0;
                    foreach (double position in positions)
                    {
                        iteration++;
                        string outputBitmapFile = string.Format(outputBitmapFiles, iteration);
                        mediaDet.WriteBitmapBits(position, target.Width, target.Height, outputBitmapFile);
                    }

                }
            }
            catch (COMException)
            {
                throw new InvalidVideoFileException();
            }
            finally
            {
                if (mediaDet != null)
                    Marshal.ReleaseComObject(mediaDet);
            }

            return;

        }

        private static Size getVideoSize(_AMMediaType mediaType)
        {
            WinStructs.VIDEOINFOHEADER videoInfo = (WinStructs.VIDEOINFOHEADER)Marshal.PtrToStructure(mediaType.pbFormat, typeof(WinStructs.VIDEOINFOHEADER));

            return new Size(videoInfo.bmiHeader.biWidth, videoInfo.bmiHeader.biHeight);
        }

        private static Size scaleToFit(Size target, Size original)
        {
            if (target.Height * original.Width > target.Width * original.Height)
                target.Height = target.Width * original.Height / original.Width;
            else
                target.Width = target.Height * original.Width / original.Height;

            return target;
        }
        private static Size scaleToFitSmart(Size target, Size original)
        {
            target = scaleToFit(target, original);

            if (target.Width > original.Width || target.Height > original.Height)
                return original;

            return target;
        }

        private static bool openVideoStream(string videoFile, out IMediaDet mediaDet, out _AMMediaType aMMediaType)
        {
            mediaDet = new MediaDet();

            //loads file
            mediaDet.Filename = videoFile;

            //gets # of streams
            int streamsNumber = mediaDet.OutputStreams;

            //finds a video stream
            for (int i = 0; i < streamsNumber; i++)
            {
                mediaDet.CurrentStream = i;
                _AMMediaType mediaType = mediaDet.StreamMediaType;

                if (mediaType.majortype == JockerSoft.Media.MayorTypes.MEDIATYPE_Video)
                {
                    //video stream found
                    aMMediaType = mediaType;
                    return true;
                }
            }

            //no video stream found
            Marshal.ReleaseComObject(mediaDet);
            mediaDet = null;
            aMMediaType = new _AMMediaType();
            return false;
        }

        private bool LoadPictureAt(int nIndex, object c)
        {

            bool bRet = false;

            if (nIndex >= 0 && nIndex < fi.Length)
            {
                if (c.Equals(trackBar1))

                    pictureBox1.Load(fi[nIndex].FullName);
                bRet = true;

            }

            return bRet;
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            LoadPictureAt(trackBar1.Value, sender);
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (_points != null)
            {
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                using (SolidBrush myBrush = new SolidBrush(Color.Red))
                {
                    for (int i = 0; i < _points.Count; i++)
                    {
                        try
                        {
                            Point pt = _points[i].Point;
                            e.Graphics.FillEllipse(myBrush, new RectangleF(pt.X - _circleWidth / 2F, pt.Y - _circleWidth / 2F, _circleWidth, _circleWidth));

                            if (i > 0)
                            {
                                if (_points[i].Connected)
                                    e.Graphics.DrawLine(Pens.Blue, _points[i - 1].Point, _points[i].Point);
                            }
                        }
                        catch ( Exception err)
                        {
                            textBox1.Text = err.ToString();
                        }
                    }
                }
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (_points == null)
                    _points = new List<LinePoint>();
                _points.Add(new LinePoint() { Point = new Point(e.X, e.Y), Connected = _connect });
                pictureBox1.Invalidate();
            }

            if (e.Button == MouseButtons.Right)
            {
                _connect = !_connect;
                _rightButton = true;
            }
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            _points.Clear();
            if (_rightButton && _points != null)
                _points.Clear();

            pictureBox1.Invalidate();
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            _rightButton = false;
        }

        public class LinePoint
        {
            public Point Point { get; set; }
            public bool Connected { get; set; }
        }

        private void loadVideoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Select a video file";
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.FileName = null;
            openFileDialog1.Filter = "Video Files|*.wmv;*.3gp;*.avi";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            DialogResult result1 = openFileDialog1.ShowDialog();
            string file1 = openFileDialog1.FileName;
            if (result1 == DialogResult.OK)
            {
                strVideoFile = file1;
                mdd.Filename = strVideoFile;
                streamlength = mdd.StreamLength;
                dt = (double)1 / mdd.FrameRate;//(double)20; //mdd.FrameRate;
                backgroundWorker1.RunWorkerAsync();
            }
            if (result1 == DialogResult.Cancel)
            {
                if (file1 == "")
                {
                }
            }
        }

        private void changeExtractedFramesDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fb.Description = "Directory To Extract Frames";
            DialogResult result = fb.ShowDialog();
            string file1 = fb.SelectedPath;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = streamlength;
            int counter = 0;
            int percentage = 0;
            BackgroundWorker bgw = (BackgroundWorker)sender;
            int i = 1;
            for (double x = 0; x < total; x += dt)
            {
                streamDouble[0] = x;
                SaveFramesFromVideo(strVideoFile, streamDouble, sf + i.ToString("D6") + ".bmp");
                i++;
                counter += 1;
                //percentage = counter * 100 / (int)total;
                percentage = (int)((x / streamlength) * 100.0);
                bgw.ReportProgress(percentage);
            }
            bgw.ReportProgress(100);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //progressBar1.Value = e.ProgressPercentage;
            progressBar1.Value = Math.Max(0, Math.Min(100, e.ProgressPercentage));
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            fi = dir1.GetFiles("*.bmp");
            if (fi.Length == 0)
            {
                trackBar1.Enabled = false;
            }
            else
            {
                trackBar1.Enabled = true;
                trackBar1.Minimum = 0;
                trackBar1.Maximum = fi.Length - 1;
                trackBar1.Value = 0;//fi.Length - 1;
                Bitmap newImage;
                newImage = new Bitmap(fi[0].FullName);
                pictureBox1.Image = newImage;
            }
        }
    }
}

Comment: percentage should always be between 0 and 100 right? UR passing 133 here.
Answer: I can't see the declaration of the variables streamlength and dt. The backgroundworker (as its name suggests) works in the background. So your program is working in parallel, the UI is reactive and it might be possible that the value of streamlength is changed while backgroundworker is working. In that case the for loop is running to a different end streamlength then the calculation of the percentage (you stored streamlength in total and use that for calculating) A first approach is to change the method backgroundWorker1_DoWork in that way:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    double total = streamlength;
    int counter = 0;
    int percentage = 0;
    BackgroundWorker bgw = (BackgroundWorker)sender;
    int i = 0;
    for (double x = 0; x < total; x += dt)
    {
        streamDouble[0] = x;
        SaveFramesFromVideo(strVideoFile, streamDouble, sf + i.ToString("D6") + ".bmp");
        i++;
        counter += 1;
        percentage = counter * 100 / (int)total;
        bgw.ReportProgress(percentage);
    }
}

That should work now, but I would highly advise you to rethink the program.
Comment: I just edited the question and put in the complete code you can see it now in the top where im asking.
Comment: @ShakulShakuli: Come on, Pieter and I gave you enough hints so you can find the error. It's useless to post **all** your code. And it's near to spam, if you post empty methods and commented-out code! You will get hints and help from Stack Overflow, but that is not a platform to make a code review!
Answer: Try making the following changes. First, change the calculation of the percentage to:
percentage = (int)((x / streamlength) * 100.0);

This uses x instead of a counter. I would make this change because this is what you're actually using to loop.
Next, to ensure you don't get problems because of rounding errors, you could change assigning the value to the progress bar to:
progressBar1.Value = Math.Max(0, Math.Min(100, e.ProgressPercentage));

This will ensure that the assigned value is always between 0 and 100.
Comment: Pieter i used Fischermaen above solution and then changed the two lines as you suggested and its working but in the end the progressBar1 green color stop just a little bit before the end it dosent get to the end completed. Very liittle ot the end it stop.
Comment: Just add `bgw.ReportProgress(100);` after the `for` loop.
Comment: Pieter i did and just checked now the progressBar1 is getting to 100% the green is getting to the end but in realtime i saw also the directory where its creating the files to and after the progressBar1 is on 100% the program still creating some files. Like there is no a sync between the files creation on the disk and the progressBar1.
Comment: I'm afraid I would not be able to help you with that because solving this depends too much on the rest of your application.


Edit view link redirected to preview link automatically

Question: I have opened edit view option on localhost using Drupal 7. firstly, the requested page i.e http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block_14?destination=node open successfully, however, It automatically redirected to edit preview link i.e http://localhost/xxx/drupal/admin/structure/views/view/products/preview/block_14. I have tried to find the problem but not able to do.
kindly assist me.
Thanks in advance.
Answer: It is not a problem, it's done on purpose for convenience of being able to quickly edit the view and return to the page where you were at initially.
If you want to stay at edit page then just remove the ?destination=node part from the URL: http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block_14
Comment: thank you for your answer, however, it did not work for me.
Comment: What do you mean it didn't work - the destination either set or not and there is simply no other way. Give me an access and I'll fix the problem for you.
Comment: there were some issues regarding Ajax, which created some conflicts, now it's working fine. Thank you:)
Comment: Sakura, the answer is correct regardless was caused the issue and should be accepted. You could also provide the detailed description of what actually was causing the problem and the way how you resolved it and accept your own answer, so this page could be useful for other users looking solution for similar problem. Whatever you do, please just do not leave your questions with no answer accepted if you want them to keep helping you.


Como posso classificar um teste, release ou feature?

Question: Se eu crio um teste em algo que já existe, isso entra como release ou feature em um fluxo do git-flow? até por que um teste não deixa de ser uma melhoria mas também não deixa de ser algo novo.
Answer: Considerando a separação como abaixo:

feature branches: Contém códigos que podem ou não ser incluídos na próxima release, o merge das features é realizado na branch develop
develop branch: Contém features que serão disponibilizadas na próxima release
master branch: Contém o código da release atual partindo da branch develop, que entrará em produção
hotfix branches: Partem da branch master ou da branch que equivale a versão atual em produção, utilizada para um reparo imediato em produção

Não existe problema em tratar apenas o desenvolvimento de um teste como uma feature, você não possui a necessidade imediata de incluí-lo em produção (hotfix).
Seguindo o fluxo normal, sua alteração entraria como feature -> develop -> master. Em alguns casos isto se torna verboso, caso seja pontual e de comum acordo entre o time, você pode enviá-lo para a develop diretamente.
Recomendo a leitura do fluxo aqui


__weak reference is still a mystery for me

Question:  NSString *myString = [NSString stringWithFormat:@"string1"];
__weak NSString *myString1 = myString;
myString= nil;
NSLog(@"%@, %@",myString,myString1);

I was expecting null , null. But the output is string1, (null). Why is myString1 still holding the value as myString is set to nil?
Comment: It probably won't zero the weak ref until later (exiting the block, etc)
Comment: This question is not about Xcode nor iPhone. It's a question about Objective-C.
Comment: For me, the output is `(null), string1`.
Comment: Don't feel bad -- I'm not sure anyone really understands it (though many pretend to).
Answer: Weak references only get zeroed when the object is deallocated. That object is not immediately deallocated (it's probably in an autorelease pool here, though there are many other reasons something might be held onto in different situations), so the reference stays alive.
Comment: This must be the answer. In non-ARC land, `[NSString stringWithFormat]` returns an autoreleased object, so presumably ARC codes it that way too. If instead we do `NSString *myString = [[NSString alloc] initWithFormat:@"string1"];` we get the nil output the questioner expects.
Comment: @SteveWaddicor Sort of;  the order of deallocation or the time of deallocation is not necessarily guaranteed.  In fact, turning on the optimizer will likely make things deallocate more quickly (because the optimizer will eliminate what are effectively `retain/autorelease` sequences).
Comment: Thanks for answering this. i was expecting the same.
Answer: Try something like this:
NSString *myString;
NSString* __weak myString1;
@autoreleasepool{
    myString= [NSString stringWithFormat:@"string1"];
    myString1= myString;
    myString= nil;
}
NSLog(@"%@, %@",myString,myString1);

Explanation
You probably noticed that there are many methods to allocate a string or generally an object:
1) [NSString stringWithFormat: ...] / [[NSString alloc]initWithFormat: ...] ;
2) [NSArray arrayWithArray: ...] / [[NSArray alloc]initWithArray: ...];
...
(Also for many other classes)
The first category of methods return an autoreleased object. The second one a non autoreleased object. Indeed if in the above code you use alloc + initWithFormat: instead of stringWithFormat: you don't need an autorelease pool to see that both objects will be nil.
Answer: I think your question may be answered by this quote from the Memory Management Guide

In particular, you should not design classes so that dealloc will be
  invoked when you think it will be invoked. Invocation of dealloc might
  be delayed or sidestepped, either because of a bug or because of
  application tear-down.
Answer: The output should be (null), string1, not string1, (null). I guess you typed it the wrong way around.
You're explicitly setting one reference to nil, but the other reference is still being used within the scope of the definition (because you're using it in the NSLog). So, it won't be released by ARC until that usage is complete.

The weak reference isn't holding onto it. The fact that you're using it means that ARC will hold onto it (by not adding the release code). Once that usage is complete, ARC will release the object and then the weak reference will be nilled.
Comment: But surely the point of __weak rather than __strong is that it WON'T hold on to the thing being pointed to.
Comment: It's simply the expected autorelease behaviour of [NSString stringWithFormat]. See Chuck's answer and my comment below it.


Using Sudo in Yeoman/Grunt

Question: I'm trying to automate creating virtual host files on my mac in yeoman/grunt. After yeoman gets the file all tidy I call
grunt.file.write('/etc/apache2/virtualhosts/' + fileName, tidyFileContents);

But this doesn't work because I need permissions to move anything around in the etc/apache2/virtualhosts/ dir. I've thought about doing
grunt.file.write(fileName, tidyFileContents);

then follow up with a:
sudo mv fileName /etc/apache2/virtualhosts

but I don't know how to write that code in javascript. My question is how can I write the above code ^ in yeoman syntax to get the desired result. Or what are some other ways I can sudo a file into a permissions virtualhost dir. My only constraint is that I cannot take the permissions off the virtualhosts dir. Thanks for your help ahead of time!
Answer: This is independent of yeoman, you can use process exec and execute any shell command.
Comment: Thanks mate, I knew this was possible in C. Had no idea this was available in javascript. Changed my day today haha

Using Sudo in Yeoman/Grunt


Adding menu item to Spree

Question: I've created a spree site and using spree_essentials and spree_essentials blog have added a blog to my site. How can I add a link to the blog from my main navigation?
I've created an extension for customization called Theme. It placed this folder into my main project folder rather than in to vendor/extensions not sure if that matters or not.
Pretty new to rails and Spree.
Here's the link for the extensions I used: https://github.com/citrus/spree_essential_blog
Answer: To do what you want add a hook inside lib/your_extension_hooks.rb, something like this :
insert_after : sidebar do
    # you can add a partial too ^^
    %(test)
end

You can find all available hook here.

Adding menu item to Spree


Difference between tableView.cellForRow(at:) and tableView.dataSource?tableView(tableView:cellForRowAt:)

Question: I'm unit testing on a tableView whether it renders a cell.
And I found that tableView.cellForRow(at:) returns nil, while tableView.dataSource?tableView(tableView:cellForRowAt:) returns the right cell.
Here's my unit test code.
it("renders one option text") {
    let indexPath = IndexPath(row: 0, section: 0)

    let cell = sut.tableView.dataSource?.tableView(sut.tableView, cellForRowAt: indexPath)

    let cell2 = sut.tableView.cellForRow(at: indexPath)

    expect(cell?.textLabel?.text).toEventually(equal("A1"))  // test suceeded
    expect(cell2?.textLabel?.text).toEventually(equal("A1")) // test failed
}

So I'm curious about the difference of the two methods.
Apple's document says that tableView.cellForRow(at:) returns nil if the cell is not visible, so I'v understood that tableView.cellForRow(at:) returns nil when it's under unit testing,
but I'm not sure the time order of the two methods being called and when tableView.cellForRow(at:) get the right value(cell).
Answer:  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

This method is used to generate or dequeue the cells as required by tableView. This is not the UITableView member method. Instead, it is a protocol method and another object, which will be a data source, will implement and return the value. So it will always return a cell whether we are unit testing or while debugging the app.
tableView.cellForRow(at:)

This method is not the generator method. It is a member method of UITableView as a utility method for eg. for getting selected row we use tableView.selectedRow. So it is supposed to return cell for any indexPath.
As we know UITableView doesn't create cells equal to rows drawn. Suppose you wanted to draw 100 rows then UITableView only create few extra cells apart from cells which are visible. So if you pass any indexPath which is not among the visible rows then practically that cell doesn't exist. Because tableview is waiting for you to scroll and reuse the unused cells. So whether you are doing unit testing or working on app it will always show nil for cells which are not visible.
Answer: tableView.dataSource?tableView(tableView:cellForRowAt:) will always dequeue a new cell.  It isn't the one on display unless tableView is the one that called it.


Cálculo de horas com Java 8

Question: Eu estava fazendo uns testes com o java 8, e estava tentando calcular a diferença entre horas de duas datas. Eu consegui de três jeitos, porém, não sei qual seria o mais correto e gostaria da ajuda de vocês.
 LocalDateTime t1 = LocalDateTime.of(2014, Month.NOVEMBER, 25, 8, 23);
 LocalDateTime t2 = LocalDateTime.of(2014, Month.NOVEMBER, 25, 10, 23);

 long horas = ChronoUnit.HOURS.between(t1, t2);
 System.out.println(horas);

 long horas2 = t1.until(t2, ChronoUnit.HOURS);
 System.out.println(horas2);

 long horas3 = Duration.between(t1, t2).toHours();
 System.out.println(horas3);

Pelo que está na documentação, o horas2 e o horas3 são equivalentes, porém, fiquei em dúvida do primeiro modo. É correto?
Comment: Só para questão de conhecimento, o próprio método `HOURS.between(t1, t2)` equivale à `t1.until(t2, ChronoUnit.HOURS)`.
Answer: Me parece que as três formas estão corretas e são equivalentes.
No entanto, me parece que as três vão falhar se houverem mudanças referentes a horário de verão ou mudança de fuso horário.
Comment: Sim, parece que o `LocalDateTime` não tem suporte à `time-zone`, então... Eu executei o trecho de código e aqui deu o mesmo resultado. Diferença sempre de duas horas.

Cálculo de horas com Java 8


Relation between multiplicative and additive identity in an ordered field

Question: In class, we prove that 1>0 by using order axioms of a field. The question is can we conclude that multiplicative identity is always less than the additive identity for any arbitrary ordered field?
Comment: As you mentioned, the multiplicative identity $1$ is greater than additive identity $0$, or I misunderstand you.
Comment: Was the thing proved in class a special case then (for instance $\mathbb R$)? If not then your question sounds a bit like: "if a statement is proved then can we conclude that we are dealing with a true statement?" Of course the answer on that is: "yes".
Comment: In class it is proved for R.
Answer: You have $-x \le 0 \le x$ or $x \le 0\le -x$, and $0\le x^2$ for every $x\in k$. Choose $x=1$. Now $x=x^2\neq0$, so $0<1$.


Alternative to punching bag

Question: I'm not entirely sure this question fits here, but here we go.
I've started with boxing/kickboxen a bit over a year ago. Now I'm looking for a way to train at home. Especially with a punching bag or something similar to conditions my body for the impact of punching amd kicking,  so shadowboxing is not really suited.
The issue is that I live in an apartment and I don't have a lot of space for anything so I'm looking for a space saving or easily storable solution.
Comment: Don't you have a pillar to train like Tong Po?
Comment: Nope my apartment isn't that fancy
Answer: I know this is old, but one option you have is to use an inflatable punching bag. That way you can blow it up when you need it and deflate it when you are done. They can be purchased on Amazon relatively cheaply.

Alternative to punching bag


How to save an image resource

Question: I have brought an image in from an API and cropped it using imagecrop in a custom module. I now have an image resource. But I cannot figure out how to turn the resource into a file I can save in Drupal or just save the resource directly as a file through Drupal. I have tried variations of file_get_contents and file_save_data. Any help would be appreciated.
When I use the following:
<code>$cropped_image = imagecrop($image_resource, $rect);
$final_file = file_save_data($cropped_image);
$type = array('type' => $content_type);
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($type);
$node->field_image = array(
  'target_id' => $image_file->id(),
);
$node->save();
</code>
I get the error "Call to a member function id() on bool in" on the $node->field_image line. That has made me think that the resource is not getting saved into a file with file_save_data() (obviously, not exactly sure what is happening).
When I included a file_get_contents($cropped_image) and then process that through file_save_data (as I do when I bring in an image from a URL), I end up with an error that the system is unable to handle the request in nothing in the recent log messages.
I have tried various other methods as well with no joy.
Comment: Googling for *drupal 8 programmatically create file* brings up quite a bunch of useful resources. Better update the question and show the code that's currently not working.
Comment: Added some code, thanks. What I have found Googling has all been for URL or actual files. What is catching me up is that I have a resource (when I ksm $cropped_image I get "Resource id $903"...I could certainly be misunderstanding what this is and how to use it), not an actual file, out of the crop.
Comment: Did you tried ```file_save_data(stream_get_contents($cropped_image));``` ? Also there is a typo in ```$final_file``` and ```$image_file variable naming.```
Answer: I may have had the code correct at some time yesterday, but I was running out of memory on my localhost. I ended up rewriting some of the code and - once I realized I was having memory issues - moved everything onto the server, where it all worked like a charm. Sorry for asking the question. And, thanks, Simon, for provoking me to question everything anew with your comment.
Here is my final code;
<code>            $cropped_image = imagecrop($precrop_resource, $rect);
            imagedestroy($precrop_resource);

            $file_path = \Drupal::service('file_system')->realpath('public://');
            imagejpeg($cropped_image, $file_path . '/temp-image.jpg');

            // load the image
            $cropped_data = file_get_contents($file_path . '/temp-image.jpg');
            $cropped_file = file_save_data($cropped_data);
            unset($cropped_data);
</code>
Then I added the image to the node object and saved the node.
EDIT:
I eventually realized a couple issues with the above code. First, it was not just my memory on the localhost; processing 10MB+ jpegs would exhaust the memory on the server as well because the GD2 image tools process everything in uncompressed format. Second, the files were saving without .jpg on their filenames, so using them could be a problem.
So, I ended up using the ImageMagick to process things and added another variable to the file_save_data function call.
Here is my new and improved final code:
<code>            // crop the image
            $precropped_image = new Imagick($precrop_file->getFileUri());
            $precropped_image->cropImage($rect['width'], $rect['height'], $rect['x'], $rect['y']);
            $precropped_image->writeImage($file_path . '/temp-image.jpg');

            // save the cropped image in the Drupal DB
            $cropped_data = file_get_contents($file_path . '/temp-image.jpg');
            $cropped_file = file_save_data($cropped_data, 'public://' . $image_title . '-og.jpg');
</code>

How to save an image resource


login_required decorator gives "object has no attribute 'user'" error

Question: New to Django. I have a view that works well without @login_required decorator.
urls.py
urlpatterns = [
    path('play/', play.as_view(), name='play'),

view.py with @login_required commented out
from django.contrib.auth.decorators import login_required
.
.
class play(View):
    #@login_required
    def get(self, request, *args, **kwargs):
        print("GET request: ", request)
        return render(request, 'play.html', {})

**EDIT:**adding the setting.py entries
LOGIN_URL = 'home'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

The page load correctly in the browser and the request is printed on the console as follows
GET request:  <WSGIRequest: GET '/play/'>
[16/Aug/2021 23:17:23] "GET /play/ HTTP/1.1" 200 3591
[16/Aug/2021 23:17:23] "GET /static/css/home.css HTTP/1.1" 200 96
[16/Aug/2021 23:17:23] "GET /static/js/home.js HTTP/1.1" 200 3544
[16/Aug/2021 23:17:23] "GET /static/js/main.js HTTP/1.1" 200 1451443
[16/Aug/2021 23:17:23] "GET /static/images/BlankPicture.png HTTP/1.1" 200 16272
Not Found: /favicon.ico
[16/Aug/2021 23:17:24] "GET /favicon.ico HTTP/1.1" 404 7793

OTOH, if I uncomment the @login_required line, I get following error.
AttributeError at /play/
'play' object has no attribute 'user'
Request Method: GET
Request URL:    http://127.0.0.1:8000/play/
Django Version: 2.2.12
Exception Type: AttributeError
Exception Value:
'play' object has no attribute 'user'
Exception Location: /usr/lib/python3/dist-packages/django/contrib/auth/decorators.py in _wrapped_view, line 20
Python Executable:  /usr/bin/python3
Python Version: 3.8.10
Python Path:
['/home/<username>/workspace/djangoapp/src',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/usr/local/lib/python3.8/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Mon, 16 Aug 2021 23:20:17 +0000

play.html is a vanilla html page with only static html in it. The error happens even if I am logged in on a different tab.
I see the error is happening in ....django/contrib/auth/decorators.py line 20
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):   <<<Here is the error

In all the other views I check if the user is is_authenticated first and then use user.request successfully. I wanted to remove that if-else loop and simplify my views using @login_required decorator.
I am following the documentation here The login_required decorator Where is my mistake?
EDIT: I want to redirect the user to 'home' url if they are not logged in.
Answer: This error is because login_required is reading self(which is the play view object as described by the error) instead of request when used as a decorator for a view inside a class.
Since this is a class-based view, login_required is used differently:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class play(View):
    ...

You can also use LoginRequiredMixin which works in a similar way:
from django.contrib.auth.mixins import LoginRequiredMixin

class play(LoginRequiredMixin, View):
    ...


sscanf returns 1 when searching for float in a string starting with the character n or i

Question: In the following code I would expect sscanf to return 0, but it returns 1 and assigns 0.000000 to the float variable x.  The same behavior occurs when the string begins with the letter i, but with no other letter.
<code>void main() {
    int ss_return;
    float x;
    char str_to_sscanf[] = "noduh";

    ss_return = sscanf( str_to_sscanf, "%f", &x );

    printf( "\n\nThe word passed to sscanf is %s", str_to_sscanf );
    printf( "\n\nWhen looking for a float, sscanf returned %d", ss_return );
    printf( "\n\nand assigned %f to x (declared as float)", x );
    printf( "\n\nWHY DID sscanf NOT RETURN ZERO????" );
}
</code>
The output of the program is:  "two weird looking characters"duh
What am I missing?
Comment: Don't use `void main`, use the proper `int main`.
Comment: Works on my machine.  You'll need to document the compiler and C runtime library that you are using.
Comment: Yes, what OS? I suspect this is a bug. *Probably* what's happening is that the buggy `scanf` implementation is seeing the `'n'` as the first character of a potential match (`"nan"`) and then, when it fails to fully match, considering a non-zero-length partial match as "success", then passing it to `strtod` and getting `0.0`.
Comment: Specifically `int main(void)` -- and the `#include ` is not optional.
Comment: Windows Vista Home Premium SP2; LCC-win32 compiler.  I was thinking something similar, that the implementation of sscanf was interpreting the leading n as something and the leading i as something and aborting.  Confusing that sscanf returns 1 in that case. I'll try using a different compiler...
Comment: Sorry, I must have not copied the #include  from my program.  I changed to int main( void ) and same behavior, but thanks for the correction.
Comment: What does `strtod("noduh", NULL)` return?
Comment: As a general rule, at least for command-line programs, it works better to include a newline at the end of each print format string rather than (or as well as) at the start.  It has no effect on the (mis)behaviour of `sscanf()` in this context.
Comment: Keith - strtod("noduh", NULL) returns 0.0, which it seems is the return value for strtod when it fails to convert.  For fun I also tried strtod("noduh999.999", NULL) and got 0.0 back.  To make sure strtod was working properly, I tried strtod("999.999", NULL) and got 999.999 back.
Comment: Recompiled the program using Tiny C and sscanf works as it should.  Very strange.  I have e-mailed the developer of lcc-win32 to see if he can explain the behavior of sscanf.  Thanks to all for your help!
Answer: My guess is that your library's state machine is seeing the "n" as the possible start of "NaN" and the "i" as the possible start of "inf" which is letting it fall into the float conversion code.  Then it immediately bails out because it can't finish parsing and assigns a default value.


Is it possible to deliver emails to a public folder

Question: Is it possible for me to create a new email address and make all the emails go to a public folder i have exchange 2003 on my server at the moment. If this is possible what would be the best way for me to implement this solution.
Comment: What are you trying to accomplish?
Comment: Create an email adress the alll mail ends up in public folder instead of personal mailbox
Comment: No what I meant was, are you wanting a bunch of different users to be able to see and respond to emails or?  I deliberately left off Public Folders because they're a management nightmare.  Are you currently using Public Folders or would you be turning them on just for this?
Comment: It's a long time since I used exchange 2003, but if I recall correctly you can simply "mail enable" them in the interface and job done. It's an absolute nightmare though - my default position for public folders these days is "don't... just don't".
Comment: we already use public folders and yes i would like everybody to be able to access them
Answer: Yes, it's possible. You need to mail enable the PF in ESM. The PF will be assigned an email address based on your Default Recipient Policy, but the email address can be changed if needed. You'll need to make sure the Anonymous and Default entities have the Contributor role on the PF in order to recieve email to the PF.
Answer: This is a pretty decent step-through of what you're trying to accomplish.  It's for Exchange 2000, but the steps should be the same for 2003.


How to evaluate $\int \frac{ds}{\sqrt{s^2-0.01}}$

Question: evaluate $$\int \frac{ds}{\sqrt{s^2-0.01}}$$
I think i should substitute $\sqrt{s^2-0.01}=t$ and then$\int \frac{dt}{s}$. But this doesn't make sense.
Comment: Hint:  let $s=0.1\sec\theta$.
Comment: Similar to: https://socratic.org/questions/how-do-you-integrate-int-1-sqrt-x-2-a-2-by-trigonometric-substitution
Comment: thanks a lot. i got the answer.
Answer: Follow the steps below,
$$I= \int \frac{ds}{\sqrt{s^2-0.01}}
=  \int \frac{10ds}{\sqrt{(10s)^2-1}}$$
With $10s=\cosh t$,
$$I= \int dt = t + C = \cosh^{-1}(10s) +C$$
Answer: Substitute $$s=\frac{\sec(u)}{10}$$ then we get
$$ds=\tan(u)\sec(u)du$$