To Find the extreme values of the function by Lagrange method of undetermined multipliers

Question: Find extreme values of the function $f(x,y) = xy$ on the surface $g(x,y) = \frac {x^2}{8} + \frac {y^2}{2} - 1 = 0$.
My approach :
First I created an auxilliary function $F(x,y,λ) = xy + λ(\frac {x^2}{8} + \frac {y^2}{2} - 1)$
Then I equated $\partial{F/\partial{x}} = 0$,  $\partial{F/\partial{y}} = 0$ and $\partial{F/\partial{λ}} = 0$.
I got the stationary points as: $(2,1), (-2,1), (-2,-1), (2,-1)$, where $λ = \frac{-x}{y}$.
How to proceed from here ? Should I directly put the stationary points in $f(x,y)$ and get its value ? In that case how will I know which points are extreme as some points may be saddle points also.
I needed a method of solving this question by finding double partial derivative.
Comment: You can try the bordered Hessian, see [here](https://math.stackexchange.com/questions/1833468/lagrange-multipliers-method-of-solving-question/1833502#1833502)
Comment: What do you mean by geometrical method?
Comment: Someone posted a graphical method, this was in reference to that. I will update it.
Comment: Does the link help? Can you see that there the second partial derivatives are made?
Comment: Yes I got the answer from Hessian method. But what if det H(x0,y0)=0 in that method?
Comment: Then you cannot make a max/min-decision with the bordered Hessian.
Answer: Solving $F(x,y,λ) = xy + λ(\frac {x^2}{8} + \frac {y^2}{2} - 1)\Rightarrow \cases{\partial{F/\partial{x}} = 0\\ \partial{F/\partial{y}} = 0\\ \partial{F/\partial{λ}} = 0}$ we obtain
four solutions
$$
\left[
\begin{array}{cccc}
x y & x & y & \lambda\\
 2 & -2 & -1 & -2 \\
 -2 & -2 & 1 & 2 \\
 -2 & 2 & -1 & 2 \\
 2 & 2 & 1 & -2 \\
\end{array}
\right]
$$
as can be depicted in the attached plot. See the four tangent points between the level curves from $x y$ and the elliptical constraint $\frac {x^2}{8} + \frac {y^2}{2} - 1=0$. We have two minima and two maxima.
Comment: Hey thanks for your answer. Can we have a geometrical solution to it by finding double partial derivative instead of graphical method? I will update this in my question also.
Comment: As the constraint is active, eliminating $y$ in $x y = f, \frac {x^2}{8} + \frac {y^2}{2} - 1=0$ we get at $f^2=\frac 14 x^2(8-x^2)$ and then we can verify at $x = \pm 2$ the behavior from $f$. We can use also the bordered hessian method https://en.wikipedia.org/wiki/Hessian_matrix
Comment: Yes I got the answer from bordered hessian method. Thanks a lot.


About the inequality $\left(\ln\left(\frac{4+x}{2x+2}\right)\right)^{2}\leq x!$

Question: Problem :
Let $-1<x<0$ then we have :
$$\left(\ln\left(\frac{4+x}{2x+2}\right)\right)^{2}\leq x!\tag{I}$$
My attempt:

I have tried :
$$x!=\frac{1}{x+1}-\gamma+O(x^2)$$
Wich is not enought .
Also I have tried derivative without success unfortunately .I think we need more terms in the power series like :
$$x!=\frac{1}{x+1}-\gamma+\frac{1}{12}(6\gamma^2+\pi^2)(x+1)+O(x^2)$$
The problem is we get an upper bound not an lower bound ...
Motivation
My motivation is to find a sufficiently accurate inverse of the Gamma function : see here

Question :
How to show $(I)$ ?
Thanks.
Comment: So you mean $\Gamma(x+1),$ not $x!$?
Comment: Notice that I wrote *"seems"* . In fact, numerically, it does not.
Answer: In this range, showing that $$\Bigg[\log \left(\frac{x+4}{2 x+2}\right)\Bigg]^2 \le x!$$ seems to be the same as showing that
$$\log \left(\frac{x+4}{2 x+2}\right)\le \sqrt{x!}$$ Consider the function
$$f(x)=\sqrt{x!}-\log \left(\frac{x+4}{2 x+2}\right)$$
$$f'(x)=\frac{3}{x^2+5 x+4}+\frac{1}{2} \sqrt{\Gamma (x+1)} \,\psi ^{(0)}(x+1)$$
$$f''(x)=-\frac{1}{(x+1)^2}+\frac{1}{(x+4)^2}+\frac{1}{4} \sqrt{\Gamma (x+1)} \left(\psi
   ^{(0)}(x+1)^2+2 \psi ^{(1)}(x+1)\right) $$ By inspection $f'(x)=0$ close to $x=-\frac 7{10}$. For this value
$$f\left(-\frac{7}{10}\right)=\sqrt{\Gamma \left(\frac{3}{10}\right)}-\log \left(\frac{11}{2}\right) >0$$ $$f''\left(-\frac{7}{10}\right)=\frac{1}{4} \sqrt{\Gamma \left(\frac{3}{10}\right)} \left(\psi
   ^{(0)}\left(\frac{3}{10}\right)^2+2 \psi
   ^{(1)}\left(\frac{3}{10}\right)\right)-\frac{4000}{363} > 0$$ So, we have the minimum
$$f\left(-\frac{7}{10}\right)=\sqrt{\Gamma \left(\frac{3}{10}\right)}-\log \left(\frac{11}{2}\right)=0.0248672$$ A full minimization of $f(x)$ gives a value of $0.02486720$ at $x=-0.700265$.
Answer: With the substitution $x = y - 1$, taking logarithm, it suffices to prove that, for all $0 < y < 1$,
$$\ln \Gamma(y) \ge 2\ln \ln \frac{3 + y}{2y}.$$
Using the known property
$$-\ln \Gamma(y) = \ln y + \gamma y +
\sum_{n=1}^\infty [\ln(1 + y/n) - y/n],$$
we have, for all $0 < y < 1$,
$$\ln \Gamma(y)
\ge - \ln y - \gamma y + \sum_{n=1}^2 [y/n - \ln(1 + y/n)]$$
where we have used $u \ge \ln (1 + u)$ for all $u\ge 0$.
It suffices to prove that, for all $0 < y < 1$,
$$- \ln y + (3/2 - \gamma)y - \ln(1 + y) - \ln(1 + y/2) \ge 2\ln \ln \frac{3 + y}{2y}$$
or
$$(3/2 - \gamma)y - \ln(1 + y) - \ln(1 + y/2) \ge 2\ln \left(\sqrt{y}\ln \frac{3 + y}{2y}\right).$$
Fact 1: For all $0 < y < 1$,
$$\sqrt{y}\ln \frac{3 + y}{2y} \le \frac{7770\gamma + 47353}{195804\gamma - 59850} - \frac{8}{63}y.$$
(Hint: Use $y = z^2$ and take derivative.)
Using Fact 1, it suffices to prove that
$$(3/2 - \gamma)y - \ln(1 + y) - \ln(1 + y/2) \ge 2\ln \left(\frac{7770\gamma + 47353}{195804\gamma - 59850} - \frac{8}{63}y\right).$$
Denote $f(y) = \mathrm{LHS} - \mathrm{RHS}$. We have
$$f'(y) = (16y - 5)g(y).$$
where
$$g(y) = \frac{(3108\gamma^2 - 5612\gamma + 1425)y^2 + (9324\gamma^2 - 10620\gamma + 9799)y + 6216\gamma^2 - 1900\gamma + 12160}{[(-49728\gamma + 15200)y + 15540
 \gamma + 94706](2 + y)(1 + y)}.$$
It is easy to prove that $g(y) > 0$ for all $0 < y < 1$.
Thus, we have $f'(5/16) = 0$, and $f'(y) < 0$ for all $y\in (0, 5/16)$, and
$f'(y) > 0$ for all $y\in (5/16, 1)$.
Thus, for all $0 < y < 1$,
$$f(y) \ge f(5/16) > 0.$$
We are done.


Visual Studio Entity Data Wizard, Crashes when Trying to Connect to Oracle

Question: I am running VS 2017,  ver 15.7.3  I have installed the Nuget Packages for Oracle,   Oracle.ManagedDataAccess and Oracle.ManagedDataAccess.EntityFramework.

I have my TNS file Configured to the proper Oracle Connection.  But When I open up the Entity Data Model Wizard, Select -> ADO.Net Entity Data Model Click ADD

Code First From Database  --> Click Next... . It just crashes out.  No Error... Nothing.  The Window just Closes

Some times it gets to the next screen and it lets me select the Oracle datasource and enter the proper credentials, but when I hit Next on that screen it just crashes out again.. I can never get past it?  Does anyone have a work around.  I'm sure I could create the Connection and the Entities Manually but there are just too many to for that approach to be practical.
Comment: Your `Oracle.ManagedDataAccess.EntityFramework` seems out of date. Have you tried updating it?
Answer: I managed to solve the same problem by:

use Entity Framework Version 5.0 with Oracle.ManagedDataAccess
v18.3.0
delete your connection from web.Config
from Server Explorer window, remove all connections

Now, you can add your entity model through the ADO.Net Entity Data Model wizard.
In my case, Oracle.ManagedDataAccess.EntityFramework wasn't needed.
Comment: The issue sound to  be from Oracle, as for providing a driver compatible to specific EF version.
Comment: but why it does not work with latest version of the packages?


Detail in the proof of $\mathbb{R}^n$ is a division algebra only for $n=1,2,4,8$

Question: One of the consequences of the Hopf invariant one problem is that $\mathbb{R}^n$ is a division algebra only for $n=1,2,4,8$. A division algebra structure $\odot$ on $\mathbb{R}^n$ need not play nicely with the norm: we could have $|x \odot y| \neq |x| |y|$. However, in the proofs I've read (for instance in Hatcher's notes), it seems to be taken for granted that the division algebra plays nicely with the norm.
Is there a way to lose this assumption?
Comment: Where does Hatcher use the assumption that $|xy| = |x|\,|y|$? He's not putting any restriction on the $H$-space multiplication map $\mu(x, y) = xy/|xy|$ beyond $\mu(x, 1), \mu(1, x) = x$.
Comment: There is more than one classification theorem concerning real division algebras. As Dietrich mentions, Hurwitz's theorem is *about* normed division algebras. On the other hand, it is a also theorem that the only division algebras occur with dimension $1,2,4,8$ with no assumption of a norm. Sources that prove that claim *do not* assume a norm. You should have no issue finding more of these sources - you even link to one, Hatcher! One issue is that some sources may hastily present what is essentially Hurwitz's theorem without mentioning the norm in the theorem statement.
Answer: The proof presented in Hatcher's notes makes no assumption that $|x\odot y|=|x||y|$.  Given any division algebra structure $\odot$ on $\mathbb{R}^n$, you get an H-space structure on $S^{n-1}$ defined by $(x,y)\mapsto \frac{x\odot y}{|x\odot y|}$.  That is, you can always just rescale the multiplication so that it preserves the norm, and that will give you an H-space structure on $S^{n-1}$ (though it may no longer give a division algebra structure since multiplication may no longer be bilinear).
Answer: Indeed, Hurwitz Theorem only holds under the assumption that $\|x\cdot y\|=\|x\|\|y\|$ for all $x,y\in A$, i.e., for composition algebras.
Theorem(Hurwitz 1898): Suppose that $A$ is a real finite-dimensional unital algebra, and suppose that $A$ is a Hilbert space with $\|x\cdot y\|=\|x\|\|y\|$ for all $x,y\in A$. Then $A$ is one of the division algebras $\mathbb{R},\mathbb{C},\mathbb{H},\mathbb{O}$.


Cubase Elements 7 - line in inputs not working

Question: Hi I have a macbook pro (2009) I have connected a synth to the line in input. Through the MacOS sound system preference I can select "line in" as the preferred input and can see that sound is getting in. So the connection to the mac seems to be ok.
I am new to Cubase Elements so I might the missing something but when I go to "devices" and to "device setup" I can set up built in mic etc , but "line in" is not an option shown to me.
As a result the input sound is coming through the built in mic, so will record me talking, but won't recognise the sound coming through the line in.
How do I set this up so that it will recognise the line in port?
Answer: Depending on which model, that machine may have a dual-purpose in/output.
Can you switch over the input, as here...?
http://support.apple.com/kb/ht3625

When you put a mini-stereo plug in the combination audio port, your computer will automatically detect the device and use the device as an analog output device.
If you want to set up the port as an audio input device, you can manually switch from using the port as an output device in the Sound pane of System Preferences. Follow these steps:
1 Plug the input audio device into the combination audio port using the proper adapter cable.
   2 From the Apple () menu, choose System Preferences.
   3 Choose Sound from the View menu.
   4 Click the Input tab.
   5 Change the "Use audio for:" menu selection from Sound Output to the Sound Input.
   6 The device type should change from "Internal Microphone/Built-in Input" to "Line In/Built-in Input."

Alternatively, theres a long discussion of various options on here -
https://discussions.apple.com/thread/4794480?start=15&tstart=0
All that said, long-term you'd be better off with a dedicated USB audio input/output device. I'm really not sure what kind of levels a mini-jack designed for a headset is going to take & a synth may be just too powerful.


Variance property

Question: I know that $$Var(X + Y) = Var(X) + Var(Y) + 2Cov(X,Y)$$
Now if I applied that same rule to $Var(\beta Y + (1-\beta)C)$ would we have $$Var(\beta Y + (1-\beta)C) = \beta^2 Var(Y) + (1-\beta)^{2}Var(C) + 2(1-\beta)Cov(Y,C)$$
I am not sure if this is correct any suggestions are appreciated.
Comment: The last term should be $ +2\beta (1-\beta)Cov(Y, C)$.
Comment: You need to define which symbols are parameters, and which are random variables.
Comment: The correct should be $$Var(\beta Y + (1-\beta)C) = \beta^2 Var(Y) + (1-\beta)^{2}Var(C) + 2\beta(1-\beta)Cov(Y,C)$$
Comment: It's always a good idea when you have derived a formula to test it for some simple cases where you know the answer. For example if $\beta = 1$ the left hand side is $\text{Var}(Y)$ which agrees with the right hand side. If $\beta = 0$ then the left hand side  is $\text{Var}(C)$ while the right hand side is $\text{Var}(C) + 2\text{Cov}(Y,C)$ so your formula cannot be correct.
Answer: As @Ramil pointed out in the comment section, the correct answer would be:
$$
Var(\beta Y + (1-\beta)C) = \beta^2Var(Y) + (1-\beta)^2Var(C) + 2\beta(1-\beta)Cov(Y, C)
$$
I just want to add a tip so that it's easier for you to expand the variance of a sum better in the future. Think of it as similar to the popular property:
$(a + b)^2 = a^2 + b^2 + 2ab$
and it should show you how to treat the constant in the variance case.
Answer: You need to check out the definition of variance and covariance; then it will be crystal clear.
However,
note that
$$
cov(\beta Y, (1-\beta)C) = E(\beta Y - E(\beta Y))((1-\beta)C - E((1-\beta)C)) = \beta(1-\beta)cov(Y,C).
$$

Variance property


NSDateFormatter not working with 4:15:00 PM

Question: How do I convert "4:15:00 PM" to an NSDate? Below is the code I have:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm:ss aa"];
NSDate *date =  [df dateFromString:@"4:15:00 PM"];

NSLog(@"date: %@",date);//outputs: 1970-01-01 17:15:00 +0000
//should output: 1970-01-01 16:15:00 +0000

UPDATE: I updated based on responses and I am still having the incorrect show:
NSLog(@"date: %@",[df stringFromDate:date]);//outputs: 12:15:00 PM
//should output: 4:15:00 PM

The question is why does the time change from 4:15:00 PM 12:15:00 PM.
Comment: NSLog of an NSDate displays in UTC.
Comment: And be aware of the [12/24 gotcha](http://stackoverflow.com/q/6613110/581994).
Answer: Actually, this is correct.
However, the debugger and NSLog display the time in GMT.
If you want to display local time, use a NSDateFormatter and stringFromDate.
Update:
Your date formatter format is also set incorrectly.
It should be:  [df setDateFormat:@"hh:mm:ss aa"]; since you are using a 12 hour clock.
Comment: Umm, it is outputting the correct time now.  Just change the format if you want it to display differently.
Answer: This is because of your locale.
NSDateFormatter outputs a NSDate - which is always in GMT time.
If you want your initial string interpreted as GMT time then you need to include the timezone.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm:ss aa z"];
NSDate *date =  [df dateFromString:@"4:15:00 PM GMT"];

Comment: Can I do this without having to change to append GMT to the input string?
Comment: If you don't put GMT then it is going to use your locale's timezone
Comment: If its defaulting then why do I have the issue where the time changes from "4:15:00 PM" to "12:15:00 PM"
Comment: Those are the same raw NSDate. It *looks* like it is changing because '4:15:00 PM', unless otherwise stated, is assumed to be in your current locales timezone. Where as NSDate is always stored in GMT time, so it does a timezone conversion *to* GMT time when you use `dateFromString`.


How to rank data based on cross-validation

Question: I had this problem from a long time. I have small dataset with about 1000 data points. The data is labeled as 1 or 0 (i.e. binary classification). In other words if the product is defective it is marked as 1 and 0 otherwise.
The features of the data are the product properties (such as height, width etc.). Since my dataset is very small, I initially performed 10 fold cross-validation to perform my classification. Now that my classification part is done, I encountered another problem.
The problem is to rank the most defective products first (i.e. a priortised list where the top contains the most defected items, so that the actions can be taken in that order).
I want to use my same features to do the ranking. For this purpose, I am considering the prediction probability of class 1 of each data point when it is in testing fold of 10-fold cross validation (i.e. using predict_proba in sklearn python). Then I sort all the 1000 data points based on this probability to get a priortised ranking list.
My concern is whether what I am doing is correct? If not, what are the other options that I can try?
Answer: Your approach is not wrong, though I would suggest a different interpretation. Those cases with higher probability values are 'more likely to be defective, given the data' rather than those cases are 'most defective'. It is binary classification after all, and your training data either was or was not defective.
Comment: In binary classification there is no concept of 'most defective' just 'most likely to be' defective. To get what you want would require that your training data include a real-valued assessment of 'amount of failure' first, then you wouldn't use binary classification but one that outputs real valued predictions
Comment: You probably do not want to recode to 1/0 then. Your cut point is arbitrary and you throw away information. You'll want to start trying some regression based techniques, and you'll likely need to transform your y variable as percentages behave differently. Then your model will output amount of defect.
Comment: thank you for the great answer. Do you have any suggestions to identify the most defective items? :)
Comment: That is a great suggestion. I do have a percentage value for each data point that denotes how much it was defected. Like 80%, 90% or 0% etc. I did the labelling of `0` and `1` based on this. Since, I am having these percentage values, how can I use them to rank the predictions? Looking forward to hearing from you :)
Comment: Thanks a lot. It is good to know that what I did previously was right. I will try the regression model :)
Comment: I have one more question. What would be your suggestion in transforming y values? Did you mean some thing like 100%  to 1.0, 99% to 0.99? :)


Statistical analysis of nonlinear equation

Question: I have the following equation:
$C_i = \frac{EF_eS_i\delta_wW_j(\frac{t_i}{t_j})^m(\frac{v_i}{v_j})^n\alpha_w\gamma_f}{dwtD_i}$
where $S_i = S_{base}(.455L_i^2-.710L_i+1.280)$
And $L_i = \frac{v_i}{v_j}$
This is a simplified description of a ship's ($i$) carbon intensity for each hour at sea during a voyage. I have data to compute the equation and know what exponents $m$ and $n$ are with n described as a cubic, but I want to understand the influence of each factor on the carbon intensity. The only variables that change each hour in this equation are $v_i, S_i, D_i$. I have a panel dataset of ships (hourly, per voyage and ship). Aside from plotting each explanatory variable against $C_i$ and looking at r-squared, can this equation be transformed using a log-log specification and then perform statistical regression?
Answer: Probably yes. Various software packages offer you the option for bespoke non-linear models e.g. in SAS you have PROC NLMIXED (frequentist estimation) or in R you have things like brms (Bayesian models) (there's also nlme). Key considerations would be parameterization (e.g. do you put some quantities that can only ever be positive on a log-scale and then put exp(quantity) in where needed?), numerical stability (some things might be more stable on a log-scale or with certain in-built stable functions) and whether there should be random effects (and on what - e.g. is there a random ship effect on the intercept or perhaps do other parameters vary between ships?).
Comment: Thanks. Just to clarify, this is not a typical stats estimation as I do not observe C (dependent variable) from real data. It is a mathematical function to estimate C. In the real world, we would observe the numerator (fuel consumption) and denominator (distance times size) which make up C and could then perform stats regression with fixed effects. The motivation here is only to decompose the equation to understand the contribution of each factor.


How can I pass an implementation of "IStorageItem" to DataPackage.SetStorageItems(items) and don't get an InvalidCastException raised on UWP?

Question: I'm developing a UWP application which shall be able to share its files. I followed the documentation from Microsoft and the solution worked pretty well.
Here is my implementation:
public void ShareLocalFile(LocalFileToShare file)
{
    DataTransferManager.GetForCurrentView().DataRequested += async (sender, args) =>
    {
        var deferral = args.Request.GetDeferral();

        try
        {
            var storageFile = await StorageFile.GetFileFromPathAsync(file.FilePath).AsTask();

            args.Request.Data.SetStorageItems(new[] { storageFile });
        }
        finally
        {
            deferral.Complete();
        }
    };

    DataTransferManager.ShowShareUI();
}

However, the app stores all files with not human-readable names which makes users be uneasy with the sharing.
So, I wanted to share a file with an alternative name without actually renaming it on the file system because files are opened in a third-party reader. In addition, the files are quite big and copying them with new names is not a good choice.
Firstly I thought that I could make a symbolic link but it's only possible with Administrator rights
Then I looked at the signature of "void DataPackage.SetStorageItems(IEnumerable value)" method and guessed that it's probably possible to pass there my own implementation of IStorageItem what I did:
public class StorageItemWithAlternativeName : IStorageItem
{
    private readonly IStorageItem storageItem;

    public StorageItemWithAlternativeName(IStorageItem storageItem, string alternativeItemName)
    {
        this.storageItem = storageItem;
        Name = alternativeItemName;
    }

    public string Name { get; }

    // the interface implementation omitted for briefness but it simply delegates all actions to the decorated storageItem
}

public static class LocalFileToShareExtensions
{
    public static async Task<IStorageItem> GetStorageItem(this LocalFileToShare file)
    {
        var storageFile = await StorageFile.GetFileFromPathAsync(file.FilePath).AsTask();

        if (!string.IsNullOrWhiteSpace(file.AlternativeFileName))
        {
            storageFile = new StorageItemWithAlternativeName(storageFile, file.AlternativeFileName);
        }

        return storageFile;
    }
}

And here I failed. The error is quite silly - SetStorageItems method throws an InvalidCastException:
"No such interface supported.
The collection contains item(s) that can't be converted to read-only form."
I investigated the windows event log and found the following entry:
Faulting application name: [MyApp].Windows.exe, version: 188.8.131.52, time stamp:    0x5bb69bfe
Faulting module name: combase.dll, version: 10.0.17763.253, time stamp: 0xa3f81b2d
Exception code: 0xc000027b
Fault offset: 0x00209931
Faulting process id: 0x4ee4
Faulting application start time: 0x01d4be3ccca1f00f
Faulting application path: [PathToMyApp].Windows.exe
Faulting module path: C:\WINDOWS\System32\combase.dll
Report Id: 35999df1-6b4f-4675-a821-a84e6ea0cfb4
Faulting package full name: [MyAppPackageName]
Faulting package-relative application ID: App

It seems that the DataPackage object communicates with COM so I also tried [assembly: [ComVisible(true)] attribute on my assembly but I did not succeed.
The question is how can I kind of dumb the system and share a file with a different name? Is it possible to pass my own implementations to UWP SDK methods? Because now it violates the Liskov substitution principle.
I will appreciate any help with this!
Comment: IStorageItem exists so that both StorageFolder and StorageFile can implement it. But you are not allowed to implement it in your custom classes. What you want is StorageFile.CreateStreamedFileAsync. This lets you create virtual files.
Answer: Please try to use the overloaded method SetStorageItems with parameter readOnly:false, something like this:
args.Request.Data.SetStorageItems(new[] { storageFile }, false);

Comment: Thank you, @Alexander!

It worked with a little trick. I also had to implement all interfaces from `StorageFile`:

`class StorageFileWithAlternativeName : IStorageFile, IStorageItemProperties2, IStorageItem2, IStorageItemPropertiesWithProvider, IStorageFilePropertiesWithAvailability, IStorageFile2`

I guess some of them are unnecessary but if only `IStorageItem` interface is implemented then a file cannot be attached to an email in MailClient.

**P.S.** _Skype_ crashes with this approach although I am ok with this since I only need MailClient working properly.
Comment: Cool, @GennadiySakhnyuk,!


Ic V I - can somebody explain?

Question: Could somebody explain what this is?
Where does the 'c' come from, and what does it mean?
Thanks!
Comment: More context, please?
Answer: British (maybe other places too, I hope so!) chord notation.    a,b,c = Root position, 1st Inversion, 2nd Inversion.  So Ic, V, I is the common I64, V, I cadence.
A neat, compact system.  V7d is a 'last inversion' dominant 7th, C7/Bb.  It should be used more.
Comment: @gidds, some people write the tonic cadential 6/4 chord with a Roman numeral `V` to show the ^5 scale degree is in the bass, and the 6/4 above is considered a double appoggiatura. That's more or less a figured bass approach. `I6/4`, which is the more 'modern' way, shows `I` to mean the chord root, not bass note, is the `^1` scale degree, the 6/4 is then read to mean "second inversion." Using the older style `V6/4` logic `I/64` would indeed be a second inversion `IV`, but I've only seen this particular use for cadential `V6/4`.
Comment: Wouldn't I⁶⁴ be second inversion IV? If so, the cadence could be written V⁶⁴ V I.
Comment: And Ic  would be shorter and completely unambiguous!

Ic V I - can somebody explain?


tar of pg_dump huge await. Do additional writes to a luks encrypted disk require additional entropy?

Question: We have a postgres server with 6 SSDs in a raid10. backing up the postgres database with pg_dump works fine and causes almost 0 load to the disks or cpu. Tar'ing said pg_dump without any options other than -vcf seems to cause so much disk IO that queries start to timeout for a brief moment (5 minutes)
I'm trying to troubleshoot why this would be as pg_dump doesn't do this and tar should be similar to cat'ing the files together. Does writing to a luks encrypted disk require additional entropy? I thought it was entirely the key/passphrase?
Comment: No, they don't require additional entropy. The true randomness construction part happens only in the key generation, using the keys doesn't require anything only computing power (and writing the things requires disk IO). Check what is in the top during this 5 minutes, it is obviously extraordinary, but may have some specific reason. Also strace the tar.
Comment: Thank you @peterh! I wasn't sure about the entropy but suspected it did not. Thanks for the confirmation!
Answer: It seems that it has been fixed in kernels >= 4.0.2.
There is a deep analysis of this problem in Abysmal general dm-crypt (LUKS) write performance


db_select query for given sql query with equi join

Question: I'm trying to do a equi join but it isn't working.
I have 2 tables:
Table 1 - taxonomy_term_data with fields "tid,vid,name,description,format,weight etc"
Table -2 -taxonomy_term_hierarchy with fields "tid and parent"
I have sql query with me it is working fine. This is the query "select t1. *,t2.vid,t2.name from taxonomy_term_hierarchy t1, taxonomy_term_data t2 where t1.tid = t2.tid AND vid=2 limit 5;"
I just want to get tid,name,vid from taxonomy_term_data table and parent from taxonomy_hierarchy table in db_select query format
Answer: You can built any type of select query using db_select, you can see in detail on following url
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7.x
Answer: You can change query based on you requirement.
<code>$query = db_select('taxonomy_term_hierarchy', 't1');
    $query->join('taxonomy_term_data', 't2', 't1.tid = t2.tid');
    $result = $query
      ->fields('t1', array('tid', 'field1', 'field2'))
      ->fields('t2', array('tid', 'vid', 'name'))
      ->condition('t2.vid', '2')
      ->range(0,5);
      ->execute();

    foreach ($result as $row) {
      // Do something with $row.
    }
</code>


binomial distibution in r, cannot replicate correct answer

Question: I'm given a problem:
An event occurs with probability 0.7. Over the course of 10,000 events the event occurred only 55 times.
Verbatim question

What is the probability that you would observe at most that many events, if the probability of each click was 0.7%?

The solution provided is 0.0372.
In r I typed pbinom(55, 10000, 0.7) which returns just 0.
How can I arrive at 0.0372?
Comment: 0.7% = 0.007... If probability of observing something is 70%, then observing it only 55 times in 10000 trials sounds pretty impossible.
Answer: In R...
p = 0.7/100
N = 10000
pbinom(55,N,p)
>[1] 0.03720226

Looks like you have an error in your call to pbinom.  If there is a 0.7% chance of an event occuring, then p=0.7/100 not p = 0.7.


How can I figure out ORA-00900 invalid SQL statement in datagrip

Question: Normally, using show errors can solve this problem in SQL*PLUS.
However executing show errors in datagrip will show Nothing to run, and executing a procedure which has invalid SQL statement only shows error invalid SQL statement.
So I can't figure out what's wrong with my procedure.
BTW I'm using macOS so configuring Oracle environment in Windows is a little troublesome.
Thanks for helping.
Comment: Perhaps you may try to run "/rdbms/admin/utlrp.sql" by connecting sqlplus as admin To see invalid statements or objects
Comment: Which version of Oracle database are you using?
Answer: show errors is a SQL*Plus command, not a SQL statement. Even IDEs dedicated to Oracle (e.g. PLSQL Developer) don't recognise it in their SQL Worksheets, so it's not surprising that a generic database IDE hurls. Maybe DataGrip has the option to associate a command line executable for running scripts?
show errors is just a wrapper for a query on the data_dictionary. You can execute this for yourself in any SQL environment:
 select e.line, e.position, e.text
 from user_errors e
 where e.name = 'YOUR_PROCEDURE'
 order by e.sequence;

The data dictionary view has other attributes you may want to use. Find out more.


Replace text with link in contenteditable

Question: I'm trying to implement an identification system like on facebook in my Angular 6 application. When a user write a comment(in a contenteditable div), he can press '@' key and then the name of the person he want to identify.
here is the html part:

{{user.firtName}} {{user.lastName}}

Here is the angular part:
selectUserSugg(user: any){
    console.log(user);
}

For now I'm able to read the name after the '@' key and send the request to find  the users that match.
Here is an example:

When user click on "John Lennon" I would like to replace "@John" by John Lennon
How to manage this ?
Comment: may be using `innerHTML`, but it would be great if you show some code to us
Comment: @PardeepJain I have updated my question
Comment: can you create small stackblitz?
Answer: You have to bind a variable to "innerHTML", so that when selectUserSugg(user) function is called, it will append your desired output in "comments" variable.

The variable "comments" should be defined in your .ts file.
[innerHTML] will allow template to render HTML code from your variable.
This will solve your problem of having comment section with "content" and "link to user" both.
And for replacing "@John" by link, you can parse "comments" variable and use regex.


Squid reverse proxy - load balance to two web servers with connection persistence

Question: I want to setup a Squid reverse proxy that splits HTTP traffic to two web servers for load balancing, and have it use persistence (so if a user gets to webserver1 with a first request their second request goes to webserver1 also.)
Other reverse proxy solutions I've worked with have done this by injecting a session cookie into the HTTP stream; how can I do this using squid?
Answer: Squid is not a good load balancer. It just doesn't have the necessary functionality. Use (or persuade the decision makers) HAProxy.
Answer: Say your servers are at 10.0.0.51 and 10.0.0.52.  You'll want something like this:
<code>cache_peer 10.0.0.51 parent 80 0 no-query originserver sourcehash
cache_peer 10.0.0.52 parent 80 0 no-query originserver sourcehash
</code>
It'll do a hash of the client's IP address and direct a given client to the same upstream server with each request (as long as the upstream servers stay up) based on that.
Comment: Two problems with this: 1. (Not a biggie) Large organizations that NAT to a single IP outside will end up on the same web server; 2. (More serious) Clients that change IPs during a single session will break.
Comment: @ynguldyn Yup, cookie-based routing is more reliable and provides more consistently balanced client distribution, but I don't believe that it's supported by Squid?  Depending on the application and the target users, this may work just fine for his needs.  IP hashing is the best recommendation that I've got when the scope is limited to Squid.


Qual a diferença entre "NULL", "\0" e 0?

Question: Ambos valem zero. Posso usar os 3 intercambiavelmente sempre?
Answer: Todos os 3 são literais constantes que valem 0, isso está correto.
0
0 é um valor numérico e pode ser usado sempre que precisa do número zero mesmo. Em alguns lugares ele acaba sendo usado para outras coisas. Onde se espera um resultado booleano o 0 é considerado falso, enquanto qualquer outro valor é considerado verdadeiro.
\0
Esse é o caractere nulo. Os compiladores costumam definir uma macro chamada NUL com este valor, que pode inclusive ter mais que um byte.
Realmente não deixa de ser um 0 e ele geralmente pode ser usado onde se espera um zero. A barra é usada como escape para definir que deseja o byte de valor zero ali e não o caractere 0, que é algo bem diferente do caractere 0 (é o byte 48). Então essa forma só é usada dentro de um literal caractere ou string. Esse caractere é o terminador de string. Isto é importante já que C não guarda o tamanho da string de forma padronizada.
No caso do char é possível usar apenas o 0 mesmo, desde que não use as aspas simples *nem todos compiladores em algumas opções ligadas aceitam). Lembre-se que o tipo char é um tipo numérico como outro qualquer. Por acaso ele pode ser usado para imprimir caracteres, mas é apenas uma representação diferente. Computadores só entendem números, o resto é representação.
NULL
Esse é apenas um #define com um valor zerado. De fato há algumas implementações que o valor é 0 mesmo. Mas é mais comum o valor (void *)0, deixando claro que na verdade esse é um ponteiro para o endereço zero da memória, portanto um ponteiro nulo.
Um 0 não é tão intercambiável assim. Se tentar comparar um NULL, ou seja void * com 0 até funciona porque ele faz um cast automático. Mas se tentar comparar um NULL com um inteiro não acontecerá o que espera. Na verdade é gerado um warning e é possível que o compilador nem deixe finalizar.
Um código demonstrando tudo isso:
#include <stdio.h>

int main(void) {
    int i = 0;
    char c = 0;
    char *s = "teste";
    void *p = NULL;
    printf("%d %c %s %p\n", i, c, s, p);
    if (!c) printf("i ok\n"); //verifica se não é zero
    if (!c) printf("c ok\n"); //verifica se não é um caractere nulo
    if (!s[5]) printf("s ok\n"); //verifica se o 6o. caractere é o terminador
    if (!p) printf("p ok\n"); //verifica se o ponteiro não é nulo
//  if (p == i) printf("p NULL ok\n"); //tipos incompatíveis sendo comparados
    printf("%zu", sizeof('x'));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Queria fazer uma adenda á resposta do @Maniero.
O Standard C nao obriga que NULL seja definido com os bits todos a 0.

§184.108.40.206
...
2 The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero.255)
...
255) Note that this need not be the same as the representation of floating-point zero or a null pointer
  constant.

Tradução:

§126.96.36.199
...
2 A função calloc aloca espaço para um array de nmemb objetos, cada um com tamanho size. O espaço é inicializado com bits a 0.255)
...
255) Note que esta não tem que ser a mesma representação do 0 em representação flutuante, ou a constante de ponteiro nulo.
Comment: Muito bom complemento. Eu sempre espero por respostas assim ou mesmo completas para que eu possa aceitar.
Comment: Muito bom mesmo.


Simple repeated measures ANOVA in R

Question: I am struggling a bit in the implementation and interpretation of repeated-measures ANOVA in R. Lots of tutorials are available, but most of the time they deal with rather complicated schemes, thus after several hours of reading I am more confused than ever.
We have subjects, for which we measured a certain parameter (measured value) a 3 consecutive time points. My data looks like this:
Subject  Time  Measured.Value
   A       1          5
   A       2          7
   A       3          9
   B       1          6
   B       2          4
   B       3          8
   C       1          3
   C       2          5
   C       3          6

I want to assess if the measured values are significantly different between time points. I used the following function in R:
my.data$Subject <- factor(my.data$Subject)
my.data$Time <- factor(my.data$Time)
my.aov <- with(my.data, aov(Measured.Value ~ Time + Error(Time)))
summary(my.aov)

I am doing this right?
Answer: Your error term is not quite correct.
Assuming you've got a balanced design, the repeated measures ANOVA model using aov is
aov(Measured.Value ~ Time + Error(Subject/Time), data = my.data)

The term Error(Subject/Time) models the subject-specific variance; or in the language of mixed-effect models: Subject is your random and Time your fixed effect, and Time is nested (i.e. repeatedly measured) within Subject.
Two more comments:

Keep in mind that aov only allows for random effects if the design is balanced (which is the case for the sample data you provide). If you've got an unbalanced design (e.g. due to missing observations), you will need to use a mixed-effect model.
It's a bit odd to use ANOVA to model a time dependence. I am assuming here that Time is a categorical variable.
Comment: Thanks! I see the error and I will correct that in my model. Time is indeed a categorical variable: subjects have been sampled at 2 time points each, and the time points are the same for all subjects.

Simple repeated measures ANOVA in R


forward subset selection in R without intercept

Question: Hey so I am developing a multiple regression model and using the forward subset selection method to reduce the number of parameters and using "mallows Cp" as a selection criterion. However this is an engineering problem and it does not make sense to have an intercept,, i.e. when all the predictors are zero, the prediction will be 0. Hence I want to remove the intercept from my regression equation. I know that in case of just regression a "lm(y~x+z-1)" will do , however this does not seem to work with my code.
#Fitting Using Model Selection
library(leaps)
a.fit<- regsubsets(ROP~.-1,data=dat1,nvmax=10)
summary(a.fit)
plot(summary(a.fit)$cp,xlab="No. of variables", ylab="Cp")
which.min((summary(a.fit)$cp))
plot(a.fit,scale="Cp")
coef(a.fit,6)

##Forward Stepwise Selection
f.fit<- regsubsets(ROP~.,data=dat1)
summary(f.fit)
plot(summary(f.fit)$cp,xlab="No. of variables", ylab="Cp")
which.min((summary(f.fit)$cp))
plot(f.fit,scale="Cp")
coef(f.fit,5)

Answer: I haven't used regsubsets() before, but the way I see it you can simply set the intercept parameter to FALSE, check ?regsubsets. Example:
data(swiss)
a.fit <- regsubsets(Fertility ~ ., data = swiss, nvmax = 10,  intercept = F)
minimum <- which.min((summary(a.fit)$cp)) # 4

coef(a.fit, minimum)
     Agriculture        Education         Catholic Infant.Mortality
      0.11714390      -0.44750066       0.07508021       3.27420789


How to calculate $\int_{-\infty}^{+\infty} \frac{x \sin x}{x^2+4x+20}\, dx$?

Question: I get the answer that it equals $\frac{\pi(2\cos2+\sin2)}{2e^4}$ by mathematica.
But I don't know how it can equal this form.
My idea is to construct equations so that problems can be transformed.Like these:
$$\int_{-\infty}^{+\infty} \frac{x \sin x}{x^2+4x+20}\, dx=\int_{-\infty}^{+\infty} \frac{(y+4) \sin (y+4)}{y^2+4y+20}\, dy$$
$$\int_{-\infty}^{+\infty} \frac{x \cos x}{x^2+4x+20}\, dx=-\int_{-\infty}^{+\infty} \frac{(y+4) \cos (y+4)}{y^2+4y+20}\, dy$$
So only by calculating $\int_{-\infty}^{+\infty} \frac{ \sin x}{x^2+4x+20}\, dx$ and $\int_{-\infty}^{+\infty} \frac{ \cos x}{x^2+4x+20}\, dx$ then we can get the values of $\int_{-\infty}^{+\infty} \frac{x \sin x}{x^2+4x+20}\, dx$ and $\int_{-\infty}^{+\infty} \frac{x \cos x}{x^2+4x+20}\, dx$.
What's more I found that
$$\int_{-\infty}^{+\infty} \frac{ \sin x}{x^2+4x+20}\, dx=- \frac{\pi \sin 2}{4e^4}$$
$$\int_{-\infty}^{+\infty} \frac{ \cos x}{x^2+4x+20}\, dx= \frac{\pi \cos 2}{4e^4}$$
So I guess I can solve the problem only by calculating
$$\int_{-\infty}^{+\infty} \frac{ \sin x}{x^2+ c}\, dx$$ and
$$\int_{-\infty}^{+\infty} \frac{ \cos x}{x^2+ c}\, dx$$
Can you help me?
Comment: Do you know residue calculus?
Comment: @MisterRiemann sorry I didn't know that
Comment: What can we say about $c$ in terms of being positive or negative?
Answer: An Alternative approach. Employ a combination of Feynman's Trick and Laplace Transforms.
Here let:
$$I(t) = \int_{-\infty}^{\infty} \frac{x\sin(xt)}{x^2 + 4x + 20}\:dx$$
Take the Laplace Transform w.r.t '$t$':
\begin{align}
\mathscr{L}\left[I(t)\right] &= \int_{-\infty}^{\infty} \frac{x\mathscr{L}\left[\sin(xt)\right]}{x^2 + 4x + 20}\:dx \\
&= \int_{-\infty}^{\infty} \frac{x}{x^2 + 4x + 20}\frac{x}{x^2 + s^2}\:dx = \int_{-\infty}^{\infty} \frac{x^2}{\left(x^2 + 4x + 20\right)\left(x^2 + s^2\right)}\:dx \\
&= \frac{1}{s^4 - 24s^2 + 400}\int_{-\infty}^{\infty}\left[\frac{s^4 - 20s^2}{x^2 + s^2} + \frac{4s^2x}{x^2 + s^2} - \frac{4\left( 5s^2 - 100\right)}{x^2 + 4x + 20} - \frac{4s^2x}{x^2 + 4x + 20} \right]dx \\
&=\frac{1}{s^4 - 24s^2 + 400}\left[ \underbrace{\int_{-\infty}^{\infty}\frac{s^4 - 20s^2}{x^2 + s^2}\:dx}_{(1)} + \underbrace{\int_{-\infty}^{\infty}\frac{4s^2x}{x^2 + s^2}\:dx}_{(2)} - \underbrace{\int_{-\infty}^{\infty}\frac{4\left( 5s^2 - 100\right)}{x^2 + 4x + 20}\:dx}_{(3)} - \underbrace{\int_{-\infty}^{\infty}\frac{4s^2x}{x^2 + 4x + 20}\:dx}_{(4)}\right]
\end{align}
We can now evaluate each individually
For (1):
$$\int_{-\infty}^{\infty}\frac{s^4 - 20s^2}{x^2 + s^2}\:dx = \left(s^4 - 20s^2\right)\left[\frac{\arctan\left(\frac{x}{s} \right)}{s}\right]_{-\infty}^{\infty} =  \left(s^4 - 20s^2\right)\frac{\pi}{s} = \left(s^3 - 20s\right)\pi$$
For (2)
$$\int_{-\infty}^{\infty}\frac{4s^2x}{x^2 + s^2}\:dx = 0$$
For (3)
\begin{align}
\int_{-\infty}^{\infty}\frac{4\left( 5s^2 - 100\right)}{x^2 + 4x + 20}\:dx &= \int_{-\infty}^{\infty}\frac{4\left( 5s^2 - 100\right)}{\left(x + 2\right)^2 + 4^2}\:dx =\int_{-\infty}^{\infty}\frac{4\left( 5s^2 - 100\right)}{x^2 + 4^2}\:dx \\
&= 4\left( 5s^2 - 100\right)\left[\frac{\arctan\left(\frac{x}{4} \right)}{4}\right]_{-\infty}^{\infty} =4\left( 5s^2 - 100\right)\frac{\pi}{4}\\
&= \left( 5s^2 - 100\right)\pi
\end{align}
For (4)
\begin{align}
\int_{-\infty}^{\infty}\frac{4s^2x}{x^2 + 4x + 20} &= \int_{-\infty}^{\infty}\frac{4s^2x}{\left(x + 2\right)^2 + 4^2} \:dx = \int_{-\infty}^{\infty}\frac{4s^2\left(x - 2\right)}{x^2 + 4^2} \:dx \\
 &= \int_{-\infty}^{\infty}\frac{4s^2x}{x^2 + 4^2} \:dx -  \int_{-\infty}^{\infty}\frac{8s^2}{x^2 + 4^2}\:dx \\
&= 2s^2\cdot 0 - 8s^2\left[\frac{\arctan\left(\frac{x}{4} \right)}{4}\right]_{-\infty}^{\infty} \\
&= - 8s^2\cdot\frac{\pi}{4} = -2s^2\pi
\end{align}
Thus, in combining we have:
\begin{align}
 \mathscr{L}\left[I(t)\right] &=  \frac{1}{s^4 - 24s^2 + 200}\left[\left(s^3 - 20s\right)\pi + 0 - \left( 5s^2 - 100\right)\pi - -2s^2\pi\right] \\
&= \frac{\left(s^3 - 3s^2 - 20s + 100 \right)}{s^4 - 24s^2 + 400}\pi
\end{align}
We now take the inverse Laplace Transform
\begin{align}
 I(t) &= \mathscr{L}^{-1}\left[\frac{s^3 - 3s^2 - 20s + 100 }{s^4 - 24s^2 + 400}\pi \right] \\
 &= \frac{1}{4}e^{-2\left(2 + i \right)t}\left(\left(2 - i\right)e^{4it} + (2 + i) \right)\pi
\end{align}
Hence
\begin{align}
I = I(1) &= \frac{1}{4}e^{-2\left(2 + i \right)}\left(\left(2 - i\right)e^{4i} + (2 + i) \right) \\
&= \left(\sin(2) + 2\cos(2)\right)\frac{\pi}{2e^4}
\end{align}
Answer: As you've already noted, the substitution $y=x-2$ gives$$\int_{\mathbb{R}}\frac{x\sin xdx}{x^{2}+4x+20} =2C_{0}\sin 2-2S_{0}\cos 2+S_{1}\cos 2-C_{1}\sin 2$$with $$C_{n}:=\int_{\mathbb{R}}\frac{y^{n}\cos ydy}{y^{2}+16},\,S_{n}:=\int_{\mathbb{R}}\frac{y^{n}\sin ydy}{y^{2}+16},$$i.e. $$C_{n}+iS_{n}=\int_{\mathbb{R}}\frac{\exp iydy}{y^{2}+16}.$$The characteristic function of the Cauchy distribution is$$\int_{\mathbb{R}}\frac{\gamma}{\pi}\frac{\exp itydy}{\left(y-y_{0}\right)^{2}+\gamma^{2}}=\exp\left(iy_{0}t-\gamma\left|t\right|\right),$$so in particular$$\int_{\mathbb{R}}\frac{\exp itydy}{y^{2}+16}=\frac{\pi}{4}\exp-4\left|t\right|.$$Differentiating with respect to t,$$\int_{\mathbb{R}}\frac{y\exp itydy}{y^{2}+16}=\pi i\operatorname{sgn}t\exp-4\left|t\right|.$$Hence$$C_{0}+iS_{0}=\frac{\pi}{4e^{4}},\,C_{1}+iS_{1}=\frac{\pi i}{e^{4}}\implies C_{1}=S_{0}=0,\,C_{0}=\frac{\pi}{4e^{4}},\,S_{1}=\frac{\pi}{e^{4}}.$$Finally,$$\int_{\mathbb{R}}\frac{x\sin xdx}{x^{2}+4x+20}=\frac{\pi}{2e^{4}}\left(2\cos2+\sin2\right).$$


Como criar um PDF usando iText para Android

Question: Eu estava tentando criar um arquivo pdf em minha aplicação Android, como não encontrava nada que funcionasse, hoje consegui resolver o problema por conta própria. Segue o código a quem interessar.
Aqui estão os imports correspondentes ao iText.jar
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

Aqui o código funcionando perfeitamente
private void criandoPdf() {

    try {

         String filename = "teste.pdf";

        document = new Document(PageSize.A4);

        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/MeuPdf";

        File dir = new File(path, filename);
        if (!dir.exists()) {
            dir.getParentFile().mkdirs();
        }

        FileOutputStream fOut = new FileOutputStream(dir);
        fOut.flush();

        PdfWriter.getInstance(document, fOut);
        document.open();
        document.add(new Paragraph("Aqui esta meu pdf"));

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        document.close();
    }

}

Se alguém souber trabalhar bem com o iText, sinta-se a vontade para postar um bom link para implementação de funcionalidades mais avançadas tais como, inserir bordas e linhas. Não é uma pergunta, apenas poste qualquer coisa relevante, apenas para agregar e ajudar quem estiver tentando o mesmo.
Answer: Veja o gist que criei abaixo, talvez ainda possa ser útil para você.
pdf
Comment: Obrigado amigo, é muito útil sim. Segue aqui um link com algumas funções básicas a quem precisar criar uma tabela. http://itextpdf.com/themes/keyword.php?id=152
Answer: Alguém sabe como criar um PDF que espelha um Holerite(Contracheque)?
Eu estava imaginando em 2 opções:
A primeira é criando um XML que representa todo o layout do contracheque, assim me facilitaria na inserção dos campos e a organização.
A segunda é através de um imagem, e colocaria as informações conforme as margens de alinhamento.
No meu ponto de visão a primeira seria a mais viável, alguém poderia me dar um Norte para eu prosseguir?
Comment: Yuri, Bem vindo ao SOpt, antes de começar de uma olhada em nosso [Tour](https://pt.stackoverflow.com/tour)  O local onde você publicou sua pergunta é apenas para respostas, sua mensagem poderia ser um comentário da pergunta, no entanto você ainda não possui reputação suficiente para tal. Sugiro que você abra uma pergunta própria explicando seu problema, porém antes leia [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example)


Using Composer in a multisite installation

Question: How do I manage modules via composer in a multisite architecture? For example, if I want one site to have version 2.3 of a module, and another to have version 2.4, how do I do this?
Do I have a composer file in each site that can inherit from the composer file in the parent Drupal application?
Answer: Short answer: you cannot do it The (new Drupal) Composer Way™ (still).
The composer is mostly project-oriented, however, based on the fact that they are projects of the projects, there is a chance that a composer.json could be made that would operate on a subsite level.
As far as we can go would be to hope that something will be done in the coming 9.2 release, somewhere south of Spring 2021. Until then, workaround and search for the best practices and other experiences (however sparsely) seems the only way
#2847218: Improve documentation around the multisite functionality
The (temporarily and incomplete) solution:
The only thing you are left with is to use the composer for the common, shared modules and to use drush or manually download modules and themes according to Drupal multisite structure:
-- sites
   -- site1
         -- modules           ----> site specific modules
            -- custom
            -- contrib
         -- themes            ----> site specific themes
            -- custom
            -- contrib
         -- files

Beside official documentation, you can read this post too: Drupal Multisite Setup: Are There (Still) any Valid Reasons to Use It? Should It Get Removed in Drupal 9.x?


Difficulties with Fail2Ban on PhpMyAdmin on CentOS

Question: I am Brazilian and I still try to adapt with the English language.
I'm having a hard time getting Fail2Ban to work on phpmyadmin.
I'm using CentOS 8.1.1911 and fail2ban 0.10.5-2.
My PhpMyAdmin is version 126.96.36.199.
I noticed that PhpMyAdmin logs login failures in the /var/log/secure file.
And he has an output like this:
Feb 14 21:40:37 www phpMyAdmin[3982]: user denied: root (mysql-denied) from 220.127.116.11
Feb 14 21:42:07 www phpMyAdmin[3978]: user denied: root (mysql-denied) from 18.104.22.168
Feb 14 21:42:09 www phpMyAdmin[3982]: user denied: root (mysql-denied) from 188.8.131.52
Feb 14 21:48:06 www phpMyAdmin[3981]: user denied: root (mysql-denied) from 184.108.40.206

So, I configured my /etc/fail2ban/jail.conf like this:
[phpmyadmin]
enabled = true
port = http,https
filter = phpmyadmin
action = iptables-multiport[name=phpmyadmin, port="http,https", protocol=tcp]
sendmail-whois[name=PHPMYADMIN, firstname.lastname@example.com]
logpath = /var/log/secure
maxretry = 3

And the filter configuration file (/etc/fail2ban/filter.d/phpmyadmin.conf), the expressions are like this:
[Definition]
denied = mysql-denied|allow-denied|root-denied|empty-denied
failregex = ^<HOST> -.*(?:%(denied)s)$
ignoreregex =

I believe I am not able to correctly form the expression, as Fail2Ban is not blocking at all.
Could someone help me in this matter?
Comment: I believe that Fail2ban is launched by a systemd service named `fail2ban.service` in your system. If so, is there any relevant error messages displayed by `systemctl status fail2ban.service` or `journalctl --since -10m _SYSTEMD_UNIT=fail2ban.service`? Have you tried to [test the filter using `fail2ban-regex`](http://www.fail2ban.org/wiki/index.php/MANUAL_0_8#Filters) or run `fail2ban` manually using `fail2ban-server -f`?
Comment: Dear friend,

Fail2ban is running OK, with no errors in the logs. See this output:

[root @ www ~] # fail2ban-client status Status
| - Number of jail: 8
`- Jail list: apache-auth, apache-badbots, apache-noscript, apache-overflows, drupal-auth, drupal-comment, phpmyadmin, vsftpd

Everything is working properly, I'm just not able to block PhpMyAdmin Login failures.

Possibly because the regular expression in the /etc/fail2ban/filter.d/phpmyadmin.conf file is wrong.

Is there anything I can do to put it on to protect PhpMyAdmin?
Answer: I finally managed to solve the problem. Fail2Ban is now blocking properly.
I decided to update PhpMyAdmin to version 5.0.1. After I did that, I edited the following file:
/var/www/phpmyadmin/libraries/config.default.php
I changed the configuration as follows:
$ cfg ['AuthLog'] = 'auto'; ------> $ cfg ['AuthLog'] = 'php';

After I did that, he started to generate the logs differently and in a different file.
The logs started to be generated in the "/var/log/php-fpm/www-error.log" file.
And in this way:
[15-Feb-2020 17:18:11 UTC] user denied: root (mysql-denied) from 18.104.22.168
[15-Feb-2020 17:18:13 UTC] user denied: root (mysql-denied) from 126.96.36.199
[15-Feb-2020 17:18:14 UTC] user denied: root (mysql-denied) from 22.214.171.124
[15-Feb-2020 17:22:06 UTC] user denied: root (mysql-denied) from 188.8.131.52
[15-Feb-2020 17:22:08 UTC] user denied: root (mysql-denied) from 188.8.131.52
[15-Feb-2020 17:22:09 UTC] user denied: root (mysql-denied) from 220.127.116.11

Then, I configured the "/etc/fail2ban/filter.d/phpmyadmin.conf" file like this:
[Definition]
denied = mysql-denied | allow-denied | root-denied | empty-denied
failregex = user denied:. + from <HOST> \ s * $
ignoreregex =

After that, I configured "/etc/fail2ban/jail.conf" like this:
[phpmyadmin]
enabled = true
port = http, https
action = iptables-multiport [name = phpmyadmin, port = "http, https", protocol = tcp]
         # sendmail-whois [name = PHPMYADMIN, email@example.com]
logpath = /var/log/php-fpm/www-error.log
maxretry = 3

After that, it was just restarting fail2ban that everything was resolved.
Look at the logs, now blocking:
2020-02-15 14: 39: 42,005 fail2ban.filter [25748]: INFO [phpmyadmin] Found 22.214.171.124 - 2020-02-15 14:39:41
2020-02-15 14: 39: 44,009 fail2ban.filter [25748]: INFO [phpmyadmin] Found 126.96.36.199 - 2020-02-15 14:39:43
2020-02-15 14: 39: 46,013 fail2ban.filter [25748]: INFO [phpmyadmin] Found 220.127.116.11 - 2020-02-15 14:39:45
2020-02-15 14: 39: 46,204 fail2ban.actions [25748]: NOTICE [phpmyadmin] Ban 188.8.131.52

Comment: Thanks for sharing your solution. The `fail2ban-client` command output you have posted in comments section suggests that there was a problem with the regular expression and no permission problems caused by SELinux, for example. `fail2ban-regex` command should have pointed the root cause.


MacOS 10.14b / C++ using: command not found, what to do?

Question: I'm new to cpp. I have a macbook air with macos mojave 10.14 beta and when I try to launch this command as follows:
chmod +x start.cpp
./start.cpp

I get:
Errors:./start.cpp: line 2: using: command not found
./start.cpp: line 4: syntax error near unexpected token `('
./start.cpp: line 4: `int main()'

I have installed clang via VS Code extensions and xcode extension as well.
#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!";
    return 0;
}

int age() {
int age;
cout << "Enter your age: ";
cin >> age;
if (age > 18) {
    cout << "You are a child" << endl; }
else {
    cout << "You are an adult" << endl; }

return 0; }

This is the code. I know these are very basics and it's short but why isn't running.
I chmoded the code and ran it in terminal.
I thank you for every little help.
Edit: The IDE doesn't show any errors.
Comment: You should include the command you used to attempt to run this in your question, it is essential information to diagnosing your misunderstanding.  Leaving it in a comment is insufficient.  That said it was possible to guess from the error C++ has nothing in it that the language refers to as a "command".
Comment: Program will run smoothly on GCC - what command did you use to run this?
Comment: chmod +x start.cpp
./start.cpp

I'm used to python 3 :DD
Answer: You need to compile and link the program first. C++ is not a scripting language. The source code cannot be run directly. It needs to first be translated to machine code.
There are several steps to the compilation process:
First the preprocessor does macro expansion and similar on the source text. Then the compiler translates the preprocessed source to assembly language. Then the assembler converts the asm to machine code, forming an object file. Then the linker links multiple object files into an executable program or a library.
In simple cases the compiler "driver" can do many/most/all of those steps for you behind the scenes. But they still exist and in more advanced programs you often need to take control of some of them.
For a simple single source program all you need is most likely just g++ -o start start.cpp to compile and link your code into a progran named "start" that you can then run (assuming you are using the GCC compiler - alternatives exist, such as clang clang++ or Microsofts cl.exe on Windows).
Btw; read up on your compiler and its options. That's really important. The above commandline generates a debug build of the program, suitable for debugging, but slow. To do a release (fast) build you need to pass options (and I'm not even scratching the surface of what you need to/should know about your compiler/linker). Since you are new, here are some basic recommend options to pass to the compiler to get it to help you spot errors sooner: -Wall -Wextra -Werror (and add -O2 or -O3 as well to enable optimization and make your program run fast (but it will also be hard to debug in a debugger - another tool you must learn about)).


Definição formal das operações = e ==

Question: Qual a definição formal sobre o uso de = e de == no Python? Consigo identificar nos exemplos quando tenho que usar qual, mas quando tento identificar essas operações por uma definição formal como (mais ou menos como se fosse um conceito matemático) me enrolo.
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: É muito simples, o = é um operador de atribuição, você só deve usá-lo para guardar um valor em uma variável. O operando do lado esquerdo sempre deve ser uma variável, nada mais que isto. Já o operando direito aceita um valor vindo de uma literal, uma variável (outra ou a mesma, ainda que não faça muito sentido ser a mesma) ou uma expressão que será executada e o seu resultado gerará um valor, e o valor final obtido será guardado na variável.
O == é um operador de comparação. Os dois lados podem ser variáveis, literais ou expressões diversas. Sempre tentará identificar que o valor final obtido do lado esquerdo é igual ao valor final obtido no lado direito. O resultado da operação de comparação será do tipo booleano, ou seja, será True ou False. É muito comum usá-lo um um if ou while, mas não precisa ser assim, pode ser usado em qualquer lugar que espera um booleano, inclusive pode ser usando no lado direito do = e atribuir esse valor à uma variável ou pode usar para imprimir algo ou passar como argumento em uma função.
O conceito é válido para essencialmente qualquer linguagem.
x = 1 == 2

Este é um exemplo onde x valerá False porque está atribuindo na variável o que está do lado direito que é uma comparação se são valores iguais, o que obviamente não são. Para entender um pouco melhor podemos fazer isso, ainda que desnecessário pela precedência a associatividade de operadores:
x = (1 == 2)

Coloquei no GitHub para referência futura.
Answer: Bem, não consigo imaginar uma definição mais formal do que a própria documentação oficial da linguagem. Então vamos a ela:

Assignment Statements
O = é chamado de assignment statement (declaração de atribuição), cuja definição é:

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects

Ou seja, ele serve para vincular (ou revincular) nomes a seus respectivos valores, e também para modificar atributos de objetos mutáveis.
Tecnicamente falando, o = é apenas uma parte do assignment statement, já que este é composto também das partes que vêm antes e depois do =:
assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

Não vou listar todas as possibilidades, mas apenas para dar alguns exemplos:
# atribuir um valor a uma variável
x = 1
# atribuir um valor a várias variáveis de uma vez
x = y = z = 1

lista = [1, 2, 3, 4, 5]
# mudar valor de uma posição da lista
lista[2] = 10
# slice, muda um pedaço da lista
lista[1:4] = [ 8 ]
print(lista) # [1, 8, 5]

dic = { 'nome': 'Fulano', 'idade': 42 }
# mudar o valor da chave de um dicionário
dic['nome'] = 'Ciclano'
# ou, adicionar uma nova chave
dic['email'] = 'firstname.lastname@example.com'
print(dic) # {'nome': 'Ciclano', 'idade': 42, 'email': 'firstname.lastname@example.com'}

lista = [1, 2, 3, 4, 5]
# x recebe 1, y recebe 2, resto recebe o restante da lista [3, 4, 5]
x, y, *resto = lista

x = 1
y = 2
# troca os valores de x e y
x, y = y, x

Lembrando que o lado direito de uma atribuição pode ser qualquer expressão válida que seja compatível com o lado esquerdo (por exemplo, em x, y = lista, a lista deve ter pelo menos dois elementos, senão dará erro).
Vale lembrar também que o = não é um operador (em algumas linguagens é, mas em Python não), tanto que no Python 3.8 foi criada a Assignment Expression (ver também aqui), que define o operador := e possui algumas diferenças com relação a = (basta ver que a Tabela de Precedência de Operadores tem o :=, mas não tem o =).

Comparador de igualdade
O == é um dos operadores de comparação, que no caso verifica se os valores dos operandos são iguais.
Lembrando que o Data Model da linguagem define o "valor" de um objeto de maneira bem abstrata, pois depende muito dos tipos envolvidos. Na documentação estão descritas todas as regras para os tipos nativos - por exemplo, números em geral podem ser comparados entre tipos diferentes (um int e um float podem ser iguais), já para sequências (como listas e tuplas) a regra é diferente, etc.
Por fim, qualquer classe que você criar pode sobrescrever o método __eq__ e definir seu próprio algoritmo para determinar se dois objetos são iguais. Basicamente, ao fazer x == y, será feita a chamada a x.__eq__(y). Se você não sobrescrever este método, ele chama a implementação de object, que usa o operador is (que considera dois objetos iguais somente se eles forem o mesmo objeto).
Um detalhe importante é que o operador == sempre retorna um booleano (True ou False), mas o método __eq__ pode retornar qualquer valor (que por sua vez, se for usado em um contexto booleano, será convertido usando-se bool()):

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

Portanto, são coisas bem diferentes. Uma forma didática de pensar é:

nome = algo está dizendo ao Python que nome recebe o valor algo - é uma afirmação (ou se preferir, uma ordem: "coloque o valor algo na variável nome")
nome == algo está perguntando ao Python se o valor de nome é algo - e a resposta será sim ou não (True ou False, que é o resultado da expressão)
Answer:
"=" Faz a atribuiçao.
"==" Faz a comparação.

Definição formal das operações = e ==


"IF statement" in a Neural Network

Question: In classification problems, it is frequent to have classes with different properties. For example, I came across a problem where I needed to classify the following images in a single network:

White mugs
Black mugs
Blue mugs
Glasses

As my approach was getting more complex, the accuracy between glass vs mugs (due to the lights) was increasing, but after looking at the confusion matrix, black vs blue vs white seemed to overfit. Likewise as my model was getting simpler, glass was confused for white and blue for black and black for white.
How can I write a NN such as:

If it is a mug, then classify mugs only, else it is a glass.

If this concept makes any sense (let aside the mug oversampling issue), I would appreciate any reference to papers or how can this be implemented in theory.
Comment: If the problem is as trivial as you described, the simplest solution may be to make it a multi-calss classification with four labels.
Comment: @Tim my approach was indeed a variety of CNNs with multiclass classification. Although, the main issue was the distribution of my misclassified objects. As the valid. accuracy between glass and mugs was increasing, the v. accuracy between mugs was decreasing. That's why I came with an idea of a "2 step" network, so I can "rebalance" the distribution to look more like a uniform in my confusion matrix.
Comment: This hierarchy problem not branching. Lookup "hierarchical multi label classification," not the most trivial task for NN. Decision trees would be more natural fit here
Answer: You can make your network aware that high probabilities of having a glass should make it detrimental to output probabilities of mug colors, a soft IF statement implemented with a gating mechanism.
At the end of your network $\mathcal N$ you could add two branches: $\mathcal G$ (for glass) & $\mathcal M$ (for mug).

$\mathcal G$ outputs a probability that decides if the image contains or not glasses.
$\mathcal M$ outputs three probabilities, which pertain to the colors of the mugs.
$\mathcal M$ probabilities are multiplied by $(1 -\mathcal G)$ probabilities, making it aware if said object is, in fact, not a mug.

You end up having to optimize for two losses: the binary cross-entropy of glass-vs-mug and the categorical cross-entropy for white-vs-black-vs-blue mugs. You can, of course, fuse them into a single categorical cross-entropy with the probabilities: $\mathcal M_{\text White}, \mathcal M_{\text Black}, \mathcal M_{\text Blue}, \mathcal G$, keeping the rest of the branches intact.

"IF statement" in a Neural Network


Detecting left and right swipes on Fragment

Question: I am trying to get left, right, top, and bottom swipes detected on Android fragments.  Using a couple online resources, such as this great answer on Stackoverflow, I now have up and down swipes being detected.  However, it is not working for left and right swipes.
OnSwipeListener.java:
// Detects left and right swipes across a view
public class OnSwipeTouchListener implements View.OnTouchListener {

    // https://developer.android.com/reference/android/view/GestureDetector
    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context context) {
        this.gestureDetector = new GestureDetector(context, new GestureListener());
    }

    // from View.onTouchListener class
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return gestureDetector.onTouchEvent(motionEvent);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;

            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e2.getX();

                if(Math.abs(diffX) > Math.abs(diffY)) {
                    if(Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if(diffX > 0) {
                            onSwipeRight();
                        }else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                } else if(Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if(diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;

        }

    }

    public void onSwipeRight() {

    }

    public void onSwipeLeft() {

    }

    public void onSwipeTop() {

    }

    public void onSwipeBottom() {

    }

}

Then I use these methods in MyFragment.java, in the onCreateView method:
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.myfragment_layout, container, false);

        v.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
            public void onSwipeTop() {
                Toast.makeText(getActivity(), "TOP SWIPE", Toast.LENGTH_SHORT).show();
            }

            public void onSwipeRight() {
                Toast.makeText(getActivity(), "RIGHT SWIPE", Toast.LENGTH_SHORT).show();
                //go back to landing page
                // Intent intent = new Intent (getApplicationContext(), MainScreen.class);
                // startActivity (intent);
            }

            public void onSwipeLeft() {
                Toast.makeText(getActivity(), "LEFT SWIPE", Toast.LENGTH_SHORT).show();
            }

            public void onSwipeBottom() {
                Toast.makeText(getActivity(), "BOTTOM SWIPE", Toast.LENGTH_SHORT).show();
            }
        });

        return v;
    }

Any help would be appreciated.  Thank you.
Answer: I believe this line is wrong:
float diffX = e2.getX() - e2.getX();

should be
float diffX = e2.getX() - e1.getX();

Comment: Can't believe I missed that.  After this change it is detecting left and right swipes, but only sometimes.  Thank you.
Answer: Check below code to detect swipe gesture
 static class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {

    OnViewPagerSwipe onViewPagerSwipe;

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2,
                           float velocityX, float velocityY) {
        switch (getSlope(e1.getX(), e1.getY(), e2.getX(), e2.getY())) {
            case 2:
                onViewPagerSwipe.onViewPagerSwipe(MainActivity.SWIPE_LEFT);
                return true;
            case 4:
                onViewPagerSwipe.onViewPagerSwipe(MainActivity.SWIPE_RIGHT);
                return true;
        }
        return false;
    }

    private int getSlope(float x1, float y1, float x2, float y2) {
        Double angle = Math.toDegrees(Math.atan2(y1 - y2, x2 - x1));
        if (angle > 35 && angle <= 160)
            // top
            return 1;
        if (angle > 160 && angle <= 180 || angle < -160 && angle > -180)
            // left
            return 2;
        if (angle < -35 && angle >= -160)
            // down
            return 3;
        if (angle > -35 && angle <= 35)
            // right
            return 4;
        return 0;
    }

    void setViewPagerSwipeListener(OnViewPagerSwipe onViewPagerSwipe){
        this.onViewPagerSwipe = onViewPagerSwipe;
    }

}

Interface
interface OnViewPagerSwipe{
    void onViewPagerSwipe(int swipe);
}

Add this class from fragment onCreateView
SwipeGestureDetector swipeGestureDetector = new SwipeGestureDetector();
swipeGestureDetector.setViewPagerSwipeListener(this);
GestureDetector mDetector = new GestureDetector(getActivity(), swipeGestureDetector);


Can't use getAsset() in a Dialog class

Question: public class Class_UniversityDialog extends Dialog {

public Class_UniversityDialog(Context context) {
    super(context);
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_university_info);

    Typeface face = Typeface.createFromAsset(getAssets(), "tahoma.ttf");
    //To Layout Topic persian
    TextView txt_Title = (TextView) findViewById(R.id.lbl_LayoutTopic);
    txt_Title.setTypeface(face);
    String newText = (String) txt_Title.getText().toString();
    txt_Title.setText(PersianReshape.reshape(newText));
}

}

In my code eclipse says that getAssets() : " The method getAssets() is undefined for the type Class_UniversityDialog"

How can I solve this?
Answer: Use
getContext().getAssets()

http://developer.android.com/reference/android/app/Dialog.html#getContext()
Comment: thanks, this also solved my problem but I prefer the Marcin S. solution
Answer: Try to use context.getAssets(). before you use it define context and initialize it.
public class Class_UniversityDialog extends Dialog {
Context context;

public Class_UniversityDialog(Context context) {
super(context);
this.context = context;
}

Answer: Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");
textfield.setTypeface(tf,Typeface.BOLD);

You can use like that this one has your prblem solved

Can't use getAsset() in a Dialog class


Let $R$ be an integral domain which is not a field. Show that $R[X]$ is not a principal ideal domain.

Question: My attempt: Since $R$ is not a field, there must be a nonzero element $a$ in $R$ that is not a unit. Let $I=(a,X)$, and we try to show that this ideal is not principal. Since $R$ is an integral domain, then $I=\left\{af(X)+cg(X): f(X),g(X)\in R[X]\right\}$. Suppose it has a generator $h(X)$, then $I=(h(X))$. Since $a\in I$ and $X\in I$, we have that $h(X)|a$ and $h(X)|X$.
How to proceed?
Answer: Typically, one then argues that $h(X)$ must be constant by degree considerations (since $R$ is a domain), and then argues a bit more to deduce the desired claim. However, I will suggest an easier route: note that the principal ideal $(X)$ is prime, since $R[X]/(X) \cong R$, but is not maximal, since $R$ is not a field. Since every prime ideal is maximal in a PID...
Comment: Makes sense, thank you!
Answer: As $R$ is a domain, the degree of a product of polynomials is the sum of the factor degrees. Using $h(X)\mid a$, this tells us $\deg h\le \deg a=0$, hence $h$ is a constant. But then from $h(X)\mid X$, the leading coefficient of $h$ must divide the leading coefficient of $X$, i.e., the leading coefficient of $h$ - which is just the constant $h$ itself - is a unit.


Can I access Outlook calendar via POP or similar server?

Question: I'm doing a micro-controller project. I know how to access email via a POP server.  That part is easy.  What I would like to do is access an Outlook calendar via some similar method.  Is this possible?
Comment: I think this Stack Exchange site: http://superuser.com/  would be more suitable to ask this question.
Comment: Thanks I think I will repost over there.
Comment: Avoid repost, delete this one and post there or do not repost. It is not well received.
Answer: No POP3 won't work for that, Exchange Web Services will be the easiest choice probably.


Looping through 2D array using sizeof() in C++

Question: I am trying to write a small C++ library to do simple matrix calculations. It consists of a Matrix class with static member functions altering given matrices.
I have one function which adds a scalar to each element, however the loop isn't working:
// Member function to add a scalar to the matrix
void Matrix::add_scal(double** arr, double s) {
    for (size_t x = 0; x < sizeof(arr) / sizeof(*arr); ++x) {
        Serial.println("test");
        for (size_t y = 0; y < sizeof(*arr) / sizeof(**arr); ++y) {
            arr[x][y] += s;
        }
   }
}

"Test" is only printed once and the inner loop isn't run at all. Here is the function I use to create a matrix:
double** Matrix::init(int rows, int cols) {
    double** temp = new double*[rows];
    for (int i = 0; i < rows; i++) {
        temp[i] = new double[cols];
        for (int j = 0; j < cols; j++) {
            temp[i][j] = 0.0;
        }
    }
    return temp;
}

The following two lines create a matrix and are supposed to add a scalar to it:
double** test = Matrix::init(3, 3);
Matrix::add_scal(test, 2.5);

Comment: Ok sorry, could you please elaborate on what it does and whether I could still get the amount of elements in an array using it?
Comment: Arrays aren't pointers and pointers aren't arrays. Use `std::array` or `std::vector` instead. Both of these have a `size()` function you can use to determine the size.
Answer: The loop is not working, because sizeof() is not working as you think it does.
You are asking for the size of pointer, which is always a constant on a given machine (e.g. it is 4 in a 32bit). So, when you ask for the size of *arr, or **arr, that would be a number, irrelevant from the dimensions of the matrix!
In order to verify this yourself, print them, like this:
std::cout <<sizeof(*arr) << " " << sizeof(**arr) << std::endl;

Read more in Is the sizeof(some pointer) always equal to four?

In order to loop over a matrix, you need to use its dimensions, rows and cols in your case, like this:
void Matrix::add_scal(double** arr, double s) {
    for (size_t x = 0; x < rows; ++x) {
        Serial.println("test");
        for (size_t y = 0; y < cols; ++y) {
            arr[x][y] += s;
        }
   }
}

PS: You dynamically allocate the matrix correctly, but do not forget to free the memory when you don't need it any more-it's a must! If you don't know how, check my dynamic 2D array in C++
.
Tip: In C++, I strongly suggest you to use std::vector, which grows and shrinks in size automatically. Moreover, it has a method called size(), which returns the size of it, so you don't need to track its size manually!
In order to create a matrix using vectors, read Vector of Vectors to create matrix.
Comment: Thank you very much for your detailed explanation. I thought I could loop through the array like this because of this question: https://stackoverflow.com/questions/8109961/loop-through-a-multidimensional-array
Comment: @derivmug this should give a warning: `warning: division 'sizeof (double*) / sizeof (double)' does not compute the number of array elements [-Wsizeof-pointer-div]`! You are welcome, glad I helped, and don't forget to accept my answer, if it helped!
Comment: @derivmug read more in [array decaying](https://stackoverflow.com/questions/1461432/what-is-array-decaying).


Lowering my chest note

Question: I am 19 and my lowest note is F2(breathy). I want to increase my lower chest range. Any suggestion. For lowering it down further.
Comment: Grow older;) Give it another 20 years & you'll be wondering where the top of your range went, instead of worrying about the 3rd you gained at the bottom.
Comment: Just keep doing descending scale runs in your vocal warmup. You'll get more comfortable in your lower range that way. I generally sing down to C#2 or D2 but when I'm particularly relaxed and warmed up I can hit as low as a Bb1. When I was your age my lower range was Eb2-F2 so I second the growing older comments.
Comment: Are you taking lessons?  Get a professional classical voice coach.  All I can think of is support with the diaphragm, proper mouth shape, posture.  It is all very internal.  No way to help via chat messages except to say take lessons with a classical voice coach.  You may be frequency limited by your size.  Other than proper relaxed practice I don't know any "tricks" to extend range.
Comment: @ Tetusjin: get older, was my first reflection too.
Answer: Lay on your bed, the head outside the bed end. Let your head hang down, breath deep in and out. Shake your head, than hold your chin on your breast.
(by this exercise you stretch and enlarge your vocal chords)
Comment: This is an interesting idea, do you have any citation for this?
Comment: Head and neck gym is a standard warm-up I used as choir leader.
Comment: How may sets or reps?
Comment: each time you before you start singing. Do it slowly, like your breathing, counting 1,2,3,4, in seconds, if you do repeat it 6-10 times it will last min. 50 seconds (in groups). If you do it alone you can also practice to let hanging your head as long you feel comfortable, stop before your head  falls down or you have a neck like a giraffe.

Lowering my chest note


Varimax Rotated factors are very much NOT uncorrelated?

Question: On the back of an earlier question i am having an issue.
Software = SAS JMP Pro 11
Earlier Question
My rotated factors (post Principal Components Analysis [PCA]) are not at all uncorrelated. I have used Variance Inflation Factor (VIF) scores to initially look at this.
I expected some increase in the VIFs across the board but what i have is pretty dire with VIFS in the 10000s on occasion.
The PCA factors unrotated are completely uncorrelated when looking at VIFs (all 1.5 or less). What problems can occur in the rotation step to cause this?
The original variables load onto to many of the unrotated factors to too high a degree to be of much real world use.
I have seen written there is no real difference between orthogonal or oblique rotation and I have also found this to be the case
The only thing i can think is my non positive definitive matrix but I thought (I do not know) that if the unrotated factors are uncorrelated this meant the matrix was handled OK?
Comment: What `earlier question`? Link, please.
Comment: I have linked the previous related question.
Comment: I am not sure if this isvalid but i have used a different estimation method to generate the correlation matrix and have now lost the NPD response the software was giving me. I have changed from pairwise (default) to rowwise (misses out rows with missing data). I now no longer get the NPD error, my PCs and rotations of these look slightly different but the topology is the same. Crucially the rotated PCs via variamax no longer are collinear (VIF analysis). Is this valid?
Comment: @Samuel: I see nothing wrong with omitting rows with missing data. So the problem is solved?
Comment: i think yes i am satisfied in mind (the hardest part) that the problem is solved. I have another question but i think that is best left for another day!
Answer: I have used a different estimation method to generate the correlation matrix and have now lost the Non-Positive Definitive (NPD) error the software was giving me. I have changed from pairwise (default) to row wise (misses out rows with missing data). I now no longer get the NPD error, my Principal components and rotations of these look slightly different but the topology is the same. Crucially the rotated Principal components (via Varimax) no longer are collinear (Variance Inflation Factor [VIF] analysis).
Comment: Please accept your own answer. Also: maybe you could de-abbreviate NPD and VIF. It could also be useful for the potential google searches if you wrote which software you were using.


String to new object with parameters

Question: How do i create a new instance of an object from a string?
I want to do this:
Event event = new Event("hello");
event.setName("nice!");

but only having
String object = "Event";
String object_variable_name = "event";
String object_params = "hello";

Is this possible?
Comment: possible duplicate of [How to get a Class Object from the Class Name in Java](http://stackoverflow.com/questions/1438420/how-to-get-a-class-object-from-the-class-name-in-java)
Comment: You can do it using reflection. Here is another post which may help: http://stackoverflow.com/questions/5211450/java-reflection-instantiate-a-new-object-with-specified-type
Comment: You would have to write your own string to object interpreter.
Answer: You can instantiate a class with the reflection API. But you need the full class name, the simple name (= with no constructor) is not enough.
Class clazz = Class.forName("com.example.Event");
Constructor constructor = clazz.getConstructor(String.class);
Object instance = constructor.newInstance("hello");

Assigning it to a variable where the variables name and type are stored in Strings is not possible. The usual pattern to implement this is to use a map:
Map<String, Object> events = new HashMap<String, Object>();
events.put("event", event);

Comment: This looks good, but this line "Event event = (Event) constructor.newInstance("hello");" assumes that I know the type is Event, but I only have the string value
Answer: You can use java.lang.Class's getConstructor isnstead.
Answer: Here is how you get the class instance (so you can call the constructor): How to get a Class Object from the Class Name in Java
Now you can you the Beans API to get the getter for the property name. See this question: Java Reflection: Instantiate a new object with specified type
Or you can use reflectasm or reflections or commons-beanutils to make your life much more simple

String to new object with parameters


Why is it worth spending time on type theory?

Question: Looking around there are three candidates for "foundations of mathematics":

set theory
category theory
type theory

There is a seminal paper relating these three topics:
From Sets to Types to Categories to Sets by Steve Awodey
But at this forum (MSE) and its companion (MO) the tag [type theory] is seriously underrepresented. As of today (2013/11/13) (questions by tag):
MSE

set theory: 1,866
category theory: 1,658
type theory: 39

MO

set theory: 1,437
category theory: 1,920
type theory: 40

Update (2017/05/17):
MSE

set theory: 4,435
category theory: 6,137
type theory: 224

Update (2019/07/15):
MSE

set theory: 6,267
category theory: 9,009
type theory: 371

Update (2020/05/05):
MSE

set theory: 7,038
category theory: 10,255
type theory: 441

What does this mean? Is type theory a hoax?  For example, I stumbled over this MSE comment (by a learned member):

[...] a lot of people [in the type theory community] didn't know
  what they really talk about (in comparison to, say, classical
  analysis, where the definitions are very concrete and clear). I'm sure
  that that's not 100% true on the actual people, but that impression
  did stick with me. [...]

I'd like to learn from the MSE- and MO-community (resp. their experts):

Why is it worth spending time on type theory?
Comment: From my, admittedly very shallow, understanding, it is usually argued that type theory is much closer to the way a working mathematician thinks than either set theory or category theory. While set theory is ontologically very simple, you need to jump through all sorts of hoops to construct objects (like the real numbers) that most people actually work with and the constructions tend to leave you with strange artifacts (e.g. the question whether $\emptyset \in \pi$ makes sense to a set theorist but probably no one else).
Comment: @HansStricker I can't pretend to know why type theory has a smaller presence on MSE/MO. The fact of the matter is that most mathematicians have at least some training in set theory, quite a few know something about category theory, but knowledge of type theory is restricted to a relatively small group (who also tend to call themselves computer scientists instead of mathematicians). Some would call this a historical coincidence.
Comment: A kind of type theory is homotopy type theory, in which you can write proofs on a computer and have them checked. One motivation according to Voevodsky is that homotopy type theory would be better resistant to potential contradictions in mathematics. I know very little about this, and am not convinced myself, but if you are interested in foundations it is at least interesting. He has an expository lecture: http://video.ias.edu/univalent/voevodsky
Comment: That bit of homotopy type theory is a little bit oversold and is hardly unique to homotopy type theory (qua type theories). Coq, Agda etc. have been around a long time!
Comment: @Miha: But what does this imply, concerning the participants of MSE/MO? Aren't they working mathematicians? Shouldn't type theory be much more prominent than set or category theory (with regard to being "much closer to the way a working mathematician thinks")?
Answer: Type theory is to set theory what computable functions are to usual functions. It's a constructive setting for doing mathematics, so it allows to deal carefully with what can or can't be computed/decided (see intensionality vs. extensionality, or the different notions of reduction and conversion in $\lambda$-calculus). Furthermore, just like category theory, it gives a great insight on how certain mathematical objects are nothing but particular cases of a general construction, in a very abstract and powerful way. Look up the propositions-as-sets and the proofs-as-programs paradigms to see what I mean (but there's a lot more than that).
Now, as always there are some cons. I'm thinking of two reasons why type theory hasn't had much success among the general mathematicians:
First, type theory doesn't allow abuse of language. For example, in type theory it is usually the case that if $A$ is a set, then a subset of $A$ is not a set. It is a completely different kind of entity: it will probably be a propositional function, i.e. something which maps elements of $A$ to propositions. Another example: if $n$ is a natural number, then $n$ is not an integer (but something like $\mathsf{int}(n)$ will be). Distinctions like these make some mathematicians uncomfortable, but they prove helpful in dealing with certain things which are maybe more interesting to computer scientists (and of course logicians).
Second, there is no "canonical" type theory. Most of the mathematics done in set theory is actually based on $\mathsf{ZFC}$ (or some extension of it). But the fact that there are many different kinds of type theories makes communication between people harder.
Anyway, there have been many attempts to actually start developing some mathematics in type theories, and some of them have been quite successful: see for instance the work by G. Gonthier with Coq, a proof assistant based on a type theory called the Calculus of Inductive Constructions.
Comment: I'd argue that type theory allows your second example of abuse of language much more than set theory does. In type theory, subtyping is exactly the notion required. In material set theory, if n is a natural number, n may well also be an integer, but it could be totally the wrong one depending on the encoding. I think the distinction you're pointing out here is between formal and informal maths, which is in principle orthogonal, but culturally/historically related. Your second point is also relevant, in that many type theories do not do this kind of subtyping.
Comment: +1 for a really good introductory answer that I think really hits the nail on the head of the important differences between the 2 approaches to foundations. For the details, a good working knowledge of mathematical logic is needed,though. Basically the advantage of set theory is it's ontological simplicity and the advantage of type theory is that it avoids almost entirely the paradoxes and "counting" problems one runs into in set theory, especially ZFC and it's variants.
Answer: What exactly is (simple) type theory? After reading some historical accounts on the development of logic, I really wanted to know the answer. However, I kept getting lost in the apparent triviality of the (typed) lambda calculus that I got as answer when I tried to look it up. This sad state of affairs was resolved when I came across "The seven virtues of simple type theory" by William M. Farmer. To my delight and surprise, it turned out that "simple type theory" is an elegant formulation of higher-order logic. There is even a simple and elegant proof system for it, which has the same consistency strength as bounded Zermelo set theory (a predicative system also known as Mac Lane set theory). However, the last claimed virtue in that article is Virtue 7 There are practical extensions of STT that can be effectively implemented. The corresponding section 8 Practicality contained an interesting selection of items from Pandora's box, if I may say so.
Let me add some thoughts in response to Pandora's box and Luca Bressan's comment. There exists many variations of type theory, exactly because it is a very practical logical system. However, this leads to many types of (terminology) confusion. Is "simple type theory" the same thing as "simply typed lambda calculus"? To which extend are polymorphism, subtypes and dependent types important? Are they used by homotopy type theory? What about intuitionistic variants? Is (homotopy) type theory constructive, or at least predicative?
I learned to no longer worry about such questions. I'm just happy that I have now enough prerequisites to better understand some articles about the history of logic. In addition, I can now read article and books which expect a certain familiarity with type theory. This includes material related to Haskell, automatic theorem proving, and of course the HoTT book.
Comment: Simply typed lambda calculus is just *one* particular kind of type theory, and also a very weak one, albeit a starting point for many other type theories.
Answer: Disclaimer: I'm starting to learn type theory, so I'm not an expert.
Personally I've found the following some very good reason to study type theory.

For start type theory is a different kind of foundational theory, and sometimes working in different background can be interesting.
As Miha Habič pointed out set theory has lot of idiosyncrasy to make all the classical mathematical construction. Type theory is free from those tricky constructions and all the objects are build in a more natural way: although I have to admit that what's natural is a matter of tastes.
Type theory has also connections with computability theory: it's a constructive foundational theory and has deep link with computer science, in particular it is a formal system that is also a programming language and so it allows to develop easily proof assistant that can help in verifying correctness of proofs. Doing that in classical set theory can be more difficult, for what I get.

I suppose that there are many other good reason to learn type theory, that I'm not aware for now.
Edit: I've just seen that I haven't addressed the first part, the one about why type theory has so very few question on SE and MO on type theory.
Still a guess, but I suppose that is due to two facts:

type theory, in it's actual form is quite new, and(apparently that's false, see ZhenLin comment below) before  of the Homotopy Type Theory's book I've never heard of a reference which introduce type theory in a intuitive way: I suppose that made type theory really a thing for people interested in computation theory and mathematical logic;
almost all the mathematics had be written in terms of sets, this probably contribute in keeping more people interested in set theory rather the type theory.

Anyway I'm thinking that the trend is gonna change especially for the work of homotopy type theorist, I'm really confident that in a not really far future more mathematicians will use type theory as foundational background (many probably already do it without knowing), so it's just a matter of time, or at least that's what I think.
Hope this helps.
Comment: Type theory is not new! Homotopy type theory is just a version of Martin-Löf type theory, which was created in the 1980s.
Comment: That's because _extensional_ type theory is so natural that it needs no introduction! This is what we mean when we say that type theory is closer to how working mathematicians think.
Comment: @ZhenLin: Can you let me know (or cite references) where this difference is elaborated?
Comment: @ZhenLin when I say new I was referring to the naive type theory, I don't know of any reference before HoTT book which treat type theory from a non formal point of view.
Comment: This is an old thread, but if you are looking for a pre-HoTT informal presentation of type theory, then Constable's "Naïve Computational Type Theory" fits the bill: http://www.nuprl.org/documents/Constable/NaiveTypeTheoryPreface.html
Comment: @ZhenLin So HoTT book aims to create an intuitive approach to intensional type theory? Ok, thanks for the correction, I'm gonna edit.
Comment: @ZhenLin: Hasn't type theory been around since Russell?
Comment: That's a different kind of type theory...
Comment: @ZhenLin In fact, the very first type theories were constructed by Bertrand Russell and Lugwig Wittenstien in the early 20th century as the first attempt to solve the paradoxes of naive set theory. These early type theories were extremely complicated and cumbersome to work with, which is why most mathematicians and philosophers had abandoned them in favor of axiomatic set theories by the 1960's. Modern or simple type theory essentially is descended from 2 ancestors: Alonzo Churches' lamda calculus and the earlier mentioned Martin-Lof theory.