Find the number of binary sequences with a certain property.

Question: I'm looking for the formula giving $a_n=|\{b\in \{0,1\}^*:\#_0(b)+2\#_1(b)\leq n\}|$, where $\#_x(a)$ is the number of times that $x$ occurs in the sequence $a$. I noticed that if we rename 0 to 1 and 1 to 2 in the sequence, then we have a recurrence $a_n=a_{n-1}+P_{1,2}(n)$, where $P_{x,y}(n)$ is the number of different ways you can write $n$ as a sum of $x$'s and $y$'s, assuming we distinguish between $1+2$ and $2+1$. What else can I do?
Comment: Correct, I forgot about the condition, sorry. As to $\{0,1\}^*$, I do mean exactly that. It's supposed to be a sequence made up of any number of 0's and 1's.
Answer: After finding the first few values $a_0=1, a_1=2, a_2=4, a_3=7$, look in the OEIS. It is sequence A000071 with a different offset. Thus, $a_n=F_{n+3}-1$ with recursion $a_n=a_{n-1}+a_{n-2}+1$. This comes from looking at any sequence $b\in \{0,1\}^*$, where if it ends in $0$ the rest is counted by $a_{n-1}$, if it ends in $1$ the rest is counted by $a_{n-2}$, or else it is the empty sequence and counted once.
Comment: Of course: that's one of my favourite tricks and I forgot it!
Comment: So the empty sequence is contained in such a set too?
Comment: @Joaid Yes, that is what the "*" means. If the "+" was used, then no.


Finding start time and end time in a column

Question: I have a data set that has employees clocking in and out. It looks like this (note two entries per employee):
Employee    Date   Time
Emp1       1/1/16  06:00
Emp1       1/1/16  13:00
Emp2       1/1/16  09:00
Emp2       1/1/16  17:00
Emp3       1/1/16  11:00
Emp3       1/1/16  18:00

I want to get the data to look like this:
Employee   Date   Start   End
Emp1       1/1/16 06:00   13:00
Emp2       1/1/16 09:00   17:00
Emp3       1/1/16 11:00   18:00

I would like to get it into a data frame format so that I can do some calculations.
I currently have tried
df['start'] = np.where((df['employee']==df['employee']&df['date']==df['date']),df['time'].min())

I also tried:
df.groupby(['employee','date]['time'].max()

How do I get two columns out of one?
Comment: I would recommend to merge `Date` and `Time` into one column as `DateTime`. That would greatly simplify your work.
Comment: If I merged the date and time together, what would I do then?
Comment: Why not `df.groupby(['Employee', 'Date']).agg([min, max])`?
Comment: @JohnGalt see my answer below. I also think that's what needs to be done. But I believe first you need to convert the `Date` and `Time` columns to datetime objects. Looks like they are string now and `min` / `max` doesn't work as intended with string date
Answer: I would recommend to merge Date and Time into one column as DateTime. That would greatly simplify your work. You can do something like this:
df['DateTime']=pd.to_datetime(df['Date']+" "+df['Time'])
df.groupby('Employee')['DateTime'].agg([min, max])

There are other options depending the content of your data. If you know that all the entries will be on the same day you can simply do:
# First convert Date and Time columns to DateTime type
df['Date'] = pd.to_datetime(df['Date']).dt.date
df['Time'] = pd.to_datetime(df['Time']).dt.time
df.groupby('Employee').agg([min, max])

no need to create a DateTime column in this case.
If you want to know Start End times per each day you can do:
# First convert Date and Time columns to DateTime type
df['Date'] = pd.to_datetime(df['Date']).dt.date
df['Time'] = pd.to_datetime(df['Time']).dt.time
df.groupby(['Employee','Date'])['Time'].agg([min, max])

Comment: I tried it at it worked! Thank you! Now, I want the 'employee' to show up in every row. I need to merge this data frame into another data frame.
Comment: Not exactly sure if that's what you are asking but try this: `grouped=df.groupby(['Employee','Date'])['Time'].agg([min, max])` then `grouped.reset_index()`
Comment: It did not work, but I will do some more research. I think it might just be a limitation on the groupby. If I cannot find anything, I will ask another question. Thank you again!
Comment: I found out that .reset_index does work. you have to do the following grouped=df.groupby(['Employee','Date'])['Time'].agg([min, max]).reset_index()  I tried assigning it based on the grouped and it did not work.


Sample Variance in Principal Components Analysis

Question: I was reading this Why is the eigenvector of a covariance matrix equal to a principal component?. And in the top answer, the poster mentions that if the covariance matrix of the original data points $x_i$ was Σ, the variance of the new data points is just $u^TΣu$. I'm not sure why this is the case. Could someone enlighten me?
Answer: I Suppose your data set consists of N vectors, each of length T. Let's denote them $\vec{x}_i$, (i=1, ..., N). The new data set consists of $\vec{y}_i$ (i=1, ..., N), $\vec{y}_i = \sum_{k=1}^N p_{ik} \vec{x}_k$.
Then the covariance matrix of the new data set has elements
\begin{eqnarray*}
C_{ij} &=& {1 \over T^{2/\alpha}} \vec{y}_i \cdot \vec{y}_j \\
&=& {1 \over T^{2/\alpha}} (\sum_{k=1}^N p_{ik} \vec{x}_k) \cdot (\sum_{l=1}^N p_{jl} \vec{x}_l) \\
&=& \sum_{k=1}^N \sum_{l=1}^N p_{ik} p_{jl} C'_{kl} \\
C &=& P C' P^T
\end{eqnarray*}
where P is the matrix with components $p_{ik}$ and C' is the covariance matrix of $\vec{x}_i$.


Identifying root cause of very poor Random Forest model

Question: I've been working on building a random forest model using h2o.ai in R for climate data. I know that there is some issue, either with my understanding of randomforest, code or dataset. However, I'm not sure exactly what is causing my model to have a very high MSE and low percent variance explained. My apologies in advance if I've overlooked something very simple. I have spent much time reading and testing but haven't improved.
So far I've tried: adjusting the parameters, reducing number of correlated predictors, checking formulas and input data for outliers, normality. Based on what I've researched random forest has been used for similar data in the past. I am using 70 rows in total with a 0.7 split. The entire dataset I've created is 12M rows and to create this subset I have taken the mean for 70 regions. I have tested on the entire dataset with no significant change.  Here is my code, header and current results:
##Code##
#Check data
head(dNBR_model)
#summary(dNBR_model)

#correlation matrix
corNBR <- cor(dNBR_model)
dNBRcor <- cor.mtest(dNBR_model, conf.level = 0.95)

corrplot(corNBR, p.mat = dNBRcor$p, type = "upper", order = "hclust", insig='blank', addCoef.col ='black', tl.col = "black", tl.srt = 45)

#Run RF model
set.seed(561)
dNBR_split <- initial_split(dNBR_model, prop = .7)
dNBR_train <- training(dNBR_split)
dNBR_test <- testing(dNBR_split)

y <- "dNBR"
x <- setdiff(names(dNBR_train), y)

#initialize h2o
h2o.init(max_mem_size='50G')

#convert train to h2o
train.h2o <- as.h2o(dNBR_train)
dNBR_test.h2o <- as.h2o(dNBR_test)

testDRF <- h2o.randomForest(x, y, ntrees = 500, max_depth = 15, min_rows = 1, mtries = 7, nbins = 20, sample_rate = 0.75000, training_frame = train.h2o, validation_frame = dNBR_test.h2o)

testperf <- h2o.performance(testDRF)
summary(testDRF)

#percent variance explained
VE = ((1 - h2o.mse(testDRF))/(h2o.var(train.h2o$dNBR)))*100
print(VE)

RMSE = h2o.mse(testDRF) %>% sqrt()
PRMSE = (RMSE/(mean(dNBR_test$dNBR)))*100
print(PRMSE)

h2o.varimp_plot(testDRF)
varimp <- h2o.varimp(testDRF)

h2o.residual_analysis_plot(model = testDRF, newdata = dNBR_test.h2o)

##Results##
** Reported on validation data. **

MSE:  4034.157
RMSE:  63.51502
MAE:  47.38234
RMSLE:  0.1174528
Mean Residual Deviance :  4034.157

% variance explained: -167.545

##Header##
Comment: Overfitting is a thought, but the fact that you have such poor performance even in-sample suggests another culprit. Overfitting leads to poor out-of-sample performance, but kind of the whole point is that overfitting leads to an in-sample performance that does not generalize, yet your in-sample performance is worse than that of a model that predicts $\bar y$ every time, as I discuss [here](https://stats.stackexchange.com/a/609621/247274). This is hardly the sign of a model that has detected coincidences in the data and fit to them; the model cannot even do that much!
Comment: I think your question remains legitimate: why can't this model fit in-sample at least as well as a model that has no features?
Comment: Welcome to Cross Validated! 1) How do you calculate the percent of variance explained? Do you know the math or at least the software command? 2) When you say that you have 70 rows, do you mean that you have 70 observations in the model, from which you allocation 70% to training and 30% to testing? When you write that you "have tested on the entire dataset with no significant change," do you mean that you have applied your pipeline to all 12-million observations?
Comment: To clarify 1) I've calculated percent variance explained as 1 - MSE/var(y)  * 100 I couldn't find a command to do this in h2o so I had to write it. 3) Yes, this model has 70 observations with 70% training, 30% testing. Yes, I also tried with all 12-million observations.
Comment: Next, how is your in-sample performance? // If 1-MSE/var(y) < 0, do you see what that says about MSE/var(y)?
Comment: ```MSE:  4421.057
RMSE:  66.49103
MAE:  52.36736
RMSLE:  0.139077
Mean Residual Deviance :  4421.057```
Comment: What about in-sample percent of variance explained?
Comment: in-sample is %VE is -79.849 and out is -167.545 (I think i had this mislabeled above) I know that it should not be negative
Comment: My model is overfitting random noise in the predictor variables?
Comment: Thank you Dave, just checked out that post. It's back to the drawing board with this data. I've realized that this model just has terrible performance.
Comment: This is why I'm even more confused, when I checked Spearman's rank correlation between y and a few predictors it showed a significant correlation. So some relationship does exist within the data
Comment: This will likely be very hard for us to help you with, since we don't have your data...
Comment: I think I ended up finding the issue! It looks like I typed my coding in wrong for % variance explained. I tried the exact same data, with similar parameters in the original randomforest r package. I noticed that this package and h2o reported similar MSE but not %VE. In randomforest they calculated pseudo r2 as 1 - mse / Var(y) whereas I had to type it in manually as h2o does not calculate it. Up above, I had input the foruma as: ```((1 - h2o.mse(testDRF))/(h2o.var(train.h2o$dNBR)))*100``` and I changed it to ```(1 - (MSE)/(var(dNBR)))*100``` I get 20.08 %VE in RF and 24.82%VE in DRF h2o.
Answer: (In the comments, I see you think it solved, so this is more general advice.)
To identify the root cause of a poor model, you should start by getting a baseline model to compare against.
As you are using H2O, that is very easy, as you can just swap h2o.randomForest with, say,  h2o.glm (for generalized linear model). You could also try h2o.deeplearning for a neural net, but using a linear model as a baseline is often good as it is quick, and the defaults are good.
So if the results are equally bad, the data or how it is loaded becomes the suspect. If the glm is much better, the way you are using randomForest becomes suspect.
With H2O, you have H2O Flow: open a web browser at http://localhost:54321/ and you can see the models and data you have loaded in, and you can then explore and analyze it.
Another thing, which also came up in the comments, is that if you are overfitting you should be seeing good scores when evaluating on your training data. If you don't then I'd be suspicious of the data again.
E.g. with this data, the very best training model score you could hope for is 0.33.
x1,x2,y
1,2,A
2,3,A
1,2,B
2,3,B
1,2,C
2,3,C

This kind of thing can happen if the data has been loaded badly, e.g. it thought the data was csv, but it was actually semi-colon separated. Again, viewing the data in H2O Flow can confirm if this has happened.
Comment: Thank you very much Darren! This is very helpful I had no idea H2O Flow even existed.


Use Canvas as style of Button

Question: Hello,                                                                              At First I want to say sorry that my English is not the best.
In my Android Project, I have a Canvas Shaped View.
My Question is.
Is it possible to use the Canvas shaped View as style of a Button?
Comment: Yes. You can http://stackoverflow.com/questions/19349155/how-do-i-add-a-button-to-canvas-without-letting-the-button-resize
Comment: This links to an answer for java.awt.Button using FlowLayout as a solution. Both do not exist in Android, so the link is probably not helpful in this case.
Answer: You could just use the view like a button by setting an OnClickListener on it. No need to use a dedicated Button object.
Comment: Glad I could help. Please consider accepting this as an answer to your question.

Use Canvas as style of Button


where can i find an uncompressed video recording from iPhone 3G/3GS/4

Question: I'm experimenting with video processing and I'm looking for uncompressed video frames from iPhone. It is possible to record them since iOs 4.0 by dumping a buffer from api to the file..
Google didn't help..
Anybody? Where can I find such videos to download, or perhaps there is an app for that?
Answer: You can't find what's not possible.
The iPhone 4 video camera can generate roughly 83 megabytes of uncompressed RGB data per second (1280 * 720 * 30 * 3).  The file system doesn't have that much write bandwidth by maybe over an order of magnitude difference, so you either have to rapidly compress the video data, skip frames, or only record a small portion of each frame.
Comment: Good point. but if I could skip frames & rapidly compress like 5-10 frames into png or pcx a second?


Feature : Flag for currently online user

Question: Feature Request
I am thinking it would be good feature if there is a green flag to indicate currently online user, at-least it would help while using the chat room.
Comment: @BabyinMagento that could become super spammy. There's the discussion chat for this I reckon that's enough. People here are volunteers not online support so I disagree with the email notifications system.
Comment: If this were implemented then we would have to send @Marius money for the burn-in on his screen.
Comment: Also if we tag any user name in comment or in answer and if user don't visit site for 1 or 2 days, it should send an email to users account.
Comment: @RaphaelatDigitalPianism you are absolutely right, i completely agree, why i thought this idea is , if one user asked question before 1 or 2 months & if someone posted an answer with how to  find solution ,  using that idea if the user solved the problem, that op should post an answer for that,  so that it will be helpfull for other community members & save their time in future. but once they get idea, they will never visit site again.
Comment: This question is not specific to the Magento StackExchange, but would apply to the entire network and I'm sure it would've been requested before
Answer: It has been asked before you can find the details here: Is there a way to identify whether users are online or not?
Basically, SE is not a social network it's a programming Q&A website, there's no real need for this feature on the website.
Comment: i love the word **SE is not a social network**..:)


Can't Install MariaDB - Dependency Error?

Question: I'm running Ubuntu 14.04 on a Digital Ocean VM. I'm trying to install MariaDB 10.1. When doing so, I get the following error:
Setting up mariadb-server-10.1 (10.1.8+maria-1~trusty) ...
dpkg: error processing package mariadb-server-10.1 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mariadb-server:
 mariadb-server depends on mariadb-server-10.1 (= 10.1.8+maria-1~trusty); however:
  Package mariadb-server-10.1 is not configured yet.

dpkg: error processing package mariadb-server (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
     Errors were encountered while processing:
 mariadb-server-10.1
 mariadb-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

Here is what I've tried to fix this:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mariadb-server

AND
restarting the machine
I was searching Stack Exchange and other Linux forms for a while and I cannot figure out what is causing this. I appreciate any help that could be offered!
UPDATE: Here is the output of apt-get install -f:
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up mariadb-server-10.1 (10.1.8+maria-1~trusty) ...
dpkg: error processing package mariadb-server-10.1 (--configure):
 subprocess installed post-installation script returned error exit status 1
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                dpkg: dependency problems prevent configuration of mariadb-server:
 mariadb-server depends on mariadb-server-10.1 (= 10.1.8+maria-1~trusty); however:
  Package mariadb-server-10.1 is not configured yet.

dpkg: error processing package mariadb-server (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mariadb-server-10.1
 mariadb-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

Comment: Did you ever find a solution to this?
Comment: Run `sudo apt-get install -f` and post the output.
Comment: @MichaelHampton I pasted the info in the updated question. I looked at the output before, it's not very useful.
Comment: Why is this question still here on serverfault or not closed?
Answer: Found this in log:
[ERROR] /usr/sbin/mysqld: unknown variable log_slow_queries=/var/log/mysql/mysql-slow.log'
So I commented out
conf.d/local.cnf
#log_slow_queries=/var/log/mysql/mysql-slow.log'

And installation finally ends succesfully.
Comment: where is the log file?
Comment: Thanks a lot, this was exactly it, preventing me to upgrade from jessie to stretch
Comment: also was a reason for me.
Answer: Try backing up all files in /var/lib/mysql somewhere. Delete them all and then execute mysql_install_db.
My problem came from removing mysqld and replacing it with mariadb and trying to keep the database files. All other methods failed for me.
Answer: Your system has problems running the (post)configure script of the mariadb-server-10.1 package.
First, try to clean the apt cache using apt-get clean and to reinstall the package (please note apt-get autoclean only partially clean the cache).
If that fails, you had to use dpkg -i mariadb-server-10.1 and/or dpkg-reconfigure mariadb-server-10.1 to give a more in-depth looking at the specific error.
Answer: sudo shutdown -r now

I know it sounds crazy that rebooting the machine solved the problem on linux, but I doublechecked. However I'm working in my Vagrant machine, not sure for Digital Ocean.
System:

Debian 7,
mysql installed from dotdeb with a working database,
updated MariaDB apt sources and key added,
install mariadb-server-10.1 which ended with the same error.

After rebooting everything worked, including the DB now served by MariaDB.
Answer: Refer link below:
https://unix.stackexchange.com/questions/249530/mariadb-dependency-problems-leaving-unconfigured
Main>
Install everything from fresh: Add the following to your /etc/apt/sources.list file:
deb [arch=amd64,i386] http://ftp.utexas.edu/mariadb/repo/10.1/debian jessie main
deb-src http://ftp.utexas.edu/mariadb/repo/10.1/debian jessie main

Answer: I ended up installing mariadb-server on another pi and moved the dependencies I was missing over.
All the dependencies I was missing were in /etc/mysql
After i did that it installed normally.


shepard diagram for high dimension data

Question: I went through this website https://www.displayr.com/goodness-of-fit-in-mds-and-t-sne-with-shepard-diagrams/ for shepard diagram.
Right now I have a 20 dimensional data with 85 samples, I used some dimension reduction methods to get a 2*85 data. And I want to use shepard diagram to assess goodness-of-fit of my dimension reduction. Then what is the value on horizontal axis and vertical axis? Right now I can only think about 85 diagrams, in each diagram, the horizontal axis is the original distance between sample i and other samples. But what if I want to include 85 samples in 1 diagram?
Comment: Neat, I didn't know the term "Shepard diagram" for the domain and image distances of a map.
Answer: Each data point in the Shepard diagram represets a pair of points $(x_i,x_j)$ in your data set. In your case with $n=85$ points, there are $85\cdot(85-1)\,/\,2=3570$ pairs. For each pair, you compute two distances, the distance in the original space $d_{orig}=d(x_i,x_j)$ and the distance in the transformed 2D space $d_{trans}=d(f(x_i), f(x_j))$, where $f$ denotes the mapping from nD to 2D.
The horizontal axis is $d_{orig}$ and the vertical axis $d_{trans}$.

shepard diagram for high dimension data


What are the numbers (calculated by the given expression) called?

Question: The numbers calculated by the expression:
$$ T(n) = \frac{n(n + 1)}{2} $$
are called Triangular numbers.
What are the numbers (calculated by the expression below) called?
$$ T(n) = \frac{n(n - 1)}{2} $$
Do they have any name at all?
Comment: Those are exactly the same numbers, just shifted, so that would still be the triangular numbers.
Comment: A bit late $$T(n+1) = \frac{(n+1)(n +1 - 1)}{2}=\frac{(n+1)(n)}{2}$$
Comment: Thank you, I was suspecting they may be called as "anti triangular numbers" or something like that. I thought they name may differ because those numbers describe the number of entries in the triangular matrix with and without the diagonal. EDIT: if I think about it, well there is no reason to call them differently even thou their connection to the matrices.
Answer: They're still triangular numbers. Shift by $1$ like so: $n\mapsto n-1$.


Can I do "Local" System calls using query?

Question: I'm currently on a host(A), connecting to a MSSQL database on server(B).
When I do a System call, such as
EXEC xp_cmdshell 'Systeminfo' GO

from within MS SQL 2008 it always returns me system information from the client(A) I'm currently running my SQL management tool on.
Is there a possibility to run System calls that will return me information from the server(B)?
Comment: On which SQL Server instance are you connected finally? It will return its information
Comment: I am using an SQL manager from my client to connect to the instance hosted on my server, Your suggestion made me realize I would get more information if I shut down the instance on my client.
Apparently that  EXEC will automatically try to connect to localhost and if it's not live it will try to turn it on.
Answer: I have since asking this question rebooted, and tried all the steps again:
1. Turn off local server
2. Connect to external server
3. Turn on XP_CMDSHELL command for the external server using
 -- To allow advanced options to be changed.
 EXEC sp_configure 'show advanced options', 1;
 GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO

And then just run
EXEC xp_cmdshell 'Systeminfo';
GO

Weird that it works now,because I couldn't get it to work past weeks.


Multiple keys per value

Question: Is it possible to assign multiple keys per value in a Python dictionary. One possible solution is to assign value to each key:
dict = {'k1':'v1', 'k2':'v1', 'k3':'v1', 'k4':'v2'}

but this is not memory efficient since my data file is > 2 GB. Otherwise you could make a dictionary of dictionary keys:
key_dic = {'k1':'k1', 'k2':'k1', 'k3':'k1', 'k4':'k4'}
dict = {'k1':'v1', 'k4':'v2'}
main_key = key_dict['k2']
value = dict[main_key]

This is also very time and effort consuming because I have to go through whole dictionary/file twice. Is there any other easy and inbuilt Python solution?
Note: my dictionary values are not simple string (as in the question 'v1', 'v2') rather complex objects (contains different other dictionary/list etc. and not possible to pickle them)
Note: the question seems similar as How can I use both a key and an index for the same dictionary value?
 But I am not looking for ordered/indexed dictionary and I am looking for other efficient solutions (if any) other then the two mentioned in this question.
Comment: Values in python are not necessarily duplicated in python, even if using multiple keys to refer to them.
Comment: You are unlikely to find a solution better than your first one.  Just put multiple keys in the dictionary.  Why is this not good enough?
Comment: As I said in question the file is very large so putting same values multiple time need lot of memory.
Comment: The value won't use up extra memory unless you recreate it every time.  See the answer from  @Useless.
Comment: @MartijnPieters - oh I missed this point I think I should do more test  now I remember i,j=0, 0; id(i)==id(j); True :)
Comment: this is were pointers would come in handy ... _explicit is better than implicit_
Comment: @moooeeeep Heavens, no. That reflects a fundamental misunderstanding of the Python object model. You expect things to work this way because they always work this way. Python *does* reflect "explicit is better than implicit" - by expecting you to be explicit when you want the *other* semantics (i.e. value semantics). You do this e.g. by using the `copy` module, or by otherwise writing code that forces creation of a new object with the same value.
Comment: @KarlKnechtel I am used to have a higher degree of explicitness imposed by the language itself. I mean, Python implicitly uses the pointer-like object reference model.
Comment: @moooeeeep that's nonsense. You have to choose an object model. C++ just-as-"implicitly" uses the value object model.
Comment: @KarlKnechtel it requires you to specify the exact type value/pointer/reference every time you want to use an object. Couldn't be more explicit, I think.
Comment: @moooeeeep that's a **completely** different issue. Manifest typing has absolutely nothing to do with value vs. reference semantics, and anyway isn't "explicit" in a sense that Pythonistas consider remotely meaningful.
Answer: What type are the values?
dict = {'k1':MyClass(1), 'k2':MyClass(1)}

will give duplicate value objects, but
v1 = MyClass(1)
dict = {'k1':v1, 'k2':v1}

results in both keys referring to the same actual object.
In the original question, your values are strings: even though you're declaring the same string twice, I think they'll be interned to the same object in that case

NB. if you're not sure whether you've ended up with duplicates, you can find out like so:
if dict['k1'] is dict['k2']:
    print("good: k1 and k2 refer to the same instance")
else:
    print("bad: k1 and k2 refer to different instances")

(is check thanks to J.F.Sebastian, replacing id())
Comment: you could use `obj1 is obj2` to test object identity instead of `id(obj1) == id(obj2)`
Comment: @d.putto - in that case make sure you're storing the same _instance_ with each key, not a duplicate instance with the same contents (as per my first two examples).  If unsure, confirm with `is`
Comment: type doesn't matter. You shouldn't rely on how Python treats some immutable objects. If you need the same object; just provide it (as in `v1` example)
Comment: dictionary values are not simple string rather complex object (contains different other dictionary/list etc.)
Comment: I agree you _shouldn't_, just wanted to check whether the OP was already getting automagical interning.  Thanks for the `is` reminder btw.
Comment: And here's the relevant page in the documentation: http://docs.python.org/reference/datamodel.html#objects-values-and-types
Answer: Check out this - it's an implementation of exactly what you're asking: multi_key_dict(ionary)
https://pypi.python.org/pypi/multi_key_dict
(sources at https://github.com/formiaczek/python_data_structures/tree/master/multi_key_dict)
(on Unix platforms it possibly comes as a package and you can try to install it with something like:
sudo apt-get install python-multi-key-dict

for Debian, or an equivalent for your distribution)
You can use different types for keys but also keys of the same type. Also you can iterate over items using key types of your choice, e.g.:
m = multi_key_dict()
m['aa', 12] = 12
m['bb', 1] = 'cc and 1'
m['cc', 13] = 'something else'

print m['aa']   # will print '12'
print m[12]     # will also print '12'

# but also:
for key, value in m.iteritems(int):
    print key, ':', value
# will print:1
# 1 : cc and 1
# 12 : 12
# 13 : something else

# and iterating by string keys:
for key, value in m.iteritems(str):
    print key, ':', value
# will print:
# aa : 12
# cc : something else
# bb : cc and 1

m[12] = 20 # now update the value
print m[12]   # will print '20' (updated value)
print m['aa']   # will also print '20' (it maps to the same element)

There is no limit to number of keys, so code like:
m['a', 3, 5, 'bb', 33] = 'something'

is valid, and either of keys can be used to refer to so-created value (either to read / write or delete it).
Edit: From version 2.0 it should also work with python3.
Comment: I tried to run it through 2to3.py, but things go south in the tests when I first hit __setitem__. I'm not sure what is causing it, but it ends up calling __getitem__ recursively and eventually exceeds the maximum recursion depth. Unfortunately because it sounds like this dictionary type might be what I need to use for the problem I'm trying to solve.
Comment: What about the case when two keys contain the same element, say `m['aa', 12]` and `m[12, 'bb']`. What happens when you do `m[12] = 20`
Comment: if two keys contain the same element (which is actually what this is trying to achieve) - this element can be accessed with either of those keys, and removal of either (e.g. `del[12]` or `del['aa']`) will remove the element and it won't be accessible by any other key (also references to this other key(s) are removed).
Comment: `m[12] = 20` will either: 1) if m doesn't contain element with this key (single or multiple) - it will create an element with key 12 and assign (map) it to the value 20 (like standard dictionary). 2) If element exists (like in example above) it will update the value referenced by this key. If this value was mapped with multiple keys - accessing it with these other keys will refer to this (updated) value. I have updated example above to reflect this.
Answer: The most straightforward way to do this is to construct your dictionary using the dict.fromkeys() method. It takes a sequence of keys and a value as inputs and then assigns the value to each key.
Your code would be:
dict = dict.fromkeys(['k1', 'k2', 'k3'], 'v1')
dict.update(dict.fromkeys(['k4'], 'v2'))

And the output is:
print(dict)
{'k1': 'v1', 'k2': 'v1', 'k3': 'v1', 'k4': 'v2'}

Answer: Using python 2.7/3 you can combine a tuple, value pair with dictionary comprehension.
keys_values = ( (('k1','k2'), 0), (('k3','k4','k5'), 1) )

d = { key : value for keys, value in keys_values for key in keys }

You can also update the dictionary similarly.
keys_values = ( (('k1',), int), (('k3','k4','k6'), int) )

d.update({ key : value for keys, value in keys_values for key in keys })

I don't think this really gets to the heart of your question but in light of the title, I think this belongs here.
Comment: I've found your post in a review. I don't understand this topic enough to judge your answer, so I'm skipping this review, leaving it to others. Anyway, let me say that an answer that says "I don't think this really gets to the heart of your question" doesn't look like a good one to me. The fact that you are addressing the title is not enough. Then again, as I said I don't understand enough of this topic, so I am not going to vote in any way. But I still suggest to improve this answer so that you don't have to write "I don't think this really gets to the heart of your question".
Comment: Sorry for the confusion Fabio, though I think we might have a semantic disagreement about what it means to be the heart of a matter. I think my solution is suitable for assigning multiple keys to a common value and this is indeed the question as it is posed in the title and the first part of d.putto's post. The second requirement, to be  'memory efficient' is what I considered the heart of the question. I hope this helps to validate my response. Nevertheless I feel like your comment addresses neither the original post nor the heart of my response and is therefore irrelevant to the discussion.
Answer: You can build an auxiliary dictionary of objects that were already created from the parsed data. The key would be the parsed data, the value would be your constructed object -- say the string value should be converted to some specific object. This way you can control when to construct the new object:
existing = {}   # auxiliary dictionary for making the duplicates shared
result = {}
for k, v in parsed_data_generator():
    obj = existing.setdefault(v, MyClass(v))  # could be made more efficient
    result[k] = obj

Then all the result dictionary duplicate value objects will be represented by a single object of the MyClass class. After building the result, the existing auxiliary dictionary can be deleted.
Here the dict.setdefault() may be elegant and brief. But you should test later whether the more talkative solution is not more efficient -- see below. The reason is that MyClass(v) is always created (in the above example) and then thrown away if its duplicate exists:
existing = {}   # auxiliary dictionary for making the duplicates shared
result = {}
for k, v in parsed_data_generator():
    if v in existing:
        obj = existing[v]
    else:
        obj = MyClass(v)
        existing[v] = obj

    result[k] = obj

This technique can be used also when v is not converted to anything special. For example, if v is a string, both key and value in the auxiliary dictionary will be of the same value. However, the existence of the dictionary ensures that the object will be shared (which is not always ensured by Python).
Answer: I was able to achieve similar functionality using pandas MultiIndex, although in my case the values are scalars:
>>> import numpy
>>> import pandas
>>> keys = [numpy.array(['a', 'b', 'c']), numpy.array([1, 2, 3])]
>>> df = pandas.DataFrame(['val1', 'val2', 'val3'], index=keys)
>>> df.index.names = ['str', 'int']
>>> df.xs('b', axis=0, level='str')
        0
int
2    val2

>>> df.xs(3, axis=0, level='int')
        0
str
c    val3

Answer: I'm surprised no one has mentioned using Tuples with dictionaries. This works just fine:
my_dictionary = {}
my_dictionary[('k1', 'k2', 'k3')] = 'v1'
my_dictionary[('k4')] = 'v2'

Comment: Yes, but it doesn't solve the problem, since you can't call my_dictionary['k1'] to get 'v1' (you'll get KeyError, since the right key for that value is ('k1', 'k2', 'k3'))

Multiple keys per value


Can you add two SECTION sections to ld script

Question: I have an executable made by linking several .o files, using a somewhat involved linker script.   If a particular environment flag is set, I'd like there to be another section involved.   So, something like:
/* withfoo.ld */
SECTIONS {
 .foo 0x80000000 : {
    _start_foo = .;
    . += 0xfff;
    _end_foo = .;
 }
}

and then compile with:
if [ $FOO_DEFINED ]; then
    gcc -Wl,-T normal.ld $(OBJS) foo.o foo.ld
else
    gcc -Wl,-T normal.ld $(OBJS)
fi

where I'd like to not to have to modify normal.ld.   normal.ld has a SECTIONS definition within it.   So that gives me two SECTIONS...  I'm getting the warning:
/usr/bin/ld: warning: foo.ld contains output sections; did you forget -T?

Is there an actual problem or is this just a warning?  Also is there a proper way to do this that I'm not aware of?
Answer: GNU linker scripts and LD do not support conditional compile. You can't use two linker scripts at once and have it work as expected. You have to pre-process the linker script with some other type of macro language like m4 or even just use the GNU C Preprocessor cpp.

Not sure if this is a type of solution you are looking for. The C preprocessor cpp can process the text of any kind of file (even non-C files) and will blindly parse for pre-processor directives and macros just like a C file. You can also pass C style defines through the cpp command line just like you can with GCC. You create a linker script with all the C pre-processor directives and generate specific linker scripts based on that. For example create a special linker script like this:
linker.ld.pp :
SECTIONS {
#ifdef FOO
 .foo 0x80000000 : {
    _start_foo = .;
    . += 0xfff;
    _end_foo = .;
 }
#endif
}

This uses typical C style #if/#ifdef/#endif for conditional compilation. If you run it through the C pre-processor with a command like:
cpp -P -DFOO linker.ld.pp

You'd get output like this:

SECTIONS {
 .foo 0x80000000 : {
    _start_foo = .;
    . += 0xfff;
    _end_foo = .;
 }
}

Not defining FOO would be done like this:
cpp -P linker.ld.pp

The output would be:

SECTIONS {
}

To redirect the pre-processor you can output to a linker script with:
cpp -P -DFOO linker.ld.pp >withfoo.ld
cpp -P linker.ld.pp >withoutfoo.ld

You can specify multiple -D directives on the CPP command line to define multiple pre-processor symbols if you wish. The idea of this method is that you have a single linker script but you create a shell script to generate the necessary specialized scripts that are required.

Other Observations
Usually you specify linker scripts on the GCC command line with the -T option:
gcc -T withfoo.ld $(OBJS) foo.o


If $f\geq0 , f(0)=f(1)=0$,and $\int_0^1|f''|/f dx$ exists,how to prove $\int_0^1f''/f dx\geq \pi^2$

Question: If $f\in C^2 , f\geq0$ on $[0,1]$ , $f(0)=f(1)=0$,and $\int_0^1f''/f dx$ exists,how to prove  $$\int_0^1\frac{|f''|}{f}dx\geq \pi^2$$
The lower bound $\pi^2$ was guessed by myself, if it was not true ,then how to find this lower bound ?
My way is to have an analytic  extension with $T=2$, and use the Fourier Series to have an evaluation .
But it seems like that I was wrong.
Comment: What if $f$ is chosen to be piecewise linear?
Comment: I'm not guessing anything, just pointing out that the integral is typically going to be negative (e.g. for $f(x) = \sin(\pi x)$ it is $-\pi^2$).
Comment: Did your bound come from applying a sine function? How did you arrive at this question?
Comment: @Mefitico It's quite hard to find a function in which $\int_0^1 \frac{|f''(x)|}{f(x)} dx$ exists other than $\sin(x)$.
Comment: Well, the original question is asked to show that integral $\geq 4$ , and the method is by using the mean value theorem , but I think the lower can be raised up to $\pi^2$,I use the Fourier Expansion to evaluate, and by the mistake of $\sum a_n\leq|\sum n^2a_n|$, I "deduced" the inequality , but later I found that inequality is not true , however, I still feel that result is correct , so I post it as a question.
Comment: @AlexanderLau Does the function have to be differentially continuous? The integral with $f(x)=1-2|x-0.5|$ is 0.
Comment: @Infiaria Yes, so it is natuarly comes up with the trignometric series
Comment: @Infiaria oh yes, sorry, I fogot to post it.
Comment: Could you please then post the solution for the problem using the Mean Value Theorem? To clarify, you know the bound to be 4 but you are searching for a tighter bound?
Answer: Let:
$$
f(x) = \sin(\pi x)+0.1\sin(2 \pi x)
$$
Then
$$
f'(x) = \pi\cos(\pi x)+0.2\pi\cos(2 \pi x)
$$
$$
f''(x) =-\pi^2\sin(\pi x)-0.4\pi^2\sin(2 \pi x)
$$
So:
$$
\int_0^1 \frac{|f''(x)|}{f(x)} dx=\int_0^1  \frac{\pi^2\sin(\pi x)+0.4\pi^2\sin(2 \pi x)}{\sin(\pi x)+0.1\sin(2 \pi x)}dx = 9.25905... < \pi^2 = 9.8696
$$
Here's the link to the result:
https://www.wolframalpha.com/input/?i=%5Cint_0%5E1++%5Cfrac%7B%5Cpi%5E2%5Csin(%5Cpi+x)%2B0.4%5Cpi%5E2%5Csin(2+%5Cpi+x)%7D%7B%5Csin(%5Cpi+x)%2B0.1%5Csin(2+%5Cpi+x)%7Ddx
Indeed it is hard to come up with a non-sine function that allows the integral to converge, but if you make a composition of such kind, you can likely lower your bound. I would suspect however, that there should be a sequence of functions $f_n$ such that the integral converges to zero.
Edit
My reasoning to claim that the integral can be made arbitrarily close to zero is that with a large enough sine series, it should be possible to build $f(x)$ such that the integral exists due to the characteristics of the sine on the extremes, but outside the extremes and some mid point, the function is "flat", i.e. with arbitrarily small  $f''(x)$ but with large values for $f(x)$, hence decreasing the value of the integral.
Answer: The proposition you're trying to prove is false. This integral can be made arbitrarily close to $4$. A family of examples:
$$f(x) = \begin{cases}2x&0\le x\le \frac12-\epsilon\\ 1-\frac{3\epsilon}{4} - \frac{3}{2\epsilon}(x-\frac12)^2 + \frac1{4\epsilon^3}(x-\frac12)^4  & \frac12-\epsilon\le x\le \frac12+\epsilon\\ 2-2x&\frac12+\epsilon\le x\le 1\end{cases}$$
Why is this $C^2$? We check the values and derivatives where the formulas change. At $\frac12+\epsilon$ using the middle formula,
\begin{align*}f\left(\frac12+\epsilon\right) &= 1-\frac{3\epsilon}{4} - \frac{3}{2\epsilon}\epsilon^2 + \frac1{4\epsilon^3}\epsilon^4 = 1 +\epsilon\left(-\frac34-\frac32+\frac14\right) = 1-2\epsilon\\
f'\left(\frac12+\epsilon\right) &= -\frac{3}{\epsilon}\epsilon+\frac1{\epsilon^3}\epsilon^3 = -2\\
f''\left(\frac12+\epsilon\right) &= -\frac{3}{\epsilon} + \frac{3}{\epsilon^3}\epsilon^2 = 0\end{align*}
Those match the values from the other formula it meets, and the first two derivatives are continuous there. At $\frac12-\epsilon$, we appeal to symmetry; $f(x)=f(1-x)$, so continuity of the first two derivatives at $\frac12+\epsilon$ implies it at $\frac12-\epsilon$.
What is $\int_0^1 \frac{|f''(x)|}{f(x)}\,dx$? Rather than calculate it exactly, I'll estimate. We have
$$f''(x) = \frac3{\epsilon}\left(-1+\left(\frac{x-\frac12}{\epsilon}\right)^2\right) \le 0$$
for $\frac12-\epsilon\le x\le\frac12+\epsilon$, so $\int_{1/2-\epsilon}^{1/2+\epsilon}|f''(x)|\,dx = \left|f'\left(\frac12+\epsilon\right)-f'\left(\frac12-\epsilon\right)\right| = 4$. Now, we divide by $f(x)$ inside the integral; from $1-2\epsilon\le f(x)\le 1-\frac34\epsilon$ on the interval,
$$\frac{4}{1-\frac34\epsilon}\le\int_{1/2-\epsilon}^{1/2+\epsilon}\frac{|f''(x)|}{f(x)}\,dx \le\frac{4}{1-2\epsilon}$$
What about $f$ outside that subinterval? The second derivative out there is identically zero, so that part contributes nothing to the integral, and $\int_0^1 \frac{|f''(x)|}{f(x)}\,dx$ lies between those bounds.
As $\epsilon\to 0$, both of those bounds tend to $4$, and therefore the integral does by the squeeze theorem. The limiting function isn't $C^2$, but we can make the integral arbitrarily close to $4$ this way.


Custom html.html.twig for a display mode

Question: While using display suite in drupal 8.6.2 Is it possible to have a custom displaymode-html.html.twig that replaces the default
html.html.twig?
So far I have tried enabling the view mode dev hints in themename.yml but it doesn't seem to be showing me anything for html.html.twig
Comment: what is your propose of having a custom html.twig file? this file is not meant to be used for design proposes much, just placement of page , page bottom, page top and placeholders
Comment: The placement needs to vary, but only for certain display modes.
Comment: You don't have any theming variables in this file , even you have no access to regions , so how placement might vary when you only have page top which must be before page, page and page button which should be placed after page?
Comment: I think you should have use other theming files like page.html.twig not html.html.twig
Comment: Thanks! Is there any documentation that would cover this?
Comment: Also, js and css placeholders are in `html.html.twig` not sure how I'd be able to override them inside `page--viewmode.html.twig`
Comment: theming files act as hierarchical in html.html.twig you place page variable, then in page.html.twig you place regions placement, regions are places that blocks are placed and ...
Comment: https://www.drupal.org/docs/theming-drupal is the drupal reference for learning how to theme, there are many more tutorials available, I highly recommend www.Drupalize.me but it is not free
Answer: I'm not used to Display Suite but I'd recommend you to have a look at hook_theme_suggestions_alter() in order to build your own twig template suggestions based on specific conditions that you can set using the $variables variable values.
Comment: Thanks. I tried this with the hook set to `html` but it just shows me a blank in view mode.


Logout em PHP com CodeIgniter

Question: Estou com um problema no logout do meu sistema, ele até que está fazendo logout corretamente e destruindo as sessões, mas se o usuário clicar no botão de voltar do navegador ele volta a página anterior do sistema onde é exibido todos os dados novamente. O código está assim:
public function logout()
{
    $this->session->sess_destroy(); //destroi a sessao
    redirect('/'); // redireciona para a raiz do sistema(pagina de login)
}

Mesmo destruindo a sessão, ele consegue acessar a página anterior do sistema, as verificações de sessão dentro do programa estão corretas, pois se ele clicar em um link e for pra outro módulo ele será expulso do sistema.
Alguém pode me ajudar?? Obrigado :)
Comment: Creio que uma boa prática, é analisar as sessions antes de renderizar o conteúdo. Caso a sessão esteja vazia, redireciona para o login.
Answer: Tem um tempo que não mexo com Codeigniter, mas a solução abaixo funcionará com qualquer outro framework (ou até mesmo no PHP puro).
Considerando que você destruiu a sessão, para garantir que a sessão anterior não seja acessada (seja por algum bug do framework ou qualquer outro erro), você pode simplesmente regenerar o id, para que a referência anterior seja perdida.
Nesse caso, faça assim:
public function logout()
{
    $this->session->sess_destroy();

    $this->session->regenerate_id();

    redirect('/');
}

Atualização
Foi informado que regenerate_id não funcionou. Então, você pode usar $this->session->sess_update().
Comment: Não funcionou, o Codeigniter não tem a função regenerate_id()
Comment: Se a atualização não funcionar, eu removo o post.
Answer: Apenas

 public function sair(){
    $this->session->sess_destroy();

    redirect('view aonde quer voltar');
  }

Logout em PHP com CodeIgniter


How can I test only a method with Ruby's Test::Unit?

Question: Imagine I have a test like this:
class MyUnitTest < Test::Unit::TestCase
  def test_first
    # test code here
  end

  def test_second
    # test code here
  end

  def test_third
    # test code here
  end
end

My test cases are destructive, and I need to regenerate the input in between tests. Therefore, it would be useful to run only one test case at a time. Currently, my approach is to comment tests that I don't want executed, but surely there must be a better way?
So, for example, how do I run only test_first when I execute my test?
Comment: possible duplicate of [ruby Test::Unit Command line options?](http://stackoverflow.com/questions/543588/ruby-testunit-command-line-options)
Answer: Use --name PATTERN argument in order to filter out test names you want to run.
D:\Projects>ruby test.rb
Loaded suite test
Started
...
Finished in 0.000000 seconds.

3 tests, 0 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 39768

D:\Projects>ruby test.rb -n test_first
Loaded suite test
Started
.
Finished in 0.000000 seconds.

1 tests, 0 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 53891 --name "test_first"

Comment: Thank you! What did you use to search for this? I get only irrelevant results. Could you give me a link to this doc please?
Comment: I went to the ruby installation directory on my computer and opened minitest/unit.rb file. Then I searched for OptionParser usages - and found an answer. You can browse the code online: http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/trunk/lib/minitest/unit.rb?view=markup.
Comment: If you're on Ruby 1.8 (which has Test::Unit), or Ruby 1.9.2 or later, you can also do `ruby test.rb --help`. Unfortunately, an ordinary install of Ruby 1.9.1 doesn't give you anything when you do `ruby test.rb --help`.
Answer: Can you regenerate the input with ruby? Then you could use the setup-method.
gem 'test-unit', '>= 2.1.1' #startup
require 'test/unit'

class Test_setup < Test::Unit::TestCase
  def setup
    #Your regeneration of the input
    puts "Setup"
  end

  def teardown
    #Clean actions
    puts "End"
  end

  def test_1()
    puts "Testing setup 1"
  end
end

Comment: It's kind of error prone, since I'm relying on Mercurial's revert to regenerate. In the same time, I'm developing. It's kind of unsafe, I prefer to do it manually :)


Show the function for which the Dirichlet generating series is $\zeta(2s)$ using only $\tau,\varphi,\sigma\text{ and }\mu$ or some explicit formula.

Question: I'm trying to find the function with Dirichlet generating series $\zeta(2s)$, I know that this relates somehow to the Liouville function but I am trying to express it in terms of only the standard arithmetic functions $\varphi,\tau,\sigma,\mu$ or some explicit formula. What I have tried so far is I know,
$$F_f(s)=\sum_{j=1}^\infty\frac{f(j)}{j^s}$$
$$F_f(s-1)=\sum_{j=1}^\infty\frac{jf(j)}{j^s}$$
And I have tried to find the g such that
$$F_g(s)=\sum_{j=1}^\infty\frac{g(j)}{j^{2s}}$$
But everything I have tried from this point onwards has been unsuccessful. Any help would be great.
Comment: $\zeta (2 s)=\sum\limits_{n=1}^\infty \frac{1}{n^{2 s}}$. If you want to write this in the form $\zeta (2 s)=\sum\limits_{n=1}^\infty \frac{a(n)}{n^s}$, then $a(n)$ is $1$ when $n$ is an integer square and zero otherwise.
Comment: @StevenClark thank you for such a clear answer.
Answer: In this sort of question, it is often a good idea to consider the effect on the Euler product:
$$ \zeta(2s) = \prod_p \left( 1 - \frac{1}{p^{2s}} \right)^{-1}. $$
This particular question happens to be relatively straightforward, as this is obviously multiplicative and this expression indicates that the coefficients are defined on prime powers by the function
$$ a(p^k) = \begin{cases} 1 & 2 \mid k \\ 0 & \text{else}. \end{cases} $$
This is, of course, another name for the "is a square" function.
Visually inspecting, we can quickly convince ourselves of this as well:
$$ \zeta(2s) = 1 + \frac{1}{4^s} + \frac{1}{9^s} + \frac{1}{16^s} + \frac{1}{25^s} + \cdots$$
Comment: Oh, hahaha. Let me rewrite my last example.
Comment: $\zeta (2 s)=\sum\limits_{n=1}^\infty \frac{1}{n^{2 s}}\ne1+\sum\limits_{n=1}^\infty \frac{1}{p_n^{\ 2 s}}$ where $p_n$ is the $n^{th}$ prime.


BST maximum height and minimum height

Question: Question:
seven keys 1, 2, 3, 4, 5, 6, and 7 are inserted in some order into an initially empty binary search tree (BST). Specify four insertion orders yielding trees of the maximum height and four insertion orders yielding trees of the minimum height.
I feel struggled about how to insert 4 maximum heights and 4 minimum heights, My idea is to pick up 4 as the root then probably only one minimum height and maximum height? Please share some ideas, Many thanks!
Answer: Thinking about how the BST insertion algorithm works could be a good approach to this problem.
To generate a maximum height tree, you need to make sure that no node has two children. In a BST, the left subtree will contain keys smaller than the root while the right subtree will have larger keys. So, by choosing the minimum or maximum of the set as the root, you'll achieve your goal: there will be no element to insert to the right (if root is maximum) or to the left (if root is minimum). Then, you continue doing this recursively: in each subsequent insertion, choose either the maximum or the minimum of the remaining items.
In each step you'll have two options to choose from (except for the last step, where you'll only have one remaining item), so there are 2⁶ permutations to choose from. For example, 7 1 6 5 4 2 3 or 1 2 3 7 4 6 5.
Now let's analyze the minimum height case. A minimum height tree of 7 keys will be a full tree of height 3. Due to the property mentioned above, this means that the root will necessarily be the middle element, because we need to insert the same amount of elements to the left and to the right. Now we also proceed recursively: on the left we'll have 1, 2 and 3 and 2 will have to be the root of the left subtree, while on the right we'll have 5, 6, and 7 and 6 will have to be the root of the right subtree. The order of insertion of 2 and 6 yields the same result. Next, you need to insert the leaves but in this case there are no restrictions. This means that you'll have only one option for the first item (4), two options for the second (2 or 6) and 4! for the remaining 4, which equals 48 possible permutations. For example, 4 6 2 1 7 5 3 or 4 2 6 1 7 3 5.

BST maximum height and minimum height


$\forall \varepsilon \in \mathbb{R}_{>0} \exists v \in V$ so that $x - \varepsilon < v$ if and only if $x = \sup V$

Question: I'm trying to prove that, given a non-empty bounded set $V$ so that $V \subset \mathbb{R}$ that an upperbound
$x \in \mathbb{R}$ is a supremum of V if and only if $\forall \varepsilon \in \mathbb{R}_{>0} \exists v \in V$ so that $x - \varepsilon  < v$
I've already proven that
$x = \sup V$ implies $\forall \varepsilon \in \mathbb{R}_{>0} \exists v \in V$ so that $x - \varepsilon  < v$
but I'm stuck on the reverse. I've tried to proof it by contradiction, but I'm not really getting anywhere. I get that, if we assume $\forall \varepsilon \in \mathbb{R}_{>0} \exists v \in V$ so that $x - \varepsilon  < v$  and that $x \neq \sup V$ we must accept that there exists an $y \in \mathbb{R}$ so that $y = \sup V$ Considering all non-empty bounded subsets of $\mathbb{R}$ have a subset. But I'm not really getting anywhere further.
Any help would be appreciated.
Comment: Your statement is incomplete. The $\forall\epsilon\dots$ is also true for any $x\in V$. You should add the condition that $x$ is an upper bound for the elements of $V$.
Comment: @SMoore thanks! I'll fix it.
Answer: Suppose that $x = \sup V$
By definition $x$ is the smallest upper bound of $V$.
Let $\epsilon>0$. Suppose that there is no $v$ such that $x-\epsilon<v$, this implies that $\forall v,x-\epsilon\ge v$, thus $x-\epsilon$ is an upper bound of $V$ smaller than $x$, which is impossible.
Hence $\forall \varepsilon \in \mathbb{R}_{>0} \exists v \in V,x-\epsilon<v$

Edit : my bad, you wanted the other way. Here it is :
We have $\forall \varepsilon \in \mathbb{R}_{>0} \exists v \in V,x-\epsilon<v$.
Let $x'=\sup V$.

If $x'<x$, then by definition this is absurd by choosing $\epsilon<x-x'$
If $x'>x$, then $x$ is an upperbound of $V$ smaller than $x'$ which is impossible

Hence $x=\sup V$
Comment: actually he said he already proved this. He is stuck on the reverse.
Comment: @SiXUlm Oh my bad I read it too fast. I'll edit it.
Comment: @pokemanfan I edited it, now it's the right way
Comment: I did a few minutes after I commented.  So, no, I hadn't seen it and that was what I was overlooking.


Finding probability distribution for a discrete random variable

Question: When the health department tested private wells in a county for two impurities commonly
found in drinking water, it found that 20% of the wells had neither impurity, 40% had
impurity A, and 50% had impurity B. (Obviously, some had both impurities). If a well is
randomly chosen from those in the county, find the probability distribution for the
discrete random variable Y = the number of impurities found in the well.
I already have the answer, and this isn't homework. Just trying to find out how to solve the problem.
Answer: First, it is obvious that (by the inclusion-exclusion principle) there are $10\%$ of wells which have two impurities, which implies that there are $80\%-10\%=70\%$ of wells that have only one impurity. For $Y$ there are only three possible values: $0$, $1$, and $2$. Then the distribution of $Y$ is clearly
$$\begin{matrix}Y&|&0&1&2\\\mathbf P&|&0.2&0.7&0.1\end{matrix}.$$
Answer: Let $p_A$, $p_B$ and $p_C$ be the respective probabilities that a well contains impurity A only, impurity B only and both impurities. We know that
$$p_A+p_B+p_C+0.2=1.$$
Notice that the probability that a well contains impurity A is given by $p_A+p_C$ (and similarly for impurity B). Thus
$$p_A+p_C=0.4,\qquad p_B+p_C=0.5.$$
Now you just have a system of $3$ linear equations in $3$ unknowns. Is this something you can solve?
Answer: Given: $P(A)=0.4,P(B)=0.5,1-P(A\cup B)=0.2.$
Look at the Venn diagram:

$$\begin{cases}
P(A)=P(A\setminus B)+P(A\cap B)=0.4 \\
P(B)=P(B\setminus A)+P(A\cap B)=0.5 \\
P(A\cup B)=1-P(A\cup B)=1-P(A\setminus B)-P(B\setminus A)-P(A\cap B)=0.2
\end{cases} \stackrel{+}\Rightarrow $$
$$P(A\cap B)=0.1 \Rightarrow P(A\setminus B)=0.3, P(B\setminus A)=0.4.$$
Hence:
$$\begin{align}
&P(Y=0)=1-P(A\cup B)=0.2 \\ &P(Y=1)=P(A\setminus B)+P(B\setminus A)=0.7 \\ &P(Y=2)=P(A\cap B)=0.1.
\end{align}$$


CSS - display property not working as expected with IE

Question: I have 2 display rules that i can't get to work
I can't use the display property with IE version < 10, i'm using this code:
Comments(<fb:comments-count href="http://mypage"/></fb:comments-count>)

That results in:
Comments(<fb:comments-count href="http://mypage" fb-xfbml-state="rendered" class=" fb_comments_count_zero">

        10

</fb:comments-count>)

With this css:
.fb_comments_count {
    display: inline;
}

.fb_comments_count_zero {
    display: inline;
}

It displays:
Comments(
10
)

instead of
Comments(10)

I tried also changing
display:inline

to
display:inline-block

But it's not working.
The other issue i'm having is when i use display:none. In fact, IE<10 doesn't hide what i'm styling, but IE10, chrome, opera and firefox don't have that problem.
How can i fix this?
P.S. I prefer not to use JavaScript, because i want my site to look good even if javascript is disabled.
Comment: I guess it's because `` is not a supported tag. I suppose it's a Facebook tag?
Comment: @poepje You are right, it's a facebook tag for including comments into the site, but i'm not styling the tag, i'm styling the tag's class, that should be supported by all browsers
Comment: Clearly the `` is being styled with `display:block`. This would be the default for an unknown element (particularly in older IE versions which don't play well with unknown elements). What doctype are you using (if you're using an xhtml doctype, it will be picking up the `` element as an embedded XML element with a namespace; this may give you different layout defaults to an HTML doctype. Either way, my preferred solution would be to drop it from the rendered HTML output unless you really need it to be there.
Comment: I guess so yeah, after all there are plenty of sites which use this and (I assume) work in IE as well. But Spudley's suggestion seems a good one, if you're not already using html5, try it (the doctype is simply ``)
Answer: You're using dashes instead of underscores in your CSS.
.fb-comments-count {
    display: inline;
}

Try changing it to:
.fb_comments_count {
    display: inline;
}

Comment: This is not the problem, it was just a typo
Answer: Internet Explorer will not style any element it is not aware of. That is why there is a HTML5 shim javascript; to inform IE of the new HTML5 elements (insert them into the DOM). Other browsers won't have this issue.
Answer: Im not entirely sure how FBML gets rendered in the end, but older IEs don't recognize custom tags and won't apply css to them, so this might be the issue. You need to "register" the tags to the IE.
Also you should avoid the linebreaks in your span:
10

this already might fix your first problem, if not try to apply white-space:nowrap;.
Comment: I tried but i can't get it work... I tried adding either `fb` and `fb-comments` to the tags list in this (separated with `|`) but the `display` rules over the `fb:comments` element are still being ignored
Answer: ie has always had a problem with braking lines where it should not try adding this to your css

white-space:nowrap;

If that does not work then please tell me what happens.
I have had these problems before with ie so it not just you.
also try wrapping your fb tag in a p tag then add a style of choice to the p tag.


Let $A$ and $B$ be two real symmetric matrices such that $A^{2018} = B^{2018}$. Show that $\cos A = \cos B$.

Question: Let $A$ and $B$ be two real symmetric matrices such that $A^{2018} = B^{2018}$. Show that $\cos A = \cos B$.
(And is it true that $\sin A = \sin B$ ?)
We can write $A = PDP^T$ and $B = QD'Q^T$ by the spectral theorem ;
Hence $PD^{2018}P^T = QD'^{2018}Q^T$
Do you have a hint to solve this?
Comment: $B=-A$ gives a lot of counterexamples for sine.
Comment: What is $S_n(\mathbb{R})$?
Comment: I am curious about where this problem comes from.  In particular, I wonder if it comes from a competition (math contests often use the year in their problems).
Comment: @anon the asker has already referenced this fact (i.e. the spectral theorem) in the body of his question
Comment: Yes, I put this, under parenthesis, because it was the end of the exercise.
Answer: $A^2$ and $B^2$ are positive definite matrices satisfying
$$
(A^2)^{1009} = (B^2)^{1009}
$$
It follows that $A^2 = B^2$.
Now, note that the power series for $\cos(A)$ may be written as a power series on $A^2$.
It is easy to come up with a counterexample for $\sin$.  If you like, take $A = \pi/2$, $B = -\pi/2$ (both $1 \times 1$ matrices).
Answer: First note that $A^{2018}$ and $B^{2018}$ are positive.
The function ``$2018$-th root ($\sqrt[2018]{\ast}$)'' is defined for all positive matrices, and it takes "a positive matrix $X$ to the only positive matrix $B$ in the algebra generated by $A$ such that $B^{2018}=X$"
Moreover, if $X$ is symmetric then $\sqrt[2018]{X^{2018}}=|X|$, where $|X|=\sqrt{X^2}$.
From this, we get $|A|=|B|$. Take cosine on both sides to get $\cos|A|=\cos|B|$, and again use symmetry to conclude that
$$\cos A=\cos|A|=\cos|B|=\cos B$$
All of this works in any C*-algebra and $A,B$ self-adjoint elements and if $\cos$ is replaced by any even continuous function (note that in this case the trick with the Taylor expansion of $\cos$ mentioned by others doesn't work anymore).
Comment: Or note that $f(t)=t^{1/1009}$ is continuous on $\Bbb R$ since $1009$ is odd; hence $A^2=f(A^{2018})=f(B^{2018})=B^2$.
Comment: @DavidC.Ullrich Works as well. I think this argument is the same as the second and third paragraph, but in opposite order, because then we need to take square roots and get $|A|=|B|$.
Comment: Of course it's essentially the same. But no, we don't need to take square roots! The reason I mentioned this is that once we know $A^2=B^2$ we done, since $\cos(t)$ depends only on $t^2$; no need to worry about $|A|$ and $|B|$ at all.


How to define Confidence Intervals from a distribution of 1000 t-statistics?

Question: I have a vector of length 300 containing some kind of values (say, scores of a math test). The distribution is not normal.
I want to test if the average score of a small group (30 samples) is significantly different from the mean of all the remaining 470 individuals.
I performed a Welch's t-test obtaining a t-statistic.
In order to validate my results I performed a bootstrapping:
I computed 1000 t-tests from a random creation of subgroups (again,30 vs. 470) generating a distribution of 1000 t-statistics.
My question is, how can I define the Confidence Intervals for my t-statistics distribution and check if the t-statistics of the original subgroup is outside the CI?
Answer: It sounds like what you're describing is a permutation test (or more strictly, a test based on random sampling of the null distribution of a full permutation test).
If the sampling is without replacement, it's a permutation test; if it's with-replacement, then it would be a bootstrap test. Both are particular kinds of resampling-based tests and are (as you might guess) related.
(I'd recommend you consider doing it as a permutation test.)
The way you use such a distribution for a hypothesis test is to collect the results for all your resamples, and then find how far into the distribution the real sample lies (the sample value itself counts in the proportion of values at least as extreme as the one observed).
Equivalently, you take the middle $n(1-\alpha)$ values (for $n$ such resamples) as the non-rejection region, and the $n\alpha/2$ values in each tail as the rejection region.
Comment: In order words, the p.value for my observed t is given by the ratio between the number of t-statistics bigger than the observed and the total number of t-statistics? Is it correct?
Comment: If you are doing a one-tailed test yes. Otherwise you need to account for the other tail as well.


page_cache_maximum_age wrongly set

Question: In our production server, we wrongly set page_cache_maximum_age a long value,
$conf['page_cache_maximum_age'] = 12960000;

Now viewers are complaining they are seeing old contents in there homepage.
I am able to see new contents with a force reload (CTRL + F5).
Is there any way to force the client side to refresh the pages in this stage?
We have our architecture Drupal+Nginx+Varnish and CloudFlare on top of it.
Answer: Either you don't need, or you can't:
If this was translated to HTTP header, and browser "knows" not to ask for the page again, nothing you would try to do about it will have any effect, because browser simply won't contact your server anyway, so it will not download any remedy you might try.
If it affected only server-side systems, tuning it down and clearing caches should be enough already, and server shouldn't send "304 Not Modified" to your clients.
Hard to tell which case is it without knowing your caching setup, but I'm afraid "fix it and wait" is the only way either way.
Unless, for some reason, you can identify uncached JS file included on affected pages. This would be a bug, so I don't expect it to happen, but if, it might be a bug you could use - ask for it on Stack Overflow, then, as this is much less Drupal-related.
If your front page isn't cached that way, you can alter all affected links. It will not help people having issues with bookmarked pages, but it will direct regular users to current content.
Comment: Actually I was meant to set max expiry for varnish when Drupal serve the content to varnish. From varnish to user end the max age should be normal or 0, so that selective cache purge will works efficiently. But due to a mistake in varnish vlc it passed the same header to clients.
Comment: @shameem so it's the first case - you can't affect user agent behavior if user agent does not contact you at all.
Comment: yes I understood. :( but we are out of choices that's how I end up here.
Answer: You might want to flush the entire cache for now with
varnishadm "ban req.url ~ /"

found this at https://www.varnish-cache.org/forum/topic/696
OR
 set req.hash_always_miss = true;

What you are looking for is to miss as stated on https://www.varnish-software.com/book/3/VCL_functions.html and the easiest way is to force the requested cache to not be present
simpeler explaination:

page_cache_maximum_age wrongly set


difference in regex logic

Question: In my website, I am using the below regex to validate email.
^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$

My doubts are:

Can I use the below regex for the same functionality?
^[a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+.[a-z]{2,4}$

The reason why I ask this is, I tried to study the meaning. So I got a confusion that
[a-zA-Z0-9_.-] cover all the instances by [a-zA-Z0-9] and [a-zA-Z0-9_-]

I a not sure about this, as I am a beginner.
I got the regex from
http://regexlib.com/
I checked both regex in http://regex101.com/#pcre. And I can't find any difference in result. May be it is because of my limited knowledge
Please give a clarification. Thanks to all in advance
Comment: None of these regexes are any good.  You need to accept email addresses containing plus signs in the local part (mine has one); equals signs, exclamation marks, asterisks, and a lot of other punctuation characters which you are currently excluding are valid as well, altough not as common as plus, which has a useful function of its own in many installations.
Comment: They don't have the exact same functionality, but your short regex is better than the long regex, since it avoids catastrophic backtracking which presents in the long one.
Comment: @nhahtdh, thank u..may I know what is the exact change in output from the long regex? :)
Comment: The long one doesn't accept user part less than 3 chars `firstname.lastname@example.com`, and doesn't accept domain less than 6 chars `firstname.lastname@example.com`. Another thing, please add escaping to the last `.`.
Comment: @nhahtdh, `^[a-zA-Z0-9_.-]{3,}@[a-zA-Z0-9.-]{6,}.[a-z]{2,4}$`. Is it equal to the regex?
Comment: See this [link](http://regex101.com/r/qE9fT9/1) as demo for invalid mail adresses your short regex would allow. (change the regex to see the difference)
Answer: Maybe it's not the answer you were looking for, but I have to say that I ended up with this kind of email validation: ^.+@.+\..{2,}$ after trimming it.
What does it check? Existence of some symbols, @ itself, some other symbols, dot, and at least two symbols for top-level domain. It says "Dude, there should be an email, not your hilarious username". And that's enough, I guess.
By the way, .[a-z]{2,4}$ is a huge mistake for checking TLD, since there are few popular domains that are longer than 4 symbols (i.e., .travel) and a lot of less popular ones.
Why do I think that you don't need a detailed validation? First of all, there are a lot of requirements which you'll miss anyway. Do you know that cyrillic symbols are allowed in the email address?
And, please, think what do you want from this validation? Avoid incorrect emails? You won't. Somebody will enter an email, which meet all of your requirements, but it'll be incorrect anyway. Is firstname.lastname@example.com a good one? No. Will it be checked by regexp? I'm afraid, the answer is "no" once again.
So, it's better to explain that user should provide valid email to get confirmation mail and to make an explanation "if you aren't the one, who registered at mysite.com, please just ignore this letter" in the email text.
Because regexp will never filter enough, but you can lose a couple of users with strange email adresses because of it.

And since this should be an answer for your question:

It won't be the same functionality, but both regexp's are far from being perfect.
Long regexp checks that first symbols in login mustn't be a dot, dash or underscore, last symbol shouldn't be a dot, while other symbols might be, but avoid the fact that login might be shorter than 3 symbols. Short regexp is better (= simpler) but it doesn't meet requirements mentioned above.
So, if you want to use your variant, just remove 4 from it. If you need the logic of the original one, you can't make it shorter.
Differences might be found using these examples: .firstname.lastname@example.com, firstname.lastname@example.com, email@example.com

difference in regex logic


How do you change the location of `form_set_error` output?

Question: Is there a way in Drupal 7 to change the location of the output of form_set_error?
At the moment, it calls drupal_set_message which queues all the form's errors to the top of the screen.
What I would like instead is for each message to appear below the appropriate field.
If this is not possible, can I manually flag the form as "invalid" within the MODULE_form_name_validate() function without using form_set_error?
Answer: Extending the (correct) answer from Clive, I worked through the IFE code. I didn't really need an entire module dedicated to this, so I adopted a few snippets here and there to get the result I needed. I've marked his answer as correct because it is ultimately the right answer.
The code is below, all credit goes to Clive and the IFE team - I just wanted to present the simplified version for anyone looking for a similar answer.
// Standard gear - do some custom validation and set the errors
// as you go..
//
// Once all the validation has been done, call MODULE_errors_reset
// which will return an array of all errors against their ID.
// Expose this array however you like to your template, or loop
// over your form adding a #suffix to each element with an error
//
function MODULE_form_name_validate($form, &$form_state) {
    drupal_set_message("validating...");

    form_set_error("description", "There is an error here!!!!");
    form_set_error("tags", "Yep, and here too!!!");

    $reset_errors = MODULE_errors_reset( $form );

    drupal_set_message( "
" . print_r( $reset_errors, true ) . "
" );
}

// This part is adopted from IFE. It's changed in two ways, it returns
// an array (which also merges with its recursive self).
// And it also skips all the 'display' stuff present in the original
// Essentially it extracts out the error messages from the session and unsets
// them. I am assuming that Drupal 7 marks the success of a validation based not
// whether the SESSION variable contains anything, the SESSION seems to be only
// for the message at the top of the screen.
//
function MODULE_errors_reset( $element ) {
    if( ! isset( $_SESSION[ 'messages' ] ) ) {
        return;
    }

    $reset_errors = array();

    // Recurse through all children.
    foreach( element_children( $element ) as $key ) {
        if( isset( $element[ $key ] ) && $element[ $key ] ) {
            $reset_errors += MODULE_errors_reset( $element[ $key ] );
        }
    }

    // Check for errors and settings
    $errors = form_get_errors();
    $element_id = implode( '][', $element[ '#parents' ] );

    if ( !empty( $errors[ $element_id ] )) {
        $error_message = $errors[ $element_id ];

        // Get error id
        $error_id = array_search( $error_message, $_SESSION[ 'messages' ][ 'error' ] );

        if( $error_id !== FALSE ) {
            unset( $_SESSION[ 'messages' ][ 'error' ][ $error_id ] );
            $_SESSION[ 'messages' ][ 'error' ] = array_values( $_SESSION[ 'messages' ][ 'error' ]  );

            if( count( $_SESSION[ 'messages' ][ 'error' ] ) <= 0 ) {
                unset( $_SESSION[ 'messages' ][ 'error' ] );
            }

            $reset_errors[ $element[ '#id' ] ] = $error_message;
        }
    }

    return $reset_errors;
}

// If there are no form errors, we still hit here, even after the 'reset', this is
// a good thing.
function MODULE_form_name_submit( $form, &$form_submit ) {
    drupal_set_message("submited!");
}

Comment: Hi Chris, when you say "Expose this array however you like to your template, or loop over your form adding a #suffix to each element with an error", how can I access the $reset_errors variable returned in the validate function in my form function? Would it be alright to provide a sample display for that? Thanks!
Comment: @LeolandoTan sorry mate - I haven't used Drupal since 2013 - I can't even remember answering this question!
Answer: The Inline Form Errors module has that functionality:

IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.

The Drupal 7 release is only in alpha but I'd say it's worth a try. Even if there are issues, it should give you a good place to start to implement your own version. This is the module screenshot:
Comment: This module is really old. I tested it out but it is so bad in terms of customizations. Sadly unuseful for Forms you have already created without these clicky creations of forms.


Prevent Search Results Being Truncated - Drupal 7

Question: Is there a way to prevent Drupal from truncating the search results?
That is, I do not want the search results shortened with a "..." added to the end of the result. I would like the full text.
Cheers in advance.
Answer: Yes, there is. Copy the /modules/search/search-result.tpl.php file into your theme directory. Then modify it like this:
  <?php /* this is just so it will be easier to access the body of the node */ ?>
  <?php $node = $variables['result']['node']; ?>
  <li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

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

  <?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>>
    <?php /* this part is modified, you could display different data then the body */ ?>
    <?php print $node->body[$node->language][0]['safe_value']; ?>

  <?php endif; ?>
  <?php if ($info): ?>

<?php print $info; ?>

  <?php endif; ?>

Note Like I said in the comment, it's easy to display content from some other field, not just the body. To see what data you have to play with do:
 <?php echo '
';
       print_r($variables);
       echo '
';
 ?>

Answer: You can rewrite the snippet by preprocessing the search results. Replace test in the module name below with the name of your module and you'll be good to go. I don't really know my way around D7 yet, but I think the 'und' part of the node array implies that you're only using one language on your site.
function test_preprocess_search_result(&$variables) {
  $variables['snippet'] = $variables['result']['node']->body['und'][0]['safe_value'];
}

Comment: Both are still valid @KristerAndersson sometimes people prefer a theme solution rather than a module solution.
Comment: That's true, I actually tried the `theme_preprocess_search_result` at first but I like templates=)


Parallelogram and triangle

Question: Could you please help me with this geometric task, as I cannot solve it by myself?

Given:  On the side CD of parallelogram ABCD is given point T, and
point R is on the segment AT.
Find :What percent of A(ABCD) is A(BTR) if:
A) R is in the middle of AT
B) AR : TR = 3 : 2

Thank you in advnace! I'd be grateful if you could help me.
Comment: Provide a diagram and your attempt to make your question more well received!!
Comment: Diagram is wrong....You have marked $T$ on $CB$ not $CD$...
Comment: What is $s(ABCD)$?I knew $ar(ABCD)$ which denotes area...what is $s$?
Comment: Is the position of $T$ on $CD$ not specified?
Comment: No, it is not specified.
Comment: Yeah, that happens when I hurry. Let me fix it!
Answer: Hint:
How the following triangles are related?

I hope this helps $\ddot\smile$
Comment: Thank you for this picture! :)
Answer: By the formula of area of triangle and parallelogram we have:
A(ATB)=A(ABCD)/2
A(BTR)/A(ATB)=TR/TA
So A(BTR)/A(ABCD)=TR/(2TA)
So the answer for A) is 1/4 and the answer for B) is 1/5
Comment: Thank you very much! That's the answer.
Comment: Until when the first-timers of SE will put the mark of the best answer to the first one they see? One thing is "a satisfactory answer" and another thing is "the best answer" which involves  a comparison with others. Many times this mark of the best answer is put having just one answer.(This comment has nothing at all against this answer of @Momo)
Comment: I understand what you mean, but as there aren't more answers, I accept this one. :)
Comment: @SuperMan: In your case your choice is justified because you have had ocassion of comparison but lately many beginners in SE put "best answer" at the first one received (which often is clearly inferior to others received after). I think the solution to this irregularity in language can be avoided changing "best answer" by "satisfactory answer".

Parallelogram and triangle


Need Immediate Roaming Profile / Folder Redirection file save with RDS Farm Windows Server 2008

Question: I have roaming profiles set up with additional folder redirection deployed by GPO in a 2008 R2 RDS farm environment.
They are working well, but files added to folder locations in the profile (such as saving a file to the desktop) only replicate to the redirected location at logout.
Is there any way I can set this up so files are immediatley saved to the network location while the user is working prior to logout? My concern is that in the event of a server crash a user could lose hours of working data.
Thanks in advance, any relevant info one way or the other will get a vote.
Answer: You can do two things:

Have your users save their files to the redirected folders, such as My Documents, rather than saving to a folder in the roaming profile, such as the desktop.
Redirect their desktop folder.
Comment: I did redirect the desktop, and I see the redirected folder structure but the changes are still only committed at logoff. I take it that something is wrong?
Comment: @Az. if redirection setup is configured correctly, then all reads and writes will go directly to the new location.
Answer: I have just been reading up on this too and found this:
◦By default, roaming user profiles are saved to the server only at logoff. Thus, to ensure that changes to the user profile are saved back to the server (if, for example, the user does not frequently log off) it is recommended that you enable the following Group Policy which is new in WS08 R2:
Computer Configuration -> Administrative Templates -> System -> User Profiles -> Background upload of a roaming user profile's registry file while user is logged on
Hope this helps


How can you hide "Your search yielded no results." when no keywords have been entered on the search page?

Question: On the core default search page located at /search/node, if you visit this URI the page displays "Your search yielded no results." It displays this message whether keywords have been entered that truly have no search results, as well as when no keywords have been entered. It is odd to be presenting "Your search yielded no results." to users when they have yet to actually search for anything.
What's the most appropriate way to remove this message when no keywords have been entered?
Answer: First find out how this string got there in the first place. Simply search your codebase for the exact string Your search yielded no results.. In a Vanilla Drupal you'll find only 6 occurrences of this string. 5 of them in tests, and only one in a controller, the SearchController.
Looking into the SearchController you'll see that this string is part of a render array. Keyed as '#empty' and themed with '#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],. This means you can target that pretty easily with a preprocess function. Let's go for item_list__search_results since you don't know of any plugin yet.
In your theme or module implement hook_preprocess_HOOK. Replace hook with your theme or module machine name and HOOK with the '#theme' key from earlier.
Now find out if any search query has been entered at all via if \Drupal::request()->query->has('keys'), and for safety let's also check if there's an 'empty' key in the $variables and then unset it. If you want you can tighten the condition now also on the plugin you'll find in $variables['context']['plugin'].
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE/MYTHEME_preprocess_item_list__search_results(&$variables) {
  // ksm($variables);
  if (!\Drupal::request()->query->has('keys') && isset($variables['empty'])) {
    unset($variables['empty']);
  }
}

Hint: Use the Devel sub-module Kint and its debugging function ksm() to have you any variable pretty-printed in the messages block of your site for easy debugging.
Comment: This answer is super close but contains a syntax error (missing `)` in the condition) and a logic error. It may not have been clear in my question but I'm only concerned about hiding the message when `keys` is *not* set. If `keys` exists in the query string but is empty, Drupal throws a "Please enter some keywords" message. The desired condition becomes `if (!\Drupal::request()->query->has('keys') && isset($variables['empty'])) ...`. Great answer and hints - I'll gladly accept if the above changes are made!
Comment: @komlenic – Ah yeah, that wasn't clear to me. And I also didn't experience this #empty-string on just visiting /search/node. This didn't trigger that string for me. Only when I hit the search button the #empty-string was triggered along with the `Please enter some keywords` message. Answer updated according your input.


Chi square or glm?

Question: My research is question is: does the temperature at which a certain species of bacteria is incubated affect its growth?
I have two agar plates, each incubated at different temperatures. I counted the number of colonies in each one and got counts of 14000 and 1000. Since count data is discrete, I know I should use either a GLM or a chi square test. However, I am unsure which one I should use.
Could someone please help me choose the most appropriate test? I would really appreciate any advice.
Edit: my dataset looks like this:
<code>               colony count at each temperature
Experiment no.   20 degrees     30 degrees
1                 14000           1000
2                 12100           800
3                 11500           1200
</code>
Comment: Usually bacterial counts aren't treated as counts of individual entities.  If you were sampling from environmental waters, they might be treated like a concentration (cfu / 100ml). In any case, if you have just two measurements, there is probably no value in conducting a statistical test.
Comment: What is your research question ?
Comment: @PeterFlom-ReinstateMonica  I think N might be 3 ! Anyway, working on the assumption that the RQ is along the lines of "are the counts different on the two plates ?" the question states that the other plates have similar counts, so with around 1,000 vs 14,000 this should be a case of common sense prevailing over the need for any statistical test. Of course they are different :)
Comment: @SalMangiafico As mentioned in my edit, I have similar counts for two more sets of plates.
Comment: Even with N = 4, nothing is likely to be very effective, statistically. But please answer @RobertLong's question about your RQ (and put that in your question).
Comment: @RobertLong I am trying to see if incubating the plates at a higher temperature significantly reduces the number of cfu's. Also, although it's obvious the difference is clearly significant here, I also have another set of data where the difference is less obvious. So I would like to know which test would be appropriate.
Comment: @Anya as Peter mentioned, please edit the question to add this info, and at the same time please provide full information about your other dataset
Comment: Are the sets of plates grouped somehow, eg, incubated together?  Can you paste in your dataset?
Answer: Since your research question involves a dependent variable (number of colonies) and an independent variable (temperature) you want regression. But you a) Should include all your plates in one regression and b) Will almost certainly need more data to get useful statistical tests, unless the relationship is very strong and clear.
I am not sure what "sets of plates" means. That is, are these sets somehow disginguishable from one another (different species or something?)  If so, that will have to be dealt with as well.
It's true that OLS regression demands a continuous dependent variable and you have one that is counts. For count data, you can use Poisson or negative binomial regression. But, if all the counts are this high (thousands) then it probably won't make much difference.
Comment: @Anya, You have a very good answer here.  Your best bet is to set the independent variable as either a continuous variable or a 2 factor categorical variable and your dependent variable a continuous variable.  Therefore either regression, or t-test is a better bet.  In no case is a Chi-square test a good choice for this problem.  See http://rcompanion.org/handbook/, the section on choosing a statistical test.
Comment: (+1) nice, Peter !
Comment: Thank you so much for the detailed answer. When I wrote sets of plates I should have been more clear but what I meant is I repeated the same experiment with the same species two more times. Could I please ask you to explain why a chi square test would be unsuitable? Is it because there is only one independent variable?
Comment: @ulfelder No we only used two temperatures so I think I will do a chi square test.

Chi square or glm?


Trazer informações deduas tabelas "models" relacionadas através do ObjectId em uma única rota de API

Question: Tenho duas tabelas "models" relacionadas através do ObjectId, como faço para que a API traga a informação das duas tabelas em uma única chamada ?
const Corporacao = mongoose.model('Corporacao',{
    nome: String,
    razao: String,
    cnpj: String,
    status: Boolean,
})

const Unidade = mongoose.model('Unidade',{
    nome: String,
    corporacao_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Corporacao'},
    razao: String,
    status: Boolean,
})

Na minha rota de API
//Buscar Unidade por ID
router.get('/:id', async (req, res) =>{
    // extrair o dado da requisição, pela url = req.params
    const id = req.params.id

    try {
        const unidade = await Unidade.findOne({_id: id})

        if(!unidade) {
            res.status(424).json({message: 'Unidade não foi encontrada'})
            return
        }

        res.status(200).json(unidade)
    } catch (error) {
        res.status(500).json({error: error})
    }
})

Como eu faço para ao buscar a Unidade já trazer informações sobre a Corporação ?
Answer: Consegui resolver alterando a busca para:
const unidade = await Unidade.findOne({_id: id}).populate('corporacao_id');

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How to assign value after increment Swift?

Question: var str = ["Franc": 2]
var a = 1
str["Franc"] = a += 1
print(str)

When I try this code i get an error on line "str["Franc"] = a += 1" that  is "Cannot assign value of type '()' to type 'Int?'"
How to solve this. I need it in single line
Thank you in advance
Comment: Essentially a duplicate of [Multiple variable assignment in Swift](https://stackoverflow.com/questions/26155523/multiple-variable-assignment-in-swift).
Comment: See also [increment Error in swift 3](https://stackoverflow.com/questions/39704971/increment-error-in-swift-3)
Comment: What I mean is set value of "a" to dictionary and then increment. How can it possible in one line
Answer: We can do this directly only in Objective C:
In Objective C:
[str setValue:[NSNumber numberWithInt:a+=1] forKey:@"Franc"];

In Swift
str["Franc"] = a
a += 1

Comment: This is the only possible way?
Answer: You can increment number like this
str["Franc"]! = a ; a += 1

assign value
var str = ["Franc": 2]
str["Franc"]! += 1

and now str["Franc"] will returns 3
And if you want to avoid force unwrapping
str["Franc"] = (str["Franc"] ?? 0) + 1

Also you can do it using if let
if let num = str["Franc"] as? Double {
    str["Franc"] = num + 1
}

Comment: `str["Franc"]! = a ; a += 1` thats how you can do it in one line ...
Comment: What I mean is set value of "a" to dictionary and then increment. How can it possible in one line
Answer: I don't think you can do this in a single line:
var str = ["Franc": 2]
var a = 1
str["Franc"] = a
a += 1
print(str)

Comment: I don't think you can do both in a single line.
Comment: You didn't increment `a` in your answer, and it looks like it is something OP wants.
Comment: What I mean is set value of "a" to dictionary and then increment. How can it possible in one line
Comment: Ok my mistake miss read the question, so you want to add a to the dictionary then increment the dictionary value or then  increment a?


Cutoff at critical point is extremum?

Question: Let $U$ be some domain in $\mathbb{R}^n$ with $0\in U$. We have some $C^2$ function $f: U \rightarrow \mathbb{R}$ with $\nabla f(0)=\mathbf{0}$, therefore 0 is a critical point (i.e. local maximum, local minimum or saddle point). Define $U^+=:\{\mathbf{x}\in U: x_n\geq 0 \}$ and $f^+: U^+\rightarrow \mathbb{R}, x \mapsto f(x)$.
Is $0$ an extremum of $f^+$ and if yes how could we prove it?
For example, in case of $n=1$ we have $U=\mathbb{R}$, $f(x)=x^3$. Then $0$ is a saddle point of $f$, but $0$ is obviously a local (and global) minimum of $f^+: [0,\infty) \rightarrow x^3$. How could I prove this (and in the general case)?
Thank you for any ideas and pointers.
Comment: You mean if $U = \mathbb{R}^2$, then $U^+ = \mathbb{R} \times [0, \infty)$, right?
Comment: Well in that case $n$ would be 2, and we would need a function $f$ that takes 2 arguments.
Answer: No. As a counterexample, take a function $f_0 : \mathbb{R} \to \mathbb{R}$ with a saddle at the origin (e. g. $f_0(x) = x^3$) and then
$$ f: \mathbb{R}^2 \to \mathbb{R}, \quad f(x, y) = f_0(x), $$
its constant extension in $y$-direction.
Then the point $0$ is a critical point of $f$ and its cutoff $f^+$ to non-negative second coordinate $\{y \geq 0\}$ still does not have an extremum in $(x, y) = (0, 0)$ (because $f(x, 0) = f_0(x)$ has a saddle in $x=0$).
The one-dimensional case is special though and your statement works. The proof is by the monotonicity criterion from the Mean Value Theorem (see https://proofwiki.org/wiki/Real_Function_with_Positive_Derivative_is_Increasing).
Comment: I might have poorly worded my question. $f^+$ should be the restriction of $f$ onto the same set but with positive last coordinate. In your counterexample $f_0$ is 1-dimensional, but $f$ is 2-dimensional. But I think my claim is still wrong. I need to think about it a bit and will update my question accordingly, thank you.
Comment: $y \geq 0$ means restricting to non-negative last coordinate. The counterexample is $f$, not $f_0$ (from which it is built).

Cutoff at critical point is extremum?