Transfom table with dates

Question: df = pd.DataFrame({'SKU': ['10001', '10002', '10003', '10004', '10004', '10001', '10002', '10003', '10004', '10004'],
                 'shop': ['s001', 's001', 's001', 's001', 's001', 's002', 's002', 's002', 's002', 's002'],
                 'date_start': ['01.02.2022', '21.02.2022', '15.03.2022', '20.03.2022', '20.03.2022', '01.02.2022', '21.02.2022', '15.03.2022', '20.03.2022', '20.03.2022'],
                 'date_end': ['02.05.2022', '03.03.2022', '23.03.2022', '30.03.2022', '22.03.2022', '02.05.2022', '03.03.2022', '23.03.2022', '30.03.2022', '22.03.2022']
                  })

I have table like "1" on the image, and i want transforme it to the "2".
I want get date range between date_start and date_end in my dataframe, for every SKU, shop and other data.

I think I should make some date generate in new column and after that open up.
Answer: Create a date range using pd.date_range for each row, then explode them:
df['Список дат'] = df.apply(lambda x: pd.date_range(pd.to_datetime(x['date_start'], dayfirst=True), pd.to_datetime(x['date_end'], dayfirst=True)), axis=1)
df = df.drop(['date_start', 'date_end'], axis=1).explode('Список дат').reset_index(drop=True)

Output:
>>> df
       SKU  shop  Список дат
0    10001  s001  2022-02-01
1    10001  s001  2022-02-02
2    10001  s001  2022-02-03
3    10001  s001  2022-02-04
4    10001  s001  2022-02-05
..     ...   ...         ...
245  10004  s002  2022-03-29
246  10004  s002  2022-03-30
247  10004  s002  2022-03-20
248  10004  s002  2022-03-21
249  10004  s002  2022-03-22

[250 rows x 3 columns]

Answer: Try:
fmt='%d.%m.%Y'
df['dates'] = [pd.date_range(pd.to_datetime(s, format = fmt),
                             pd.to_datetime(e, format = fmt),
                             freq='D')
               for s, e in zip(df['date_start'], df['date_end'])]
df[['SKU','shop','dates']].explode('dates')

Output:
      SKU  shop      dates
0   10001  s001 2022-02-01
0   10001  s001 2022-02-02
0   10001  s001 2022-02-03
0   10001  s001 2022-02-04
0   10001  s001 2022-02-05
..    ...   ...        ...
8   10004  s002 2022-03-29
8   10004  s002 2022-03-30
9   10004  s002 2022-03-20
9   10004  s002 2022-03-21
9   10004  s002 2022-03-22

[250 rows x 3 columns]

Transfom table with dates


Whether to leave the data unaltered in the face of outliers and non-normality when performing structural equation modelling?

Question: I recently received this email from a graduate student, and I get similar questions often enough, that I thought I'd post it here:

I'm using factor analysis, multiple regression, and SEM and currently
  checking statistical assumptions.  I have found numerous univariate
  and multivariate outliers.  If I deleted them all, it would mean a
  large chunk out of my sample size ($N \approx 350$).  I also have
  problems with non-normality, non-linearity, heteroscedasticity
  (Multiple regression), and large standardised residual covariances
  (SEM).
I have tried reducing the influence of the outliers (allocating them a
  value one unit larger/smaller than the next most extreme non-outlier
  value), and transformations (mostly the variables remained skewed and
  some outliers remain).  When I compare original results with altered
  data, there is little effect.  Given this, I am wondering whether it
  would be acceptable to leave the data as it is? I'm inclined to,
  particularly because this data is from a non-clinical population and I
  have used clinical measures.
Answer: A lot depends on where exactly the outliers occur within the model -- in the indicators? in the latent variables and their measurement errors? in the exogenous variables, at the top of the causal chain? In the former case, you cannot do much, as you really have a high leverage influential cases rather than outliers. To control for outliers in the indicators/response variables, you need to work at the equation level, like Moustaki and Victoria-Feser (2006) did. Shooting at it with the robust covariance matrices may or may not be the right thing to do. I am referring here to the recent work by Ke-Hai Yuan and Zhiyong Zhang of Notre Dame who tried to revive robust estimation methods as applied to structural equation modeling -- see e.g. their R package rsem (that seems to rely on having EQS as the estimation engine though, which is weird given the variety of choices within R). They've been publishing like crazy on this in the past five or so years; I've reviewed at least three papers for various journals, and frankly I am at a loss which one is to be recommended, as they all repeat each other. I have not seen this used much in applied work, although it probably should be; may be you'd be the trendsetter!
A great diagnostic tool is the forward search method developed by Atkinson and Riani of LSE (for regression and multivariate data). This has been adopted for SEM here and here. I personally think this is really neat, but whether it could catch up in the SEM community at large, I don't know.
Frontiers in Quant Psy published a review paper on this in early 2012. Even though I am the acknowledged reviewer of this work, I am extremely reluctant to really recommend it (it barely passed my threshold of publishable work, and I simply gave up explaining the theory of robust statistics in my referee letters), but I am just not aware of anything better.
Answer: General References

Hair et al has a fairly extensive non-mathematical discussion of  issues of multivariate data cleaning and assumption testing that you might find accessible.

First step: Understand your data

Why are the distributions  as they are?
What is causing the outliers?

You might want to think about whether the skew and outliers are a natural part of the phenomena or reflect data entry errors, erroneous measurements, or participants for which your model is not intended to generalise.
Another point, transforming data will often remove or reduce issues of outliers.
What to do with non-normal data
There is some discussion of strategies for performing structural equation modelling with non-normal data here:

http://rudyanto62.blogspot.com/2008/01/handling-non-normal-data-in-sem.html
http://ssc.utexas.edu/software/faqs/amos#Amos_7

In general, it should give you greater confidence in your results that your results are not sensitive to the form of transformation and outlier adjustments that you make.
Large standardised residual covariances

This may suggest that your proposed model provides a poor fit to the data. It's important to think about the implications of this. What changes to your model do these residuals suggest that you make?


Como apagar variáveis definidas no Gerenciador de Cabeçalho em uma determinada requisição HTTP (JMETER)

Question: Alguém poderia ajudar?
Eu gostaria de apagar um determinado parâmetro (variável) informado no Gerenciados de Cabeçalhos HTTP em apenas uma Requisição HTTP.
Desde já agradeço!
Answer:
Adicione JSR223 PreProcessor  como um filho da sua requisição HTTP
Coloque o seguinte código dento da  "Script" area
sampler.getHeaderManager().removeHeaderNamed('foo')

Substitua foo com o nome do cabeçalho, que você deseja remover.

Mais informações em:

HeaderManager.removeNamedHeader()
Apache Groovy - Why and How You Should Use It
Comment: Olá @Dmitri. Está no **SOpt**, pf coloque a sua resposta em português.


Authenticating against the Yammer JS SDK using ADAL in SharePoint Online

Question: After scouring the internet, I've found a variety of answers to this question, but nothing is clear. With an Azure AD app, it looks like Yammer Delegate permissions are included so I would imagine that I could use then ADAL token from the app, to interact with Yammer APIs but have been running into issues. Has anyone else got this working? Is there any way to silently authenticate with yammer in SharePoint online?
Answer: The Yammer Delegate permissions are a preview feature. Long-term we plan to integrate fully with the O365 developer experience, but aren't quite there yet. Today, Yammer supports a number of scenarios that don't align with O365. Once the product better aligns it's going to be possible to provide much deeper integration (not just limited to developer APIs.) One limitation of the delegate permission is that it won't work with networks that are using Yammer Identity. Another is that some endpoints might not accept the tokens.
The supported authentication flows for Yammer are documented on the developer site and these support users with all authentication types for Yammer. With these APIs you'll end up juggling an additional Yammer-only token. It is possible to use impersonation to silently authenticate users without them being prompted to authorize the Yammer app. There is a blog post providing an overview of how this can be used in combination with the Yammer JS SDK, but the tokens could be used from other clients.
Comment: Thank you for the clarification @Brian Lyttle!


Intersection of sets: $\bigcap_{n \in \mathbb{Z}^{+}} \left[ -\frac{1}{n}, 0 \right[$

Question: Why is the following true?$$\bigcap_{n \in \mathbb{Z}^{+}} \left[ -\frac{1}{n}, 0 \right[ = \emptyset$$
The sets which are intersected get "smaller", and as $n \rightarrow \infty$, I reasoned that the interval becomes $[0,0[$. I don't exactly know how to make sense of that, but why not let this intersection be the set $\{0\}$ instead of an empty set? I understand that $[-1/n,0[$ does not contain zero, but $[0,0[$ seems to contain and not contain (?) zero.
Thanks in advance.
Comment: If anyone else is wondering, our friend Sherheryar means $[a,b) = [a,b[.$ This notation is commonly used in Europe more than in the NA.
Comment: It is the set $\{x \in \mathbb{R} | a \leq x < b \}$
Comment: @SheheryarZaidi So $\;[0,0[ \;=\; \{x \in \mathbb R | 0 \le x \;\land\; x \lt 0\} \;=\; \{x \in \mathbb R | \text{false}\} \;=\; \emptyset\;$.  So it does not contain $\;0\;$.
Comment: What is the meaning of $[a,b[$?
Comment: Because $0 \notin [-1/n, 0[$ for any $n.$
Answer: Suppose that set was not empty. Then, there would be $x \in \mathbb{R}$ such that $x\geq\frac{-1}{n}$ for every $n \in \mathbb{N}$, but $x<0$. Can you show why there is no such x?
Comment: Well, if I choose a certain $x \in \mathbb{R}$, which is non zero and negative, then I can always find some $n$ for which $-1/n > x$. Good argument. Similar to DanUznanski's.
Answer: You've got the hard part but not the easy here.  It does become $\left[0,0\right[$; but this is obviously the empty interval.  $\left[x,x\right]$ is merely $\left\{x\right\}$, but $\left[x,x\right[$ is open on the right, and so the set can't contain $x$ either.  Since that's the only thing in the set already, there's nothing left.
Comment: Well, the right side of $[x,x[$ says that $x$ is not part of the interval but the left side says $x$ **is** part of the interval. Why go for the right side and not the left?
Comment: Think about it.  $[0,0[ = \{x \in \mathbb{R} : 0 \leq x < 0\}$.  What element is simultaneously greater than or equal to $0$ and less than $0$?
Comment: @SheheryarZaidi, if one element does not belong in one set, it won't belong in the intersection of all those sets.
Comment: There is no such element, I agree with that then! +1
Answer: The question looks interesting, the primary purpose is to dissect the following method!
Say $x\in[-1/n,0)$
Now for any $x$ (negative) which belong to any of the above  the set, we can always find a $n_1\in Z^+$, such that $x<-1/n_1$. Hence there can't be any number which satisfies the above condition!
Answer: $
\newcommand{\calc}{\begin{align}\quad &}
\newcommand{\calcop}[2]{\\ #1\quad &\quad\text{"#2"}\\\quad & }
\newcommand{\endcalc}{\end{align}}
$Here is how I would prove this, directly using the definitions.  Implicitly letting $\;n \in \mathbb Z ^+\;$, we calculate the elements $\;x\;$ of this set:
$$\calc
x \in \langle \cap n :: \left[ -1/n, 0 \right[ \rangle
\calcop{\equiv}{definition of $\;\cap\;$}
\langle \forall n :: x \in \left[ -1/n, 0 \right[ \rangle
\calcop{\equiv}{definition of $\;[\cdot,\cdot[\;$}
\langle \forall n :: -1/n \leq x \lt 0 \rangle
\calcop{\equiv}{logic: move part not using $\;n\;$ out of $\;\forall n\;$; arithmetic: multiply by $\;n\;$}
\langle \forall n :: -1 \leq x \times n \rangle \;\land\; x \lt 0
\calcop{\equiv}{arithmetic: divide by $\;x\;$, allowed with changing sign by $\;x \lt 0\;$}
\langle \forall n :: -1/x \geq n \rangle \;\land\; x \lt 0
\calcop{\equiv}{arithmetic: $\;\langle \forall n :: y \geq n \rangle\;$ is false}
\text{false}
\endcalc$$


Probability density function in Stationary Random Process

Question: According to the definition of (strict) stationary random process "A process is strictly stationary if the joint distribution of any set of random variables obtained by observing the random process  $X(t)$ is invariant wrt location of origin t = 0". A corollary of this definition is $F_{X(t)} (x) = F_{X(t+\tau ) } (x)$ for all $\tau$ and t. If I keep on making $\tau$ very small, am I right in inferring that $F_{X(t_1 ) }(x) = F_{X(t_2 )} (x)$. If yes then the auto correlation should always be constant , that is equal to $R_X (0)$
Also please provide (if possible) a 3-D plot of stationary process.
Answer: Your claimed corollary

$F_{X(t)} (x) = F_{X(t+\tau ) } (x)$
  for all $t$ and $\tau$

is being interpreted incorrectly. It is true that all the random variables in the process have the distribution function, but in order to calculate the covariance of two of these variables, you need their
joint distribution, and, for strictly stationary random processes, this joint distribution depends only on $\tau$, the separation in time of the two random variables. Nowhere is it claimed that (for fixed $t$), the joint distribution of $X(t)$ and $X(t+\tau)$ is the same for all choices of $\tau$.  Indeed, the invariance to time origin for strictly stationary random processes is saying that

For all choices of real number $T$, the joint distribution of $X(t$) and $X(t+\tau)$ --- two random variables separated in time by $\tau$ --- is the same as the joint distribution of
  $X(t+T$) and $X(t+\tau+T)$ which also are two random variables separated in time by $T$.

It is not saying that $X(t)$ and $X(t+\tau)$ have the same joint distribution for all choices of real number $\tau$.
See this answer of mine on our sister site dsp.SE for more information about the consequences of strict stationarity.


Defined patern for mysql table primary key

Question: is there anyway to create lets say pattern for primary key i.e. for table products such pattern would by p-1,p-2... p-n etc.
Thanks
Answer: Well, you can manually create and enforce that pattern into your application (or using triggers). A primary key just needs to be unique to work.
But I don't recommend it. In your sample, seems P-1 have a business meaning. And, if it belongs to your business realm, it can be changed. While most database have a UPDATE CASCADE equivalent, it doesn't change basic reason you shouldn't use that as key: it's information, not data.
I suggest you to create a field named ProductCode char(10) NOT NULL UNIQUE and maybe to fill it with P-00000001, P-00000002, and so on. Maybe you do prefer to use a varchar: this doesn't matter, as it must fulfill your business requirement. Create an Id INTEGER AUTO_INCREMENT PRIMARY KEY field to use as primary key, as it doesn't never needs to be changed.
Comment: "int IDENTITY" on MySQL will be "INTEGER AUTO_INCREMENT PRIMARY KEY"


Postgres 8.3 on Ubuntu. Where are the server logs?

Question: Postgres 8.3 on Ubuntu. Where are the server logs?
I'm sure there must be a standard place it puts them.
Answer: Did you have a look in the /var/log directory? I assume the logs are placed in /var/log/postgresql. But you can also check the PostgreSQL configuration files for the logfile settings.
Answer: If you enable logging from /etc/postgresql/13/main/postgresql.conf then you'll able to see logs on this directory /var/log/postgresql.
Answer: Somewhere in /var/log would be my guess. That's the standard place for logs in Debian, which Ubuntu is derived from.


Can weighted average be used to calculate percentage increase?

Question:
Possible Duplicate:
Is this a weighted average/percentage problem?

Let's say a Marketing company has a total turnover of 10000 \$
There are 3 salesmen A,B,C with the following turnovers:
The turnovers have two components - Income and Expenses:
<code>A = 2000 $
B = 3000 $
C = 5000 $
Ia = 80% = 1600 $
Ib = 70% = 2100 $
Ic = 60% = 3000 $
Ea = 20% = 400 $
Eb = 30% = 900 $
Ec = 40% = 2000 $
Total Income = 6700 USD = 67%
Total Expense = 3300 USD = 33%
</code>
Now, If the company wants to increase total Income by 10 %, How should this increase be split across the Incomes of A,B,C? Is this a weighted average/percentage increase problem?
Comment: Whoa - not cool. This is your other question, with a tidbit added at the end.
Comment: I was not sure if weighted average method can be applied to both subtotals and deltas in subtotals. I have rephrased my question now
Comment: This question has been closed. You should edit and change your other question (the copy of this one) to reflect your question.
Comment: Also note that you can pick up a copy of the whole post and move it over, if absolutely necessary. Or the post history by clicking on the time (e.g. edited **3 mins ago**).
Answer: Firstly, this is a duplicate of your other question. Secondly, it has the same answer: if you want to increase the income, which is at 6700, by 10%, then adding 670 income to the three in any particular way will do it. If you wanted to maintain the income/expense ratio for each person, then it is slightly less trivial.
In this case, you want $0.8 A_+ + 0.7 B_+ + 0.6 C_+ = 670$. Here, I use letter$_+$ to indicate the additional turnover to the person with that letter. In a sense, that's a weighted average problem... but that's not how I would solve it (I would do it as above).
Comment: Adding 670 to the income increases Total income to 7370 and If expense remains the same, the percentage of total income and total percentage changes to 69.1 % and 30.1 %. Is there a way to solve this so that the Income percentage is 77% and the expense percentage is 23 %?
Comment: @Sathish: yes - but that is not increasing the income by 10%. Now you have a weighted average. You are solving $\dfrac{6700 + D}{10000 + D} = 0.77$. This has a solution - but I'll let you find it.


If $\log_{30}{3} = c$ and $\log_{30}{5} = d$ then the value of $\log_{30}{8} $ is??

Question: I attempted the following:

$\log_{30}{8} = 3\log_{30}{2}$
$\log_{30}{3} = c$ is equivalent to $3 = 30^c$
$\log_{30}{5} = d$ is equivalent to $5 = 30^d$

What should I do further?? Is there any basic formula for $log_a{(x - y)}$ ??
Answer: Here's an idea:
$$
\log_{30} 8 = \log_{30}(2^3) = 3 \log_{30}2 = 3 \log_{30}\left(\frac{30}{15}\right) =
3 \log_{30}\left(\frac{30}{3 \cdot 5}\right)
$$
I think you should be able to figure out the rest.


Smoothness of Product Functions

Question: Suppose $f:\mathbb{R}^{n}\times\mathbb{R}^k\to\mathbb{R}$. Define
$$f(x,y)\equiv f_x(y)\equiv f_y(x)$$
If $f_x$ and $f_y$ are both smooth, is $f$ smooth?
Answer: Well-known counterexample: $f=\frac{x^2-y^2}{x^2+y^2}$

Smoothness of Product Functions


regex to match everything

Question: I'm using the following regular expression to match everything:
/^(?=.{10,8000}$).*$/

But now I just realize that .* doesn't match the newline character. How can I make this regular expression match newlines?
Comment: Using a `{,}` repetition rule *and* match line breaks can be tricky. How many characters are there in a line break on your platform? On mine?
Comment: Add the multiline and global flag to the regex construct. var regex = new RegExp("^(?=.{10,8000}$).*$", "gim")
Comment: I will leave a compensantion in the 10,8000 repetition rule, like 10,7950. This way it will not throw a exception in the database. thx
Comment: @myself Why do you want to use a regex for this? It makes absolutely no sense whatsoever.
Answer: All whitespace + non-whitespace = all characters: [\S\s]
/^(?=[\S\s]{10,8000})[\S\s]*$/

Comment: @myself Actually it does. Although in general I have no idea why you need a regex for this.
Answer: var filter =  /.*/gim;

That will match everything across multiple lines.
Comment: `/.*/gim.exec("a\nb")` only matches `a` when I insert it into devtools or nodejs-repl.
Answer: I think that is pretty much simpler, just use
/.*/
. stands for any character and * allows any repetition of that character.
Answer: Why do you use a regex?
var txt = "Hello World!";
if(length(txt) >= 10 && length(txt) <= 8000) {//match}

Comment: Bro, hehe, we already meet on here, and thats because Ill not be rude. My project have a validation layer shared between js and c#. All fields have a acronym that determines what pattern will be use to validate it. The layer is working very well, keeping the validation consistent in the client side, the server side, and the database. This layer validation uses only regex to validade, its why Im not doing that (and Im not planning to extend or refactor this layer because my problem is trivial and still fits the layer).
Answer: 1.use this
 var filter = /[\w|\W]*/gim;

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

regex to match everything


Find probability density function

Question: i have a problem with following task:
$X_1,...,X_n$ are independent random variables with normal distribution $N(\mu,\sigma^2)$ with expected value $\mu$ and variance $\sigma^2$,
$$Z=\frac{1}{\sigma^2}\sum_{k=1}^{n}(X_k-\mu)^2$$ And my task is to find it's denisity. After a while I've managed to transform it and see it's Chi-squared distribution. Thanks to wikipedia now I know denisity, but I guess I should make it from scratch maybe using variance or expected value? I would be more than glad for help.
Comment: this question on crossvalidated may be of help: http://stats.stackexchange.com/questions/6104/proving-that-the-squares-of-normal-rvs-is-chi-square-distributed
Comment: See also https://en.wikipedia.org/wiki/Proofs_related_to_chi-squared_distribution.
Answer: Let $Y_k = \dfrac{X_k-\mu}{\sigma}$
Then $Y_1,\ldots , Y_n$ are independent random variables with normal distributions $N(0,1)$ i.e. expected value $0$ and variance $1$, and
$$Z=\sum_{k=1}^{n}Y_k^2$$
which meets the definition of a $\chi^2$-distribution with $n$ degrees of freedom
Comment: Wikipedia gives a derivation at https://en.wikipedia.org/wiki/Proofs_related_to_chi-squared_distribution#Derivation_of_the_pdf_for_k_degrees_of_freedom though it is not trivial
Comment: Yes, I come up with that. Knowing that this is $\chi^2$ -distribution, I can find denisity somewhere in internet. But I suspect it's expected from me to calculate it, which I am unsure how to.

Find probability density function


solve this error: "The type or name 'Collections' does not existe in the namespace 'System'. (Are you missing an assembly or a reference)"?

Question: This is the thing: System.Collections should be available for most of .NET Frameworks, that is, including .NET Standard 2.0, Core, and others.
The code that is failing is using System.Collections;
I have a solution in VS 2019, with 5 projects:
2 of them are for Xamarin.Forms and the Android that goes with it, aiming to tackle Android Pie 9.0
1 of them is a library for Xamarin, same conditions than the previous 2. This is where we can find the error.
2 of them are libraries in .NET Standard 2.0.
I have done a little bit of research and the solution was to target the same framework in all of the projects, however this is not possible as I don't find the target framework for the Xamarin projects (the full 3 of them), and according to MS website the namespace should be available.
Any ideas of how to solve this?
Update: I have tried dotnet restore, but it is not recognized, after further looking, this command is for .NET core, not for standandard
Comment: Did you create a class in a folder or a namespace called Collections?
Comment: one possibility here is that the entire TFM is missing; have you done `dotnet restore` at the command line? did it work?
Comment: no, some projects were created by myself, other ones by colleagues. I don't get why this is not working for me but to another colleagues
Comment: dotnet restore? never heard of it, I will try, thanks
Comment: >dotnet restore
Command "dotnet" is not valid.
Comment: Are you sure you don't have an .NetStandard20 project referencing a .NetStandard21 project. Upward framework references can cause funny errors like that. I now check that first.
Comment: Yes, I have checked that many times, 2 projects in .NET Standard 2.0, and the rest are for Xamarin
Comment: @lria Can you provide some code that having this error message?
Comment: the code is in the using statement, I've already added at the begining
Answer: Well, I did sort it.
dotnet can not be run on VS because it is Standard and not Core, as I said. But I was able to run it from command line.
Then it was not working fully, so I tried to change the target framework in the project that was erroring, put it to 2.1 instead of 2.0, that kind of work. Some of the errors were still there, but this one in particular was gone. My guess is that the library included some nuget packages that needed 2.1, because the libraries that we built, all of them target 2.0.
Then there was some change in the library done by the colleague of mine that was in charge of that part that solved everything. So I guess it was a nuget package the whole problem.
Answer: Install Do select Dotnet Desktop Development from Visual studio installer
If it wont work for time being right click on project --> Manage Nuget Packages --> Install Systems.Collections
Last resort: looks like your Visual Studio is corrupted. Completely uninstall and reinstall.


How to make xcodebuild test recognize classes in the main app target

Question: In my main target, I have a MyClass class. Then I try to access this class in my simple test case.
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "MyClass.h"

@interface TryXcodeBotTests : XCTestCase

@end

@implementation TryXcodeBotTests

- (void)testExample {
    MyClass *object = [[MyClass alloc] init];

    // This is an example of a functional test case.
    XCTAssert(YES, @"Pass");
}

@end

In my test target, I already set the Host Application to my app, and check the Allow testing Host Application APIs. I go to Product > Test in my Xcode. The simulator shows up. The test went well. Great!
BUT!!! The problem is, when I try it with xcodebuild command line, it doesn't work.
This is the command.
/usr/bin/xcodebuild test -scheme TryXcodeBot \
-workspace TryXcodeBot.xcworkspace \
-configuration Release \
-destination 'platform=iOS Simulator,name=iPhone 5s'

This is the output, with errors at the end.
ld: warning: directory not found for option '-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator9.0.sdk/Developer/Library/Frameworks'
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_MyObject", referenced from:
      objc-class-ref in TryXcodeBotTests.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Testing failed:
    "_OBJC_CLASS_$_MyObject", referenced from:
    Linker command failed with exit code 1 (use -v to see invocation)
** TEST FAILED **

The following build commands failed:
    Ld /Users/thongchai/Library/Developer/Xcode/DerivedData/TryXcodeBot-ciwyldvaiganvlcceegjybtnqlto/Build/Intermediates/TryXcodeBot.build/Release-iphonesimulator/TryXcodeBotTests.build/Objects-normal/i386/TryXcodeBotTests normal i386
(1 failure)

I can't find a way to set the test Host Application when using xcodebuild to test. Or do anything to make the test recognize the class in my app file. I know I can manually add MyClass.h to my test target (which it works). But that's not what I want. I want MyClass to only exist in my main app target. Is there any way to do this?
Answer: It turns out I just have to remove -configuration Release in the command. Then it works.
Or use -configuration Debug instead.

Funny. It just come to my mind right after I posted this question
  :facepalm:.


jQuery: Custom function for onclick event on select dropdown

Question: Looking for a way to attach custom onlick event to a select dropdown. By clicking on either of the options a custom function should be called.
My code consists of the following HTML:
<select name="database" id="database">
    <option disabled selected> -- select an option -- </option>
    <option>MySQL database format</option>
    <option>PostgreSQL database format</option>
    <option>Oracle database format</option>
    <option>Other format</option>
</select>

Based on another question (Trying to get a jQuery event to Fire onClick on a select/option form) I created this JS + jQuery + jQueryUI code:
$("#database").selectmenu();
$("#database").change(function() {
    alert("A1");
});

https://jsfiddle.net/1ba470wL/5/
There is something wrong and the function is not being called, where is the problem?
Comment: Your fiddle is broken because `selectmenu()` isn't a standard jQuery method, and you haven't included the library that contains it.
Comment: Uncaught TypeError: $(...).selectmenu is not a function
Comment: Something still is not working there, even outside fiddle and with the correct jQuery UI library
Comment: Without an example of the problem we can't help. Remove the extraneous `selectmenu()` line and your code works fine: https://jsfiddle.net/1ba470wL/4/
Comment: [Selectmenu](https://jqueryui.com/selectmenu/) is a standard UI component in jQuery UI and works in the same example outside fiddle, while the change event doesn't. I imported jQueryUI to the code example: https://jsfiddle.net/1ba470wL/
Comment: Try now, the problem with `selectmenu` is fixed in jsfiddle
Answer: The solution was to change the change event to selectmenuchange, which was caused by jQueryUI handling events differently.
$("#database").selectmenu();
$("#database").on("selectmenuchange",function() {
    alert("A1");
});

Answer: $("#database").selectmenu(); is undefined
https://jsfiddle.net/1ba470wL/2/
Comment: Fixed it, but it was not part of the main problem
Answer: I'm not sure what you're trying to achieve..
$("#database").on("click", function() {
    console.log("custom function");
});

You fiddle is broken since you're missing an external library (the one you're calling via selectmenu())
Comment: I'm trying to detect the event when an option gets selected so another menu gets visible based on what option was selected.
Answer: With the html from your example:
$("#database").on("change", function(){
//Code here
});

Comment: It may be useful to add an explanation of what the code does and why you've done it that way. It often makes it clearer to the questioner and in turn helps your answer get accepted.
Answer: Not sure exactly what you're trying to do.

$("#database").on('change', function() {
 var selected_value = $(this).val();
    alert(selected_value);
});

<select name="database" id="database">
    <option disabled selected> -- select an option -- </option>
    <option value="mysql">MySQL database format</option>
    <option value="postgreSQL">PostgreSQL database format</option>
    <option value="oracle">Oracle database format</option>
    <option value="Other">Other format</option>
</select>
Comment: I need to capture the onclick event, which makes additional form fields visible.
Comment: Then you can get the value of the selected option and do what ever you need to do with it. See the updated snippet.


React update state of component after search through object

Question: I have an object that is outputted from the reactIcons npm package https://www.npmjs.com/package/react-icons I am importing everything from one of the folders with import * as ReactIcons from 'react-icons/fa' I am using sanity studio, I created a text input that takes the value searched and runs a search function that runs a includes on the values from the object I grabbed from the reactIcons fa folder and log's the vales that match. Now I want to take those values and update a react component with useState() Howerver I get the following error Uncaught ReferenceError: setIcon is not defined and SetIcon is the setter function from useState array. Here is my code so far
import React, { useState } from 'react';
import PropTypes from 'prop-types'
import FormField from 'part:@sanity/components/formfields/default'
import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event'
import * as ReactIcons from 'react-icons/fa'

console.log(ReactIcons);

const createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)))

const Example = value => {
  const [icon, setIcon] = useState();

  return (

{icon}

  );
}

const search = value => {
  console.log(value);
    Object.keys(ReactIcons).map(go => {
    if (go.toLowerCase().includes(value) === true){
      console.log(go);
      setIcon(go);
    }
  })
}

class IconPickerCustom extends React.Component{

    static propTypes = {
        value: PropTypes.string,
        onChange: PropTypes.func.isRequired
    };

    render = () =>{
        const {type, value, onChange} = this.props
        return (
          <>
            <FormField label={type.title} description={type.description}>
              <input
                type="text"
                value={value === undefined ? '' : value}
                onChange={event => onChange(createPatchFrom(event.target.value))}
                ref={element => this._inputElement = element}
              />
            </FormField>
            <input
              type="text"
              onChange={event => search(event.target.value)}
            />
            {Object.values(ReactIcons).map(X =>{
              return (
                <>
              <X/>
              </>
              );
            })}
            {console.log(ReactIcons.Fa500Px)}
            <ReactIcons.Fa500Px/>
            <Example/>
          </>
        )
    }
}

export default IconPickerCustom;

Comment: Why are you using a hook when you are using a class component????   Just set and update state as normal and don't use the hook.  https://reactjs.org/docs/state-and-lifecycle.html
Comment: hmm, I don't know why I am. I'm not so familiar with react, I've only played with hooks before so I used them here. Could you give me a rough example.
Answer: React has two types of components, class components and function components (formerly stateless components).   Hooks are used in function components when you realize you need state inside a function component and prefer not to convert it to a class component.
The useState() Hook allows us to add state in a function component.
Class Component
//initialize state
constructor(props) {
    super(props);
    this.state = {foo: bar};
}

//set state
this.setState({foo: baz});

//read state
this.state.foo;

Function Component
(with useState() Hook)
//initialize state
const [icon, setIcon] = useState("myInitialValue");

//set state
setIcon("myNewValue");

//read state
{icon}

That being said, you already have a class component so no need to use hooks here.
class IconPickerCustom extends React.Component{

constructor(props) {
    super(props);
    this.state = { icon: "nothing" };
}

static propTypes = {
    value: PropTypes.string,
    onChange: PropTypes.func.isRequired
};

const createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)));

const search = value => {
    Object.keys(ReactIcons).map(go =>
        ({ go.toLowerCase().includes(value) ?
           this.setState({icon:go}) : null;})
}

render = () =>{
    const {type, value, onChange} = this.props
    return (
      <>
        <FormField label={type.title} description={type.description}>
          <input
            type="text"
            value={value === undefined ? '' : value}
            onChange={event => onChange(createPatchFrom(event.target.value))}
            ref={element => this._inputElement = element}
          />
        </FormField>
        <input
          type="text"
          onChange={event => search(event.target.value)}
        />
        {Object.values(ReactIcons).map(X =>{
          return (
            <>
          <X/>
          </>
          );
        })}
        {console.log(ReactIcons.Fa500Px)}
        <ReactIcons.Fa500Px/>
        <Example/>
      </>
    )
}
}

export default IconPickerCustom;

You are going to want something along those lines.   Let me know if you have any questions.


Marcar checkbox com retornos na DIV

Question: Neste Form:
<input type="checkbox" value="1" data-id=1" name="status_entrega" id="status_entrega">

Atualizado

<input type="checkbox" value="1" data-id=2" name="status_entrega" id="status_entrega">

Atualizado

Tenho o seguinte jQuery:
$('#status_entrega').click(function(){
    var id_pedido = $("#status_entrega").attr("data-id");
    $("#retorno_"+id_pedido).toggle(this.checked);
});

Porém, o primeiro item consigo marcar como checado, o segundo e os demais, não consigo nem marcar... Não retorna a mensagem de atualização. Alguém consegue ajudar?
Atualização:
Conforme ajuda do Sérgio, eu modifiquei, mas preciso que, ao desmarcar, envie também a solicitação de atualização. Segue o codigo atualizado:
$('[name="status_entrega"]').click(function() {
    var id_pedido = $(this).attr("data-id");
    $("#retorno_" + id_pedido).toggle(this.checked);

    $.ajax({
        type: 'post',
        url: '../ajax/getTransacaoOK',
        success: function (response) {

            $("#retorno_" + id_pedido).html("Atualizando...");
            setTimeout(function(){

                $("#retorno_" + id_pedido).html("Atualizado!");

                setTimeout(function(){
                    $("#retorno_" + id_pedido).html("");
                },1000);

            },2000);
        },
    });
});

Answer: Tens IDs duplicados... eles têm de sêr únicos.
Podes usar o name="status_entrega" como seletor e fazer assim:

$('[name="status_entrega"]').click(function() {
    var id_pedido = $(this).attr("data-id");
    $("#retorno_" + id_pedido).toggle(this.checked);
});

    <input type="checkbox" value="1" data-id="1" name="status_entrega" id="status_entrega">

Atualizado

    <input type="checkbox" value="1" data-id="2" name="status_entrega" id="status_entrega">

Atualizado

Comment: Perfeita solução. Obrigado! :)
Comment: @AndréBaill faz sim, só que está escondido. Mas para ficar ainda melhor podias fazer assim: https://jsfiddle.net/m443k17f/
Comment: @AndréBaill `data: {id_pedido: id_pedido}`
Comment: @AndréBaill `data: {id_pedido: id_pedido, estado: this.checked},`
Comment: Eu fiz um ajuste nele, mas quando clicar de volta, ele precisa enviar a ação novamente... exemplo, marquei, enviou ação, desmarquei, enviou ação novamente.... mas ao desmarcar, não envia, atualizei o meu codigo.
Comment: Ok, ai pra eu passar o id do pedido, eu faço dentro do ajax...  data: id_pedido? :)
Comment: Neste caso @Sergio, eu vou enviar 1 se for ativo e 0 ser for inativo, dessa forma, eu preciso passar qual é o valor do checkbox?
Comment: Isto var status_entrega = $("status_entrega").val(); deve resolver né? Porque ai eu pego o valor do checkbox
Comment: Ahh bacana, certo, vou tentar.

Marcar checkbox com retornos na DIV


Why is String Deduplication not standard

Question: I am having a problem with creating 10 million objects from a csv file on import in my application. Doing a heap dump I figured the Out-Of-Memory occurres when reaching around 4.8 million objects.
Researching a solution and looking into how to improve the GC I stumbled upon the VMOption:
<code>-XX:+UseStringDeduplication
</code>
Using this I was able to create 7.8 million objects before Out-Of-Memory occurred, which is an increase of more than 60 %. The heap dump showed, that the strings and the byte[] in the heap where decrease by up to 75 %.
In another stackoverflow answer someone showed similar results in memory usage optimization.
https://stackoverflow.com/a/27953779/10020419
So I am asking myself, why this isn't standard (I am using Java 11)?
The only downsides I read are more like smaller increasing of CPU, because the GC has to work a little more.
Are there any other reasons to not use this as a default?
Comment: Well I guess reading [Why/When you would not want to have Java 8 UseStringDeduplication enabled in JVM?](https://stackoverflow.com/questions/42080648/why-when-you-would-not-want-to-have-java-8-usestringdeduplication-enabled-in-jvm) could be part of the answer. Now, for the "why is is not standard", this will be "opinion-based".. The link asked for the reason to use it and seems better fit SO
Comment: Thanks, I found several questions/answers on stackoverflow, but not this one.
Answer: When asking "why was this language decision made", all we can do is guess or listen to what the language designers have said publicly. I haven't heard any commentary from the developers as to why they did this, so here's a somewhat educated guess.

In most cases, CPU is a more precious resource than memory.
This flag requires the G1 garbage collector, which may not be applicable for some people. If it was on by default, you may come to switch to another GC and find that you now get OOM errors everywhere.

Like I say, without explicit comments from the devs, educated guesses are the next best thing.
Comment: Ok, thank. The question is rather not "why isn't this standard" but rather "can I use this or are there problems I didn't find?" The link provided by AlexH in the comment answers this question.


Subtracting 5 Business days from a given date field in pyspark or hive

Question: I have a need to subtract 5 business days from a data field in a spark data frame.
Below is my sample data.
+-----------+---------------+
|cust_id    |agreement_date |
+-----------+---------------+
|901866745  |2021-01-28     |
|901866746  |2021-01-29     |
|901866747  |2021-02-02     |
|901866748  |2021-02-05     |
+-----------+---------------+

I need to derive another field to this data frame called prcs_strt_dt which is agreement_date - 5 Business days. Expected output is below.
+-----------+---------------+---------------+
|cust_id    |agreement_date |prcs_strt_dt   |
+-----------+---------------+---------------+
|901866745  |2021-01-28     |2021-01-21     |
|901866746  |2021-01-29     |2021-01-22     |
|901866747  |2021-02-02     |2021-01-26     |
|901866748  |2021-02-05     |2021-01-29     |
+-----------+---------------+---------------+

I can use pyspark or hive but the limitation is that I cannot use external libraries.
Can someone help me??
Thanks in advance
Answer: If the agreement_date is a weekday, then subtract 7 days from it.
If it's a Saturday or Sunday, then subtract 5 or 6 days respectively.
To get the weekday from the date, you can use date_format. For date subtractions, use date_sub:
from pyspark.sql.functions import date_format, expr
from pyspark.sql import functions as F

df.withColumn('prcs_strt_dt', F.when(date_format('agreement_date', 'u') == 6, \
    expr("date_sub(agreement_date , 5)"))\
    .when(date_format('agreement_date', 'u') == 7, expr("date_sub(agreement_date , 6)"))\
    .otherwise(expr("date_sub(agreement_date , 7)"))).show()

+---------+--------------+------------+
|  cust_id|agreement_date|prcs_strt_dt|
+---------+--------------+------------+
|901866745|    2021-01-28|  2021-01-21|
|901866746|    2021-01-29|  2021-01-22|
|901866747|    2021-02-02|  2021-01-26|
|901866748|    2021-02-05|  2021-01-29|
|901866748|    2021-02-06|  2021-02-01|
|901866748|    2021-02-07|  2021-02-01|
+---------+--------------+------------+


Solving a differential equation numerically to plot particle path

Question: I'm trying to plot the evolution of a particle in an accretion disk by solving the equation
$$2X\frac{\partial X}{\partial\tau}=V_R(X,\tau)$$
where I have found $V_R$ numerically to be
$$V_R(X_i,\tau_n)=-\frac{3}{2X_i^2\sigma_{i,n}}\bigg[\frac{X_{i+1}\sigma_{i+1,n}-X_{i-1}\sigma_{i-1,n}}{2\Delta X}\bigg]$$
and I have all values of the surface density $\sigma_{i,j}$.
So I assume I need to integrate $V_R$ with respect to time $\tau$ in order to get $X=f(\tau)$
I'm confused when it comes to trying to do this numerically. The first initial condition is $X(0)=\sqrt{0.9}$.
Any hints or help would be greatly appreciated because I've been stuck on this problem for way too long.
Comment: Is $X$ a single variable (as seems to be implied by the first equation) or a vector (as implied by the second)?  If it's a vector, what does $2 X \frac{\partial X}{\partial \tau}$ mean?
Comment: $X$ starts off as a single variable but to solve numerically I consider $X$ to be discrete with values $X_i$, $i=1,2,...,100$ and $X_1=\Delta X=0.02$. Time $\tau$ is written in a similar way, but with much smaller timesteps.
Answer: To solve this numerically you would start by rearranging to get
$$\frac{\partial X}{\partial \tau} = \frac{V_R(X,\tau)}{2X} $$
and then starting with $X(0)$, you find $X(\Delta\tau)$ using:
$$ X(\Delta\tau) = X(0) + \frac{\partial X}{\partial \tau}\Delta\tau $$
and so on
$$ X((n+1)\Delta\tau) = X(n\Delta\tau) + \frac{\partial X}{\partial \tau}\Delta\tau $$
It is important that your $X$ variable be continuous. In other words, don't store it as $i$ or $X_i$, but rather as $X$ (otherwise you may find your particle doesn't move anywhere!). And then when you evaluate $\partial X/\partial\tau$ you can either round $X$ to the nearest $X_i$ or you can interpolate.
Comment: Thanks again @lemon. I got it to work with the following code:
 $$X(i+1) = X(i) + (dt / (2 X(i) ) ) V( round(X(i)/dx),i)$$

Now I've calculated that that when $X_0 = \sqrt{1.1}$, it takes a time of 0.2117 to reach the outer boundary at $X = 2$. I need to write 0.2117 as a function of $X_0$. It seems I have to work the iteration backwards in order to end up with a function of the original $X_0$, but I keep running into problems. Is there any simple way to do this?
Comment: You currently have $X(t)$. Plot $0.2117-t$ (as the $y$-axis) against $X(t)$.
Comment: @AlexM < I forgot to add this to alert you.
Answer: No, you don't want to integrate $V_R$ with respect to $\tau$.  You want to solve the differential equation $2 X \frac{dX}{d\tau} = V_R(X,\tau)$ with initial condition $X(0) = \sqrt{0.9}$.
Unless you have very special requirements, you shouldn't try to re-invent the wheel.  There is lots of good software for numerical solution of differential equations, and you can access it easily through Maple, Matlab, Mathematica etc.
Comment: But is it possible to use a simple Matlab function to solve this when my solutions need to be a vector in order to plot the path the particle traces?

Would the following work: $X^{2}(\tau)=\intop_{0}^{\tau}V_{R}(X,s)ds$, finding this integral for each discrete value of $\tau$?
Comment: No, because $V_R$ depends on the unknown $X$.
Comment: I don't understand what you mean by "my solutions need to be a vector in order to plot the path the particle traces".  Plotting should be a separate issue from finding $X(t)$.


Limit of a sequence with $a_{1}=2, a_{n+1}=\frac{n^{2}-1}{a_{n}}+2$ for $n\geq1$

Question: I have the following sequence: $$(a_{n})_{n\geq1}; a_{1}=2, a_{n+1}=\frac{n^{2}-1}{a_{n}}+2, n\geq1$$
At first exercise calculated the limit of $\frac{a_n}{n}$.I used $n\leq a_n\leq n+1$ and I got the limit $1.$
At the last two exercises I need to calculate $$\lim_{n \to \infty }\frac{\sum_{k=1}^{n}a^{3}_{k}}{n^{4}}$$ and $$\lim_{n \to \infty }\frac{\sum_{k=1}^{n}a^{k}_{k}}{n^{n+1}}$$
I tried to use again the first inequality but I got the limit $\infty$.How to start?
Comment: In my book, it's $n^{n+1}$
Answer: Partial answer:
You certainly do not get infinity for neither of the limits.
Since $1\leq \frac{a_n}{n}\leq 1+\frac{1}{n}$, you have
$$k^3\leq a_k^3\leq k^3(1+\frac{1}{k})^3=(k+1)^3$$
hence
$$\frac{1}{4} n^2 (1 + n)^2=\sum_{k=1}^nk^3\leq\sum_{k=1}^na_k^3\leq\sum_{k=1}^n(k+1)^3=\frac{1}{4} (12 n + 13 n^2 + 6 n^3 + n^4)$$
so that the sum is sandwiched between two polynomials of $n$ of degree $4$, with leading coefficient $\frac{1}{4}$. Hence the first limit is $\frac{1}{4}$.
For the second limit, we have
$$k^k\leq a_k^k\leq k^k(1+\frac{1}{k})^k=(k+1)^k$$
hence
$$\sum_{k=1}^nk^k\leq\sum_{k=1}^na_k^k\leq\sum_{k=1}^n(k+1)^k$$
The r.h.s is bounded above by $n(n+1)^n < (n+1)^{(n+1)}$, so the second limit, if it exists, is at most $e$.
Comment: Thank you for your answer.At the second limit, in my book the right answer is 0.


Inequality of fourier series coefficients

Question: Can someone argue why the inequality must be true for all $2\pi$-periodic integrable functions:
$$ |f(x)| \le \sum_{n\in\mathbb{Z}}|\hat{f(n)}|$$
for almost all $x\in\mathbb{R}$.
I have an intuitive feeling that this statement is true, I als don't think that this statement remains true for all $x \in \mathbb{R}$. Could someone give me a hint on how to proof this? Thank you!
Answer: If $\sum_{k\in\mathbb Z}|\hat f(k)|=\infty $, the result is obviously true. Suppose $\sum_{k\in\mathbb Z}|\hat f(k)|<\infty $.
Define $g(x)=\sum_{m\in\mathbb Z}\hat f(m)e^{2i\pi mx}$. Notice that $g$ is well defined and continuous because the series converges normally (and thus uniformly). You have $$\hat g(k)=\sum_{m\in\mathbb Z}\hat f(m)\int_0^{2\pi}e^{2i\pi mx}e^{-2i\pi kx}=\hat f(k).$$
Therefore, $f=g$ a.e., and thus $$f(x)=\sum_{k\in\mathbb Z}f(k)e^{2i\pi x}\quad a.e.$$
Therefore $$|f(x)|\leq \sum_{k\in\mathbb Z}|\hat f(k)|.$$


Array of string not working

Question: I use a simple array: contentHouseOne[] that contains strings. But in the Do/While loop it isn't working! It seems like the code don't understand that it's a string when a new object is to be created!? It works when I hardcode the string like I show below. Help is preciated! Thanks!
This isn't working:
listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition));

But this works:
 listHouseParts.Add(new HousePart(content, "100x100", newPosition));

EDIT:
Here are some code to declare arrays
string[] contentHouseOne = new string[] { "ruta100x100Red",
                                          "ruta100x100Grey",
                                          "ruta100x100Green",
                                          "ruta100x100Yellow",
                                          "ruta100x100Blue" };

bool[,] occupiedPositions = new bool[500,500];

Here are some code to set all grid positions to false
for (int i = 0; i < gridCol; i++)
    for (int ii = 0; ii < gridRow; ii++)
        occupiedPositions[i, ii] = false;

And finally here are the code that I have the problem
int i = 0;
do
{
    Vector2 newPosition = NewRandomPosition;
    if (occupiedPositions[(int)newPosition.X, (int)newPosition.Y] == false)
    {
        listHouseParts.Add(new HousePart(content,
                                         contentHouseOne[i], newPosition));
        occupiedPositions[(int)newPosition.X, (int)newPosition.Y] = true;
        i++;
    }
}
while (i <= 5);

Comment: Please show a short but complete program demonstrating the problem. You haven't given *nearly* enough information about what's going wrong.
Comment: What does `contentHouseOne[]` contain and what does `listHouseParts` do with `HousePart`?
Comment: the way i am understanding,you are using listbox ok then you have to cast array to listbox
Comment: What happens? Do you get an exception when it runs, or is there a compilation error?
Comment: how did you declared "listHouseParts"?
Comment: I get a index out of range exeption
Answer: Your string array includes five elements:
string[] contentHouseOne = new string[] { "ruta100x100Red",
                                          "ruta100x100Grey",
                                          "ruta100x100Green",
                                          "ruta100x100Yellow",
                                          "ruta100x100Blue" };

But your while loop ends if your running variable i is greater than 5
while (i <= 5);

which causes a IndexOutOfBounds exception on contentHouseOne, because the 6th element at index 5 isn't defined.
You should change your while condition to (i < 5).
Comment: Nice catch. P.s., @3D-kreativ: If this is the error you get, it would have been even easier to explain if you had included it. Please provide any such info along with your code next time.
Comment: Thanks for the answer! (i <= 5) was the problem, now it's working. But your suggestion to use a loop, would that really work!? What if a position in the occupiedPosition is true, then there will be no new object added to the listHouseParts!? Thats why I used Do/While. But If you have a better solution your welcome with a new suggestion
Comment: @3D-kreativ no of course, you're right,  while loop is just fine. Monday morning, bad time for creative thinking :-)
Answer: Try this so atleast you know if its empty or not
    HousePart housePart = new HousePart();
    housePart.Content = content;

    if (!string.IsNullOrEmpty(contentHouseOne[i]))
        housePart.ContentHouseOne = contentHouseOne[i];
    else
        housePart.ContentHouseOne = string.Empty;

    housePart.NewPosition = newPosition;

    listHouseParts.Add(housePart);

Comment: What happens when you step through with the debugger, and do you check all your variables, be a little more defensive

Array of string not working


Cannot ping to localhost into CentOS

Question: I'm connecting to my server (Centos 7) with ssh and I try to ping to localhost: ping 127.0.0.1 but doesn't work:
ping 127.0.0.1

PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
^C
--- 127.0.0.1 ping statistics ---
78 packets transmitted, 0 received, 100% packet loss, time 76999ms

Here my files. networks:
default 0.0.0.0
loopback 127.0.0.0
link-local 169.254.0.0

hosts:
# nameserver config
# IPv4
127.0.0.1 localhost.localdomain localhost
1xx.xxx.xxx.xxx  server
#
# IPv6
::1     ip6-localhost ip6-loopback
...

lo route:
DEVICE=lo
IPADDR=127.0.0.1
NETMASK=255.0.0.0
NETWORK=127.0.0.0
# If you're having problems with gated making 127.0.0.0/8 a martian,
# you can change this to something else (255.255.255.255, for example)
BROADCAST=127.255.255.255
ONBOOT=yes
NAME=loopback

I need make a ping! What I can do?
Comment: Check routes, firewall, iptables ? Do you have a resolv.conf ? If no, please create one for testing purpose at least
Comment: try setting it to 0 with echo 0 > path_to_file. Guess its the cause
Comment: maybe bring up local interface : ifup lo ?
Comment: Is currently UP :/
Comment: Also check if `/proc/sys/net/ipv4/icmp_echo_ignore_all` is set to `0` if it exists.
Comment: iptables and firewall are disabled. I have a resolv.conf file. Lets to check routes.
Comment: Is set to 1? What I have to do?
Comment: I've added the lo route file into question.
Comment: Like this: `echo "0" >  /proc/sys/net/ipv4/icmp_echo_ignore_all` IT WORKS! Thanks!
Comment: And for set this permanently? @Nico you are the best!
Comment: No problem. This file is saying : Should I answer to ICMP Requests ? with 0 you answer : "Do not ignore all", if sets to 1 you say "Yes, ignore everything". Hope I'm clear enough. Next time, try a google research first with "centos cannot ping 127.0.0.1" with the 5 first links, you should be able to solve and understand the problem ;) You can answer your own question, or I can do it if you prefer
Answer: After checking that local interface is up (ifup lo0 or similar).
Check for routes, firewall or iptables problem.
Here it was a problem from the file located here /proc/sys/net/ipv4/icmp_echo_ignore_all
When set to 1 : There is no response to ICMP Requests, so ping will not work.
When set to 0 : Replies to ICMP Requests are enable.
Check if sets to 1. If so, set it to 0 by using this command :
echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all
Now, your machine replies to ping.
Comment: Did you accidently switch 0 and 1 in the first part of your answer?

Cannot ping to localhost into CentOS


Hotmail blocks company emails, when hyperlink is inserted in the message body

Question: I received the following results:
==========================================================
Summary of Results
==========================================================
SPF check:          pass
DomainKeys check:   neutral
DKIM check:         neutral
Sender-ID check:    pass
SpamAssassin check: ham

Mail sent from my company email to Hotmail recipients goes to "junk" if message body contains link to my company web, examples:

http://www.mycompanydomain.com
www.mycompanydomain.com

but mycompanydomain.com is OK and delivered to inbox well!
I think Hotmail filters/blacklists my full domain name as a keyword and therefore this issue has nothing to do with rest antiSPAM stuff checks, like SPF, DomainKeys, DKIM, Sender-ID, SpamAssassin - all these checks are OK and set well!
Answer: You're messages are probably considered borderline spam without the links, and the addition of links pushes them over the threshold.
Hotmail uses a variety of heuristics to determine if a message is spam. The main ones are:

SPF - Do you have a SPF record properly configured for your domain?
DKIM - Do you have DKIM properly configured for your domain and outgoing mail is signed?
SenderScore.org - Check your IP(s) (note that this works on a feedback loop, the more e-mail addresses you send to, where the majority of your messages are considered ham, the better your score; if you conduct testing, use only one destination testing address to minimize the effect on your score; similarly try not to send spam to a ton of addresses or your reputation will be trashed).
Common content scoring (similar to SpamAssassin if you know how it works) - If you're sending marketing, automated, or similar e-mails on a regular basis, run your messages through SpamAssassin and see what it thinks. Hotmail doesn't use SA to my knowledge, but most systems work similarly enough that you'll get a good idea of where you stand.

SPF, DKIM, and SpamAssassin can all be checked quickly be sending a test message to a verifier.
This Canonical Question answer the more generic question of How to send emails and avoid them being classified as spam?
Some of the information in this one may be useful, as it speaks to the other side of the coin: Fighting Spam - What can I do as an: Email Administrator, Domain Owner, or User?
Comment: DKIM did not pass. SA returned Ham, but what are the details of that result??
Comment: Mail sent from my company email to hotmail recipients goes to "junk" if message body contains link to my company web, examples:

1) "http://www.mycompanydomain.com" 2) "www.mycompanydomain.com"

but "mycompanydomain.com" is ok and delivered to inbox well!

I think Hotmail filters/blacklists my full domain name as a keyword and therefore this issue has nothing to do with rest antiSPAM stuff checks, like SPF, DomainKeys, DKIM, Sender-ID, SpamAssassin - all these checks are ok and set well!

Please advise!
Comment: "SA ham" doesn't mean that it is not passed or "bad", as well as DKIM result "neutral"


php encode and decode row if know salt (not use mcrypt)

Question: Good day.
Tell me please how encode/decode row if i know word and salt, for ex.:
$word = 'row=test&row2=link';
$salt = '42b&df';

I would like encode $word and decode code (get $word) if i know $salt.
How make it?
P.S.: not use mcrypt.
Comment: You would also need the key. `mcrypt` deals with encryption, not hashing, perhaps you mean `crypt`?
Answer: <?php
$word = 'row=test&row2=link';
$key = "42b&df";

$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $word, MCRYPT_MODE_CBC, md5(md5($key))));

echo $encoded.'
';

$decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encoded), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

echo $decoded;
?>


Code to output a number of columns based on search criteria

Question: My sister has a worksheet at work with the first five columns containing patient's information, and then columns have the heading of each date for the whole month. She needs non-technical operators to be able to filter the information to show only records which have appointments for that day, plus two days either side.
Currently, she manually filters the column of the date she wants to remove the "blanks" for that date, which shows only the patients who have appointments for that day, hides the other columns to show just that date and then prints the information out for the date.
What is the best way to automate this process?
I've played with several different methods like copying it over to a new sheet or autohiding data but I'm having trouble displaying a list of patients with no blank in the field for that specific day (i.e. - they have an appointment!)
Comment: Thanks for the reply... is it possible to upload a copy of the worksheet? Sorry for the confusion, tricky to explain. Ideally, I would have a button which initiated a popup to select a date, which then outputs the correct information for the user to keep it very simple. Thanks
Comment: I've uploaded it here: https://www.wetransfer.com/downloads/aa316f620334b911dbbcea3eea9b94b720131221214714/d410dacbffd7fbb2a73c57961dc1c0b520131221214714/f87269
Answer: I doubt this will be a proper answer, but might give you some ideas – and won't fit in a comment:

I'd suggest Columns 2,3,4,5, & 6 are stored elsewhere and merely referenced for current purposes. This is partly because I'm guessing there are a lot more patients (ie details) than required for any one month. So an index would be useful (say just a few characters rather than maybe typing around 20-30 at present - and the risk of errors), but Name & DOB would serve. Use this in your existing sheet (which I have called Month) to retrieve the appropriate details for ColumnsB:F for the relevant month. By the looks of it the likes of "Tany M/W CAF Meeting" may best be entered manually.
I'd suggest top aligning all cells (may help with matching one column to another, given your data).
In a new sheet put labels such as Name & DOB, B/D, C & V details, Contact Details, delivery details, M/W, OVERDUE, overdue, TODAY, PENDING, pending in Row2. (I suggest no highlighting for the first six so as not to clash with red, amber, pale blue, green, dark green for the five days.)
I say Row 2 so that in Row1 there is room for a date. This could be constructed with a (rather horrible) formula such as:
=VLOOKUP(WEEKDAY(DATE(O2,O1,I1),3),DofWeek,2,0)&", "&TEXT(DATE(O2,O1,I1),"dd mmmm yyyy")

where manual entry is in I1 (just the day of the month), the month in say O1 (just the month number) and the year in say O2. The intent it that only those three cells are ever adjusted on the 'extra' sheet (and two of the three only rarely). This allows, for safety, protecting the sheet after only unlocking just the three cells. DofWeek is a named range to convert 0 to Monday etc. I think it is important that the relevant date of the selection is very evident.
5.  In G4 put:
=INDEX(Month!$G$2:$AK$6,MATCH($A4,Month!$A$2:$A$6,0),$I$1-2)

and copy across to K4. Then copy all five cells down as far as required.
6.  Optionally, in order to be able to hide details that appear on sheet Month that are not relevant for the 5-day view, you might add:
=COUNTIF(G4:K4,"<>0")

in L4 and copy that down to suit.
7.  Row3 I deliberately left blank so that the body can be filtered without the little arrows obscuring other information (ie select Row3 and down to suit before applying a filter). Filtering for ColumnL for not - (I chose an Accounting format for the main body of cells – so that results are 'discrete' dashes rather than 0s).
Snags with this include:

The need to change the Month number when appropriate. This could be driven from the computer's clock but I'd suggest best not to (eg for flexibility). Note that a month such as 13 would work but might be confusing if the Year cell has not been updated.
Perhaps the main problem is uncertainty of how far 'down' is sufficient for as far as required. However many cells are preloaded with formulae there is always a risk that one month that won't be enough. But this could be countered with a check to compare the number of entries on the two sheets.
Based on one month at a time, will not give a 5-day view at the start and end of each month (but will show warning that the 5-day period is not fully populated with the relevant data). This could be addressed by duplicating the last two days of each month as though the start of the next.
Formatting is not transferred with INDEX/MATCH.

I have assumed that at the end of each month sheet Month will be archived before being wiped clean of data, ready for the following month. All data entry is in sheet Month, though hopefully the data in B:F can be collected from elsewhere via the index field.
Comment: +1 for including analysis


Method for integrating $\int_{-\infty}^\infty x e^{\frac{-x^2}{2}} dx$?

Question: As part of a proof on deriving the mean and variance of the standard normal distribution I came across the following integral -
$$\int_{-\infty}^\infty x e^{\frac{-x^2}{2}} dx$$
which integrates to
$$-e^{\frac{-x^2}{2}}\mid_{-\infty}^\infty$$
I don't know what method is being used to perform this integration?
Comment: You're missing a minus sign (not that it matters for the result). One just uses the fact that $$\frac{d}{dx} e^{-x^2/2} = -xe^{-x^2/2}.$$
Comment: It takes a bit of practice, of course, but after a while, yes, that is obvious. Depending on the amount of practice, the border where things are obvious is at different degrees of complication, but for such integrands, it doesn't take long.
Comment: It is of the form $\int f^\prime f$. Derive $x\mapsto e^{-x^2/2}$ to see why.
Comment: here is one i made earlier http://math.stackexchange.com/questions/685046/gaussian-like-integral/685066#685066
Comment: @DanielFischer Would you consider it obvious that the initial function integrates to that equation though? It's obvious when you have $F(x)$ that it differentiates to $f(x)$ but given just the $f(x)$ it doesn't seem obvious to me that it integrates to $F(x)$...maybe I just need to get used to seeing more of them...
Comment: Guess and check method.
Answer: This is $u$-substitution.  If you let $u=-\frac{x^2}{2}$, then $du=-x\,dx$.  The integral becomes
$$
\int -e^u\, du.
$$
Comment: Just noticed when I tried u-substition that I had left out the $2$ in the denominator when writing down the formula, no wonder it didn't work for me.
Answer: Using the change of variables $u=x^2/2$ and $du=xdx$
$$
\int xe^{-x^2/2} dx = \int e^{-u} du = -e^{-u}
$$
And re-substituting you get the desired result.
Answer: Let's consider, for nonnegative integer $k$, $$I(k) = \int_{x=0}^\infty f(k;x) \, dx, \quad f(k;x) = x^k e^{-x^2/2}.$$  For $k = 0$, we have $I(0) = \sqrt{\pi/2}$, which we can prove in a number of ways, such as considering a double integral of the form $$\int_{x=0}^\infty \int_{y=0}^\infty e^{-(x^2+y^2)/2} \, dy \, dx.$$  For $k = 1$, we have by the substitution $$u = x^2/2, \quad du = x \, dx$$ the result $$I(1) = \int_{u=0}^\infty e^{-u} \, du = \lim_{L \to \infty} \left[ -e^{-u} \right]_{u=0}^L = 0 - (-1) = 1.$$  For general $k$, we use integration by parts with the choice $u = x^{k-1}$, $du = (k-1)x^{k-2} \, dx$, $dv = x e^{-x^2/2} \, dx$, $v = -e^{-x^2/2}$, the choice of $v$ being informed by our earlier calculation of $I(1)$.  Then $$\begin{align*} I(k) &= \lim_{L \to \infty} \left[ -x^{k-1} e^{-x^2/2} \right]_{x=0}^L + (k-1) \int_{x=0}^\infty x^{k-2} e^{-x^2/2} \, dx \\ &= (k-1) I(k-2).\end{align*}$$  Therefore, we have $$\begin{align*} I(2n) &= \sqrt{\frac{\pi}{2}} \prod_{j=1}^n (2j-1) = \sqrt{\frac{\pi}{2}} \frac{(2n)!}{2^n n!}, \\ I(2n+1) &= \prod_{j=1}^n 2j = 2^n n!. \end{align*}$$  Since these are finite, we can now consider symmetry:  for even $k = 2n$, $f(2n;x) = f(2n;-x)$, hence $$\int_{x=-\infty}^\infty f(2n;x) \, dx = 2I(2n).$$  For odd $k = 2n+1$, $f(2n+1;x) = -f(2n+1;x)$ and $$\int_{x=-\infty}^\infty f(2n+1;x) \, dx = 0.$$
Comment: It is interesting that in your proof of the general setting, there is no care taken for the existence of the general integral for various $k$'s that you admonished me on for my solution. You use the symmetry of the integrand just like I did. Hmm, I wonder why there is this glaring instance of a double standard. :-)
Comment: I'm not sure why you wrote that:  the above clearly shows the explicit evaluation of the integral over $[0,\infty)$ for positive integers $k$, which **does** show existence.  I wrote, "Since these are finite, we can now consider symmetry."  Your answer (which I upvoted, btw) did not show that the integral over half the real line was convergent.
Comment: I am referring to the second line where you define $I(k)$. To be rigorous to the standard set before, you have to show the existence of the limit to infinity even before your write down the improper integral expression.
Comment: No, that is not correct.  Of course you can write down $I(k)$:  the integrand $f(k;x)$ has no singularities and the limiting behavior of $f(k;x)$ at $\infty$ is not in question.  As I explained in my comment on your answer, $\lim_{x \to \infty} f(k;x) = 0$ but that in itself does not prove $\int_0^\infty f(k;x) \, dx$ exists.  Convergence of the *integrand* to zero is a necessary but not sufficient condition for convergence of the *integral*.
Comment: I am confused. Your last sentence is exactly my point, and is what I am protesting about your proof being not rigorous. However one proves the integrability, you have NOT done it. Are you saying, to be rigorous, you do not need to prove the existence of the integral $\int_0^\infty f(k,x)dx$ before you define $I(k)=\int_0^\infty f(k,x)dx$? If you can, what is then the basis on which you criticized my solution earlier?
Comment: Maybe you misunderstood my previous phrase "the limit to infinity". I am not referring to the limit of $f(k,x)$ but the limit of the integral $\lim_{y\rightarrow\infty}\int_0^y f(k,x)dx$. You need to show the existence of this limit.
Comment: My proof is completely rigorous, whether or not you recognize it to be so.  Until you can precisely articulate what it is that you find deficient in my answer, I have nothing more to add to this comment thread.
Comment: That is one obstinate response. Let me quote your very own comment not long ago to articulate what I find deficient in your solution "one can't just claim that the integral exists--we have to SHOW it formally." You have not shown the existence of the integrals formally. You failed to uphold the standard that you hold others to. That is what I called double standard. It is a bit ironic, isn't it?
Comment: You are more than welcome to fill in the gaps that you perceive to exist in my exposition for yourself.  I encourage you to post exactly what you think is missing.  Unless you can furnish some actual mathematics instead of continuing to make vague claims and accusations, there is nothing else I can say. That is all.
Answer: Use the fact the integrand is an odd function to see the integral on the negative $x$ axis cancels that on the positive $x$ axis and the integral vanishes. This way, you do not even need to be able to analytically integrate the indefinite integral.
Comment: You have to be very careful with this but this is a reasonable approach.
Comment: @Hansen:  that is precisely what we need to be careful about.  One can't just claim that the integral exists--we have to *show* it formally.  An integrand can have $\lim_{x\to\infty} f(x) = 0$ but its improper integral over $[0,\infty)$ is not bounded; e.g., $f(x) = 1/x$.  So "rapid decay" needs to be rigorously explained.  That was all that was meant.
Comment: I think convergence is what Cameron was referring to. Of course you're right that the integral exists, but it seems to me that the easiest way to show that is to do the u substitution. So you're not really saving yourself any work.
Comment: It is a way (straightforward) to get that all odd moments are zero (although not exactly what the OP asked).
Comment: @CameronWilliams: What is there to be especially careful with? The integral exists because of the rapid decay of the integrand at infinity.
Comment: The integral is improper at both $+\infty$ and $-\infty$ and the limits must be taken individually so the odd-ness of the integrand doesn't help much on the surface (but there are ways around this).
Comment: You guys are right about being careful in rigor. @CameronWilliams: The integral is proper at infinity. Because say, $xe^{-x^2}<\frac{1}{x^4}$ or $x^2 > 4 \ln x$ for large enough $x$. The latter is integrable at infinity.


How to check if current page is a group entity?

Question: Im using drupal 7 and group module
I am trying to run some code only if the current page is a group.
here is my code
<?php
$arg = arg(0);
$arg1 = arg(1);
global $user;
if($arg ='group' && is_numeric($arg1)) {
    $group = group_load($arg1);
    if($group->getMember($user->uid)) {
       print ('user is member');
    };
};
?>

If this is placed on a group page it will print user is member if the current user is a member. If the current user isn't a member it will not show anything. Which is what it is supposed to do.
If I navigate to a none group page I get an error 'Error: Call to a member function getMember()',  but the if statement should prevent this?
How do I check if the current page is a group entity?
Thanks
Edit
I wanted to return true if a group page and user is a member of the group.
Using menu_get_object by Jaypan I used the code below to show. Im checking if page is group if so loading the group then checking if the user is a member of the group.
if (!empty(menu_get_object('group')))
   {
   $group = group_load(arg(1));
   if($group->getMember($user->uid)) {
       return TRUE;
    }
}

Answer: You can get the object for the current page in Drupal 7 using menu_get_object().
if ($group == menu_get_object('group')) {
  // do something with $group
}

Comment: Hi, Thanks for replying but this doesn't work and I don't know the syntax to make it work. I think it isn't working because $group has already been loaded as a group, what I want to do is check that the path is a group before loading $group. So I need to get type from menu_get_object and check if it is of type group, if menu_get_object([0]) = 'group', or menu_get_object($type) = 'group'. But I do't know how to structure menu_get_object.
Comment: I managed to do it by checking if menu_get_object('group') is set first.
Comment: I'm not sure why you think this doesn't work. It only loads $group when `menu_get_object('group')` returns a group. If you are on a group page, the `if()` conditional is entered. If you are not on a group page, the `if()` conditional is not entered. And when on a group page, this will load the group for you, so you don't need to call `node_load()` after the fact, as `menu_get_object('group')` will have already returned the group on group pages.
Comment: I put , nothing happened, I checked log it said group not defined, this was on a group page.
Comment: In Drupal, printing often doesn't print to the screen. Try `drupal_set_message('Here');`.
Answer: checking if page is group if so loading the group then checking if the user is a member of the group.
if (!empty(menu_get_object('group')))
   {
   $group = group_load(arg(1));
   if($group->getMember($user->uid)) {
       return TRUE;
    }
}


For $x,y,z∈ℝ^{+}$,without using Hölder's inequality prove that $\frac{x}{\sqrt{x^2+8yz}}+\frac{y}{\sqrt{y^2+8xz}}+\frac{z}{\sqrt{z^2+8xy}}\geq1$.

Question:
For $x,y,z∈ℝ^{+}$, prove that $\frac{x}{\sqrt{x^2+8yz}}+\frac{y}{\sqrt{y^2+8xz}}+\frac{z}{\sqrt{z^2+8xy}}\geq1$.

In this question solution used Hölder's inequality, but I am looking a solution without using Hölder's inequality.
I first tried using AM-GM inequality but not results clearly.
Then I used Cauchy-Schwarz inequality which gave,
$${(\sum_{cyc}x²)(\sum_{cyc}\frac{1}{x²+8yz})\geq(\sum_{cyc}\frac{x}{\sqrt{x²+8yz}})}^2$$
But I couldn't solve it. Can anyone help me out?
Comment: this is a very well-known inequality. One nice solution is to prove:
$$\dfrac{x}{\sqrt{x^2+8yz}}\geq \dfrac{x^a}{x^a+y^a+z^a}$$
for some suitable exponent $a.$ IIRC, $a = \frac 43$ works.
Comment: Can you prove for $a=\frac{4}{3}$. Coz I'm not able to.
Answer: Okay, just to get this question removed from the unanswered queue - we are looking for an exponent $a$ such that:
$$\dfrac{x}{\sqrt{x^2+8yz}}\geq\dfrac{x^a}{x^a+y^a+z^a}\iff x^a+y^a+z^a\geq x^{a-1}\sqrt{x^2+8yz}.$$
But note that:
$$(x^a+y^a+z^a)^2\geq (x^a+2(yz)^{\frac a2})^2=x^{2a} + 4x^a(yz)^{\frac a2}+4(yz)^a\geq x^{2a} + 8x^{\frac a2}(yz)^{\frac{3a}{4}}.$$
For $a = \frac 43$ then, this is just $$x^{\frac 83} + 8x^{\frac 23}yz = x^{\frac 13}\sqrt{x^2+8yz} = x^{a-1}\sqrt{x^2+8yz}$$
as desired.
Comment: This is the so-called isolated fudging.
Answer: By C-S twice and by AM-GM again we obtain:
$$\sum_{cyc}\frac{x}{\sqrt{x^2+8yz}}=\sum_{cyc}\frac{x^2}{x\sqrt{x^2+8yz}}\geq\frac{(x+y+z)^2}{\sum\limits_{cyc}x\sqrt{x^2+8yz}}\geq$$
$$\geq\frac{(x+y+z)^2}{\sqrt{(x+y+z)\sum\limits_{cyc}x(x^2+8yz)}}=\sqrt{\frac{(x+y+z)^3}{\sum\limits_{cyc}(x^3+8xyz)}}\geq1.$$
Answer: Another way.
By AM-GM, C-S and AM-GM again we obtain:$$\sum_{cyc}\frac{x}{\sqrt{x^2+8yz}}=\sum_{cyc}\frac{2x(x+y+z)}{2\sqrt{(x+y+z)^2(x^2+8yz)}}\geq\sum_{cyc}\frac{2x(x+y+z)}{(x+y+z)^2+x^2+8yz}=$$
$$=\sum_{cyc}\frac{2x^2(x+y+z)}{x(x+y+z)^2+x^3+8xyz}\geq\frac{2(x+y+z)^3}{\sum\limits_{cyc}(x(x+y+z)^2+x^3+8xyz}=$$
$$=\frac{2(x+y+z)^3}{(x+y+z)^3+x^3+y^3+z^3+24xyz}\geq1.$$


Alinhamento vertical de texto com CSS

Question:
Como posso alinhar esse texto "Adote o ritmo da natureza: o segredo dela é a paciência", verticalmente e horizontalmente dentro do campo branco?
Usei o seguinte código:

       adote o ritmo da natuza: o segredo dela é a paciência.

Ralph Waldo Emerson

ul{
    position: relative;
    width: 100%;
    height: auto;
    list-style: none;
    margin: 0;
    padding: 0;
}
ul li{
    position: relative;
    width: 309px;
    height: 260px;
    background: #f3f2f1;
    float:left;
    margin: 0 19px 19px 0;

}
ul li  a{
    width: 257px;
    height: 170px;
    background: #fff;
    display: block;
    margin: 25px 0 0 25px;
    text-decoration: none;
    text-transform: uppercase;
    text-align:center;
    color: #f37021;
    font-family: Futura;
    font-size: 15px;
}
 ul li h2{
    font-family: Georgia;
    font-size: 14px;
    color: #111111;
    font-style: italic;
    text-align: center;
    margin: 0;
}

Answer: 1. Alinhando o texto no meio da célula
Crie uma div com a classe vertical contendo o texto. Depois use:
.vertical {
    vertical-align: middle;
    display: table-cell;
}

2. Rotacionando o Texto
Crie uma div com a classe vertical contendo o texto. Depois use:
.vertical {
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  -o-transform: rotate(-90deg); /* opcional: Opera agora usa -webkit */
  transform: rotate(-90deg);

  -webkit-transform-origin: 50% 50%;
  -moz-transform-origin: 50% 50%;
  -ms-transform-origin: 50% 50%;
  -o-transform-origin: 50% 50%; /* opcional: Opera agora usa -webkit */
  transform-origin: 50% 50%;

  /* Use se você quer que apareça para o IE8. */
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

Comment: `-ms-`: a Microsoft removeu grande parte dos prefixos. `-o-`: agora o Opera usa Webkit. Já falei por aqui do [prefixfree](http://leaverou.github.io/prefixfree/) mas recomendo o [autoprefixer](https://github.com/ai/autoprefixer), ainda mais para respostas.
Comment: Testei seu código no autoprefixer, nas opções padrão: ele deixou os prefixos `-ms-` e `-webkit-`. *Grande parte...*
Comment: Cigano Morrison Mendez, na verdade o que eu preciso é alinhar verticalmente e horizontalmente no espaço branco.
Comment: Expandi a resposta.
Comment: Alguém já perguntou no meta sobre o que fazer com propriedades prefixadas? IMHO nunca uso: quem irá copiar nossos códigos - e tenha certeza que farão - irão usar prefixos que nunca serão necessários. Exemplo? `-o-`.
Comment: `-o-` é do Opera, não? Sei lá. Resolvi colocar um CSS completo.
Comment: Editei colocando suas observações. Vou deixar por desencargo.
Answer: Porque não usar line-height ?
ul li{
    position: relative;
    width: 309px;
    height: 260px;
    background: #f3f2f1;
    float:left;
    margin: 0 19px 19px 0;
    line-height: 260px;
}

Para mim funciona bem.
Perdão pela gafe, não tinha visto que o texto possui espaçamento e que já tinha tentado o line-height.
Answer: No seu caso, basta trocar de display:block para display: grid; e acrescentar o align-items: center; no ul li e a

ul{
    position: relative;
    width: 100%;
    height: auto;
    list-style: none;
    margin: 0;
    padding: 0;
}
ul li{
    position: relative;
    width: 309px;
    height: 260px;
    background: #f3f2f1;
    float:left;
    margin: 0 19px 19px 0;

}
ul li  a{
    width: 257px;
    height: 170px;
    background: #fff;
    display: grid;
    align-items: center;
    margin: 25px 0 0 25px;
    text-decoration: none;
    text-transform: uppercase;
    text-align:center;
    color: #f37021;
    font-family: Futura;
    font-size: 15px;
}
 ul li h2{
    font-family: Georgia;
    font-size: 14px;
    color: #111111;
    font-style: italic;
    text-align: center;
    margin: 0;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

             adote o ritmo da natuza: o segredo dela é a paciência.

Ralph Waldo Emerson

Alinhamento vertical de texto com CSS


Is there a "float flow"?

Question: When I have some simple elements floated like in this example: http://jsfiddle.net/2zpqyLt0/

div {
  width: 100px;
  height: 100px;
}
.element1 {
  background: rgb(211, 206, 61);
  float: left;
}
.element2 {
  background: rgb(85, 66, 54);
  float: left;
}
.element3 {
  background: rgb(247, 120, 37);
  float: left;
}

They are stacked next to each other. As far as I understand, when you "float" an element, it's out of the document's normal flow. Elements that are (still) in the document normal flow don't know this element exists, so they can overlap with it. But what about OTHER floated elements? It seems they know each other and are in some sort of "floated flow", else if they didn't, they'd all overlap and end up at the left edge. Is there a term for this "float type of flow" where floated elements, for some reason know that they exist?
Comment: I'm not sure why some have marked the question as "non-programming", it's a conceptual question on how CSS works in the background...so it's a programming question.
Comment: You need to read up on the float property. https://css-tricks.com/all-about-floats/
Comment: I guess what you are looking for is `position`ing. Using `position: absolute`, you can achieve what you want.
Answer:
Elements that are (still) in the document normal flow don't know this element exists, so they can overlap with it. But what about OTHER floated elements?

This behavior is defined in the visual formatting model documentation.
More specifically, sections 9.5 and 9.5.1 discuss this:

9 Visual formatting model - 9.5 Floats
A float is a box that is shifted to the left or right on the current line. The most interesting characteristic of a float (or "floated" or "floating" box) is that content may flow along its side (or be prohibited from doing so by the 'clear' property). Content flows down the right side of a left-floated box and down the left side of a right-floated box. The following is an introduction to float positioning and content flow; the exact rules governing float behavior are given in the description of the 'float' property.
A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the outer top of the floated box is aligned with the top of the current line box.
Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

In other words, even though a float is not in the document flow, floating element(s) will still be positioned to the outer edge of other floating element.
See the exact rules governing the float behavior in section 9.5.1.
Answer: I'm not an expert on the internals, but this doesn't seem too surprising to me.
After all, text and other content already flows around the floated element. So if you have a second floated element, it seems only natural that it, too, flows around the first one.
It just so happens that this results in multiple elements floated side-by-side.
Comment: Given the sample example above, if I put float: left only to .element1, element2 will overlap and "disappear". It doesn't wrap around it, it just overlaps it. Yet, this doesn't happen with something like a  element which will wrap around it. Why is that?
Comment: @daremkd: Like this answer states, it's the text that is wrapping around the float. The actual bounding box does not. See http://stackoverflow.com/questions/30634020/why-the-text-or-images-are-not-placed-behind-a-floating-element/30634087#30634087

Is there a "float flow"?


What is the variance of the estimator in ordinary least squares with correlated residuals

Question: If we assumed that $y \sim N(X\beta,S)$ where
S=
$\sigma^2\begin{bmatrix}
1 & \rho & \rho &...\\
\rho & 1 & \rho &...\\
\rho & \rho & 1 &...\\
\rho & \rho & \rho & ...\\
... & ... & ... & ...\\
\end{bmatrix}$
Then the OLS approximation of $\beta$ would be the same as in the independent case:
$\hat{\beta} = (X'X)^{-1}X'y$.
However, the distribution of $\hat{\beta}$ seems to become harder to determine.
The variance of $\hat{\beta}$ would be $Var((X'X)^{-1}X'y)$ = $(X'X)^{-1}X'SX(X'X)^{-1}$. How can I further simplify this?
Comment: Don't use OLS, because it's the wrong model: instead use [Generalized Least Squares](https://en.wikipedia.org/wiki/Generalized_least_squares).
Answer: (On a side note, this is a case of correlated errors -residuals are always correlated).
You are considering a very specific form of correlation, equicorrelation. Then note that
$$S=\sigma^2[(1-\rho)I+\rho\mathbf i \mathbf i']$$
where $I$ is the identity matrix and $\mathbf i = (1,...,1)'$.
It follows that
$$\text{Var}\left(\hat \beta_{OLS}\mid X\right) = \sigma^2(X'X)^{-1}X'\big[(1-\rho)I_p+\rho\mathbf i \mathbf i'\big]X(X'X)^{-1}$$
$$=(1-\rho)\sigma^2(X'X)^{-1}X'X(X'X)^{-1} + \rho\sigma^2(X'X)^{-1}X'\mathbf i \mathbf i'X(X'X)^{-1}$$
$$=(1-\rho)\sigma^2(X'X)^{-1} + \rho\sigma^2\Big[(X'X)^{-1}X'\mathbf i\Big] \Big[(X'X)^{-1}X'\mathbf i\Big]'$$
Further, on can show that, if the regressor matrix includes a constant term, then
$$\Big[(X'X)^{-1}X'\mathbf i\Big] = (1, \mathbf 0)'$$
so we arrive at
$$\text{Var}\left(\hat \beta_{OLS}\mid X\right) = (1-\rho)\sigma^2(X'X)^{-1} + \rho\sigma^2\cdot \left[ \begin{matrix} 1 & \mathbf 0 \\ \mathbf 0 & \mathbf 0 \end{matrix} \right]$$


Pyinstaller Placing Images On Separate File Problem? How Do I Fix This?

Question: I am trying to place my images on a seperate file then my  exe BECAUSE I have alot of images and I dont want the person scrolling throw thousands of images just to find the exe

I dont know if I am missing something on my .spec

this is what I did I made a folder for my images and added them and then the exe is outside my image folders but whats happening is its not detecting the images on that folder *am I messing something on my .spec file?

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(['tower.py'],
             pathex=['C:\\Users\\Habib\\Desktop\\AllMyGames\\TowerD'],
             binaries=[],
             datas=['C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image'],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='tower',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False )

it will end up just saying
FAILED TO EXECUTE SCRIPT

Comment: Two things: 1. If you have a new question, you should create a new question rather than edit an old one (and if you don't think the old question is worthwhile for other people, you can delete it). 2. This seems a bit trivial to put such a large bounty on.
Comment: Your question does not provide enough details for us to accurately reproduce your problem. Please update your question to include the exact folder structure and commands you are using before you get this error.
Comment: Your spec file works fine for me, through `pyinstaller tower.spec` and then running `dist/tower`. So if it's not working for you, you'll have to provide more details for us to help.
Answer: Two problems I see:

Your datas string contain backslashes (escape character for python strings), resulting in an invalid string for a path.
The datas property is incorrectly structured.

From the docs:

The list of data files is a list of tuples. Each tuple has two values, both of which must be strings:

The first string specifies the file or files as they are in this system now.
The second specifies the name of the folder to contain the files at run-time.

https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-data-files
So, assuming your project root is C:\Users\Habib\Desktop\AllMyGames\TowerD, change
# Change this line
datas=['C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image']
# To this
datas=[('dist/image', 'image')]

And I think it will work.
Comment: is there like a update command that I can put in the cmd because the problem is still there and says "failed to execute script"
Comment: What command, exactly, are you trying to run?
Comment: I am trying to run the exe of my game
Answer: As @Multihunter said that the path is not escaped so the script is failing, here is the simplest solution to it
replace
datas=['C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image']

with
datas=[r'C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image']

prepending the r to your string will not escape any characters and your path will be as you wanted it to be.
See this for reference
Answer: I would recomend you to check if your image is in ico format, if it isnt
use :https://icoconvert.com
If this still does not work re do the procces but in your cmd promp write 'pyinstaller -icon "Your .ico file" and your project.py'


Header function asks the user for the file to be opened rather than automatically?

Question: I am trying to redirect the user to simply another phtml file when they logout. I am using the function header like so:
header('Location: ../../Site/index.phtml');
exit;

In reality when that runs, the user is greeted if they want the file to be opened and they're not automatically re-directed. Like shown in the image. How can I get them to redirected please without the dialog (automatically). I am running a localhost.
Many thanks
Image of the output
Comment: 1) are you 100% sure nothing is output before coming there? 2) use an absolute URL not a relative one 3) what does happen when you try to enter directly the URL in your browser? Same symptoms or not? If same, it means the problem is not in your PHP but just that this page is not served probably with the appropriate `Content-Type: text/html` header.
Comment: Thank you it's fixed now. Sorry again for the stupidity, it's those tiny mistakes. I used an absolute URL for anyone having this issue and it works. Thank you again
Answer: The problem is likely due to the fact that .phtml is a very old PHP file extension (from PHP 2, circa 1997). We're now on PHP 7, and as such, most web servers don't even have logic built in to handle the .phtml extension.
Because your webserver (in this case localhost) doesn't know what to do with the file, it falls back and lets your browser handle it. Because your browser doesn't have an associated default file handler for the extension, it prompts you for an action (assuming a user would be more familiar with a file extension).
The easiest way to resolve this would be to simply switch to the .php extension, as I'm yet to encounter a server that is unable to handle the main PHP extension.
If you are still having issues opening the file, ensure that you specify the type of the file with header("Content-Type: text/html"), which is the default for PHP. This shouldn't be necessary, but will ensure that your browser correctly parses the file as a PHP file.
Hope this helps! :)
Comment: You're correct because when I changed it to .php, it worked correctly. But why would they provide the functionality of .phtml on phpstorm if it is very old? What can you replace .phtml with?


SSH Connections Refused When Routing Through Xinetd

Question: I'm trying to route SSH connections from port 22 on the SSH machine to port 2222 on the xinetd machine, I get a connection refused error every time I try to connect through port 2222 on the xinetd machine.
The SSH machine is running CentOS 5.4 and the xinetd machine is also running CentOS 5.4.
Xinetd service:
service 2222
{
socket_type = stream
port = 2222
wait = no
user = root
redirect = 10.10.10.10 22
}

And the Terminal output on my Mac:
Mac mini:~ Justin$ ssh -v email@example.com -p 2222
OpenSSH_5.2p1, OpenSSL 0.9.8l 5 Nov 2009
debug1: Reading configuration data /etc/ssh_config
debug1: Connecting to sub.mydomain.com [xxx.22.xxx.29] port 2222.
debug1: connect to address xxx.22.xxx.29 port 2222: Connection refused
ssh: connect to host sub.mydomain.com port 2222: Connection refused
Mac mini:~ Justin$

Any ideas?
Thanks :)
Answer: Can you connect to 10.10.10.10:2222 from the xinetd machine? If you can, check you're not denying packets on the xinetd machine in the FORWARD chain of IPTables
Comment: I am trying to connect to 10.10.10.10:22 in the SSH machine and be able to access that from the xinetd machine from port 2222 since the xinetd machine also runs SSH, I would like to be able to connect to the xinetd machine on port 2222 to access 10.10.10.10:22


Detectable System problem

Question: My question is about a proof :
We have the system
$$dx/dt=Ax\\
y=Cx
.$$
If $y(t)=0$ and $(A,C)$ is detectable how can i prove that $\lim_{t\to \infty} x(t) =0$ ?
Comment: Do you mean that $y(t) = 0$ for all $t>t_0$?
Answer: Detectability is often defined via the implication
$$
y(t) \equiv 0  \Rightarrow \lim_{t \to \infty} x(t) = 0.
$$
But anyways. Let's say that a pair $(A,C)$ is detectable if every unobservable eigenvalue of $A$ is in the left-hand side part of the plane. By contraposition, assume that $y(t) \equiv 0$ but $x(t)$ does not tend to zero as $t\to\infty$. Then
$$
\exists \lambda \in \mathbb{C}, \text{ with } Re(\lambda) \ge 0, \quad
\exists  x_0 \in \mathbb{R}^n, \text{ with } x_0 \not = 0 \, : \quad
x(t) = e^{\lambda t} x_0 \ \text{ and }  \ y(t) \equiv 0.
$$
This implies
$$
A e^{\lambda t} x_0 = A x(t) = \dot{x}(t) = \lambda e^{\lambda t} x_0
$$
and
$$
0 \equiv y(t) = C x(t) = e^{\lambda t} C x_0 .
$$
Evaluating the first at $t=0$ gives
$
A x_0 = \lambda x_0
$.
while the second implies $C x_0 = 0$. This means that
$$
\exists \lambda \in \mathbb{C}, \text{ with } Re(\lambda) \ge 0, \quad
\exists  x_0 \in \mathbb{R}^n, \text{ with } x_0 \not = 0 \, : \quad
\begin{bmatrix}
\begin{array}{c}
\lambda I - A \\
C
\end{array}
\end{bmatrix} x_0 = 0 .
$$
which (in view of the Popov-Belevitch-Hautus test) proves the claim.
Answer: Hint: Start with
$y=Cx$
and differentiate
$$\dot{y}=C\dot{x}=CAx$$
$$\ddot{y} = CA^2x$$
$$\vdots $$
$$\dfrac{d^{n-1}}{dt^{n-1}}y = CA^{n-1}x$$
By this procedure, we get $n$ equations that we can rewrite in the following way
$$\begin{bmatrix}y\\ \dot{y}\\ \ddot{y}\\ \vdots \\ \dfrac{d^{n-1}}{dt^{n-1}}y\end{bmatrix} = \begin{bmatrix}C\\CA\\CA^2\\ \vdots \\CA^{n-1} \end{bmatrix}x.$$
From $y(t)=0$ for all $t>t_0$ we know that the right-hand side is a zero vector. If the system $(A, C)$ is controllable we are done. But if we only have a detectable system (Definition: A linear system (continuous or discrete) is detectable if all unstable
modes are observable. Source) then we will need to remove the unobservable states (they are asymptotically stable) from the system and do the same procedure with the reduced system. It will be observable such that we can use the previous procedure.

Detectable System problem


When can I adjust partition sized in Leopard?

Question: The version of Disk Utility that comes with Mac OS X 10.5 will let you resize existing partitions on a partitioned drive -- some of the time.  What determines if it will let you adjust partition sizes or not?
Answer: Fragmentation would probably be the biggest problem. For a newly formatted partition, data will be added (more or less) from start to finish, however after a time fragmentation will leave blocks of data all over the disk. DiskUtil cannot resize a volume to a size less than the last block in use on the partition.
To defragment your partition, thereby moving all the data to the front of the disk, you can use a program like iDefrag. Alternatively you can simulate the process by copying all your data off to another disk, reformating the volume, then copying it back. You can use a program like SuperDuper or Carbon Copy Cloner to help with this process.
There may also be restrictions on resizing the startup volume. To avoid those, boot from the install DVD.
Comment: What partition format are they, GPT, MBR or Apple Partition Map ?
Comment: HFS+ can be defragged, in fact there's lots of options including iDefrag (http://www.coriolis-systems.com/iDefrag.php)
Comment: @Chopper3, I never knew about iDefrag. Thanks for the suggestion, i've updated my answer
Comment: I could adjust the sizes on the partitions on my startup drive, but not on an external drive (which had two HFS+ partitions).  This is what led me to believe some subtlety is involved.
Comment: I was just trying this again on another computer.  Trying to resize it failed.  I ran some tools (which weren't entirely clear), but it did seem to be fragmented.  I optimised it with Disk Warrior.  Then I tried to resize it again ... and it almost worked.  At the end, Disk Utility said it had lost its connection with an internal tool that it works with and needed to quit -- leaving me with an unmounted volume in who knows what sort of health.  Glad I backed up first!