Serre's vanishing theorem and global generation.

Question: Given a short exact sequence of coherent sheaves on a projective variety if we tensor the sequence with $\mathcal{O}(n)$ with a high enough $n$, everything becomes globally generated and by Serre's vanishing theorem taking the global sections becomes exact. I wonder whether it is possible to prove this without Serre's vanishing theorem. Serre's theorem applies for the proper varieties, I wonder whether the fact mentioned above remains true for let's say if we remove a high codimension subvariety from a projective variety? Like $\mathbb{P}^2\setminus \text{pt}$.
Answer: Let $L$ be a line through $p\in\mathbb{P}^2$ and let $X=\mathbb{P}^2-\{p\}$ and $M=L-\{p\}$. You have an exact sequence of coherent sheaves, $0\to O_X(-1)\to O_X\to O_M\to 0$. Easy to see that $H^0(O_X(n))\to H^0(O_M(n))$ is not surjective for any $n$, since $H^0(O_M(n))$ is not finite dimensional over the base field.
Comment: Dear Mohan, allow me to add (for the benefit of beginners) a few explanations to your splendid example. The point is that every line bundle on $X$ extends to $\mathbb P^2$. This is because on a smooth variety line bundles are represented by Weil divisors, which extend through codimension $\geq 2$ closed subvarieties: see Hartshorne Proposition 6.5 (b). From there we can apply Hartogs's theorem (Hartshorne, Chapter I, Exercise 3.20 (a)) and deduce that the canonical restriction map $H^0(O_{\mathbb P^2}(n)) \to H^0(O_X(n))$ is bijective, so that $H^0(O_X(n))$  is indeed finite-dimensional.
Comment: @GeorgesElencwajg Thank you for your expansions and clarifications. Will help the beginners .
Comment: Dear Mohan, it is a pleasure for me to be able to comment on an answer of such high quality.


Is there a git style amend option in TFVC?

Question: In git there is a very handy feature that lets you fix your last commit, e.g. when you have forgotten something that does not justify a full commit.
It is very easy to do this in git:
<code>git commit --amend
</code>
That way you don't have to specify a commit message or anything else, the commit is simply "appended" to your last full commit - or at least that is how I understand it.
Is there anything similar available in TFVC?
Answer: No, not really. You can update the Check-in comment, or associate a work item, but you cannot change the file contents of the check-in. A rollback doesn't help either, since that will add yet an additional compensating checkin to the history, making it even harder to understand.
To update the message, open the TFVC history panel and right click a changeset. Choose Show Changeset Details and you'll be able to update the Check-in comment and optionally the check-in notes.
To associate to a new work item make note of the changeset number, open the work item and go to the links tab. Click add-link and chose the link type "Changeset", supply the number and save the work item.
Comment: @jthill, when using Git on TFS, you have Amend support. But when using TFVC you don't.
Comment: Seems what TFS offers as "git" is, ahhh, limited, in "minute, subtle, and utterly effective" ways.


Is turning 'ordered' categorical data into numerical data advantages?

Question: Let's say we want to predict house prices and have the following 3 features with their possible categorical values:
Slope of land property:
1) Gentle
2) Moderate
3) Severe
Type of utilities available:
1) All public Utilities
2) Electricity, Gas, and Water
3) Electricity and Gas
Style of dwelling:
1) 1s - One story
2) 1.5s - One and one-half story
3) 2s - Two story
Would it be acceptable/advantages to turn all those values into 1,2,3 integers (numerical data)? On the one hand it makes sense since e.g. 1s building is worse than 1.5s building which is worse than 2s building. On the other hand it's possible that the gap between 1s and 1.5s is much bigger than between 1.5s and 2s. How common/uncommon is this practice?
Comment: What is the problem with treating these as categorical regressors in your model?  Do you have so few data that you might be worried about losing degrees of freedom?
Comment: I understand feature engineering as a way of helping the algorithm to capture the right trend of the data. For example if I try to model the relationship between money and happiness and I know that 1 mil more makes you less happier when you are rich than when you are poor I might take a log of wealth feature and help the accuracy of my algorithm. Similarly, explicitly giving my algorithm the order of my feature might improve it. But I don't really know.. I'm new to ML.
Comment: Search our site for methods of representing ordinal predictors. The point here is that you've very few distinct values in any case: in a regression model, say, even treating the predictors as continuous, you'd only use six degrees of freedom to represent each with a quadratic basis function - equivalent to treating them as categorical.
Answer: There is no good reason to do this. The only this would be justified is if, as you say, the distances between categories are equal. Since you have only a few categories per variable, there is no reason to make this assumption. This may be an occasionally used practice, but that doesn't mean it's right. When you're dealing with scale scores on a survey of a psychological variable, taking the sum of many 3-category items to form a sum score might violate my previous advice, but in general it is robust to the violation of that assumption for each item. As independent variables, you should definitely retain the categories.


How to analyze data which has varying amounts of measurements recorded?

Question: I'm doing research which involves data pertaining to the physical characteristics, recorded at consistent intervals, of mice, with the mice's time at death being recorded as well. As such, some mice have more timepoints recorded than others. How should I approach modelling this?
I've considered using a hierarchical linear model, but I admittedly am not especially knowledgeable about this sort of analysis and was curious if anyone had suggestions. There are a large number of total datapoints for several hundred individual mice, so I had initially planned on using a neural network before I saw the variety of recorded data. Is there a way I could implement this approach in these circumstances? Or would this be unnecessary? Thanks for any help.
Edit: Basically, I have information pertaining to these mice over time, with data being collected every 4 weeks or so, and including blood glucose levels, food intake, and other similar metrics. There is also discrete information, such as the genetic strand of the mice, and lastly a "time of death" value. Because the mice died at very different times, certain things, such as food intake, have data corresponding to shorter or longer time periods (so every 4 weeks for 18 months versus every 4 weeks for 5 months depending on how long it lived). I'd like to make a model to determine which of these factors are most significant in how long these mice lived for, i.e. which provides the best information for predicting how long these mice will live. Hope this clears things up.
Comment: Welcome to CV :) Please edit your question to provide more details. Please let us know your research question, and describe the dataset that you have. Depending on the purpose, a hierarchical linear model (or mixed effects model) could be suitable, or maybe a survival model, but we need more details in order to advise further.
Comment: Seems like survival analysis would be a good starting point, at least.
Comment: Ok, I just added some edits to make things more clear
Answer: In principle, you could use a Cox survival regression with time-varying covariate values. The process, using the "counting process" data format, is explained in a vignette of the R survival package.
You set up a separate row for each time interval over which an individual has a constant set of measured values (e.g., each 4 weeks or so in your data). Each row contains the start and stop times of the interval, the covariate values in place during the interval, and an event indicator of whether the individual was alive or dead at the end of the interval.
The problem is defining useful values of time-varying covariates. A typical survival model assumes that the current risk of an event (death in your data) is related to the current values of the covariates. In this type of study, some aspect of the history of covariate values might be better associated with the current risk. You would have to apply your understanding of the subject matter to come up with a way to incorporate that history into the time-varying variables you supply as predictors to the model.
You might also consider a "joint model", combining a model of the longitudinally observed covariates along with a model of time to death. There are several packages available for such modeling noted in the R Survival Task View. A vignette in one of those packages, rstanarm, explains the approach:

Joint modelling can be broadly defined as the simultaneous estimation of two or more statistical models which traditionally would have been separately estimated. When we refer to a shared parameter joint model for longitudinal and time-to-event data, we generally mean the joint estimation of: 1) a longitudinal mixed effects model which analyses patterns of change in an outcome variable that has been measured repeatedly over time (for example, a clinical biomarker) and 2) a survival or time-to-event model which analyses the time until an event of interest occurs (for example, death or disease progression). Joint estimation of these so-called "submodels" is achieved by assuming they are correlated via individual-specific parameters (i.e. individual-level random effects).

That differs from the approach in the Cox model, which simply takes the covariate values as given and doesn't try to model the trajectories of their values over time. A joint model thus provides information about the covariates that a Cox model doesn't.
Comment: I thinks this is great advice (+1)


Split VMWare's Hard Drive

Question: I've got a virtual machine with an 8 gig hard drive in one file.  I want to now split virtual hard drive into 2 gig chunks so I can copy the VM onto a FAT32 drive.  Is this possible?
Answer: This can be done using the vmware-vdiskmanager.exe program
Quote from www.luisrocha.net:

For a growable virtual disk, use the following command to split into 2 GB:

vmware-vdiskmanager.exe -r old.vmdk -t 1 new.vmdk or

For a preallocated virtual disk, use the following command to split in 2 GB:

vmware-vdiskmanager.exe -r old.vmdk -t 3 new.vmdk

Also see:
VMWare Server FAQs (Look for "What are the pros and cons of the different disk types"
Comment: This is of course assuming you are using VMware's workstation product.  Some of the other products use a utility known as "vmkfstools", but the general concept is the same.
Comment: My VMware Server 2 machine also has `vmware-vdiskmanager`
Answer: Probably the only way to do that would be to download the VMware converter and use that to migrate to a new virtual machine which is configured for 2 Gig files.
It would probably be easier to simply convert the destination hard drive to NTFS.
Comment: This is overkill. You can easily convert an existing disk without creating a whole new virtual machine.
Comment: Oh, excellent.  Didn't know you could split the disk like that.
Answer: Rather than mess with the .vmdk I'd strongly advise you to use RAR or ZIP to compress and split the single file into multiple <2GB files - then expand them at their destination - that way you're not fiddling with the actual VM, just packing it differently for transportation.
Comment: No, I think it now needs to reside on a FAT32 drive -- so he can't expand it on a FAT32 partition because it can't handle files this large.
Answer: haven't tried splitting virtual disk but I think that won't be complicated. I used to split HDD with partitionguru and I remember this tool supports virtual disks generated by Vmware. Since it's a free tool, you may as well have a try

Split VMWare's Hard Drive


UNION within multiple if statements

Question: I am essentially trying to write a query that will look at multiple databases and then union the results. As of right now I get all the correct results, without the union.
Here is my current query:
SET NOCOUNT ON
DECLARE @DBName VARCHAR(3)
    SET @DBName = 004
DECLARE @join VARCHAR(10)
    SET @join = 'UNION ALL'
DECLARE @statement VARCHAR(100)
DECLARE @loopcounter INT
    SET @loopcounter = 1
WHILE @loopcounter < 102

BEGIN
IF @DBName IN (004,005,011,012,021,026,027,028,038,039,044,045,050,051,052,053,054,057,060,061,062,063,066,069,073,074,075,076,079,083,084,
           085,086,087,088,089,090,091,092,093,094,095,098,099,100,105,106,107,108,109,110,111,112,116,121,122,126,127,128,129,130,131,
           132,136,137,138,139,140,141,142,143,144,149,150,151,152,153,154,155,156,159,164,165,166)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 1
        SELECT @statement
        UNION ALL
        SELECT @join
END
IF @DBName IN (013,015,017,019,022,024,032,046,048,055,058,064,067,077,096,101,103,117,119,145,147,157,160,162)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 2
        SELECT @statement
        UNION ALL
        SELECT @join
END
IF @DBName IN (029,070,080,113,123,133,167)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 3
        SELECT @statement
        UNION ALL
        SELECT @join
END
IF @DBName IN (034,040)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 4
        SELECT @statement
        UNION ALL
        SELECT @join
END
IF @DBName IN (006)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 5
        SELECT @statement
        UNION ALL
        SELECT @join
END
SET @loopcounter = @loopcounter + 1
END
SELECT 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'

My results as is:
----------------------------------------------------------------------------------------------------
SELECT * FROM a0040040.HTL004.dbo.zz_tb_transactions_base
UNION ALL

----------------------------------------------------------------------------------------------------
SELECT * FROM a0050040.HTL005.dbo.zz_tb_transactions_base
UNION ALL

----------------------------------------------------------------------------------------------------
SELECT * FROM a0060040.HTL006.dbo.zz_tb_transactions_base
UNION ALL

----------------------------------------------------------------------------------------------------
SELECT * FROM a0110040.HTL011.dbo.zz_tb_transactions_base
UNION ALL

----------------------------------------------------------------------------------------------------
SELECT * FROM a0120040.HTL012.dbo.zz_tb_transactions_base
UNION ALL

How can I get my results to union:
SELECT * FROM a0040040.HTL004.dbo.zz_tb_transactions_base
UNION ALL
SELECT * FROM a0050040.HTL005.dbo.zz_tb_transactions_base
UNION ALL
SELECT * FROM a0060040.HTL006.dbo.zz_tb_transactions_base
UNION ALL
SELECT * FROM a0110040.HTL011.dbo.zz_tb_transactions_base
UNION ALL
SELECT * FROM a0120040.HTL012.dbo.zz_tb_transactions_base
UNION ALL

Any ideas?
Comment: SQL Server 2008 by the way
Comment: I'm not quite sure i get waht you want, but, since your in a loop, can't you just concat the @statement variable and select it in the end once (offcourse varchar(200) needs to be bigger) Or do you want it in seperate rows? If so, create a temp table and insert a row for each statement and select all from the temp table in the end?
Comment: The @statement variable is constantly needing to be ran. It is being ran about 100 times because I need it to change for each database...a004...a005...a006...etc.
Answer: Something like this? (a bit simpler then your example, but for the idea :)  )
declare @db varchar(3) = '000'
declare @counter int =1;

create table #testt(testc varchar(20))

while @counter <100
begin
insert into #testt values(@db + CAST( @counter as varchar(20)))
set @counter = @counter +1
END

select * from #testt
drop table #testt

EDIT, based on your comment - the idea still works (although im still not completely sure what result you expect):
DECLARE @DBName VARCHAR(3)
    SET @DBName = 004
DECLARE @join VARCHAR(10)
    SET @join = 'UNION ALL'
DECLARE @statement VARCHAR(100)
DECLARE @loopcounter INT
    SET @loopcounter = 1

create table #result(query varchar(200))

WHILE @loopcounter < 102

BEGIN
IF @DBName IN (004,005,011,012,021,026,027,028,038,039,044,045,050,051,052,053,054,057,060,061,062,063,066,069,073,074,075,076,079,083,084,
           085,086,087,088,089,090,091,092,093,094,095,098,099,100,105,106,107,108,109,110,111,112,116,121,122,126,127,128,129,130,131,
           132,136,137,138,139,140,141,142,143,144,149,150,151,152,153,154,155,156,159,164,165,166)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 1
END
IF @DBName IN (013,015,017,019,022,024,032,046,048,055,058,064,067,077,096,101,103,117,119,145,147,157,160,162)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 2
END
IF @DBName IN (029,070,080,113,123,133,167)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 3
END
IF @DBName IN (034,040)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 4
END
IF @DBName IN (006)
BEGIN
IF @DBName < 010 SET @statement = 'SELECT * FROM ' + 'a00' + @DBName + '0040.HTL00' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName BETWEEN 011 AND 099 SET @statement = 'SELECT * FROM ' + 'a0' + @DBName + '0040.HTL0' + @DBName + '.dbo.zz_tb_transactions_base'
IF @DBName > 099 SET @statement = 'SELECT * FROM ' + 'a' + @DBName + '0040.HTL' + @DBName + '.dbo.zz_tb_transactions_base'
    SET @DBName = @DBName + 5
END
SET @loopcounter = @loopcounter + 1

insert into #result values(@statement), ('union all')
END
SELECT * from #result

drop table #result

Comment: Well the issue is that it isn't every one, so it goes 4,5,6,11,12,13,15, etc...I work for a hotel company and the numbers are based on properties and some have closed down. So I have to use the IF statements so it skips the ones that do not exist, but I think I may be able to get something out of what you have there.
Comment: See update, i only removed your last line, this could be inserted the same way offcourse
Comment: Perfect, your first idea got me to it, but it works perfectly now. Thanks for the help!

UNION within multiple if statements


Liferay + JSON + AJAX

Question: I have a code
@RenderMapping
    public ModelAndView model(RenderRequest renderRequest, ModelMap map) {

        map.put("form", form);

        ModelAndView view = new ModelAndView("view", map);

        PortletSession portletSession = renderRequest.getPortletSession(true);
        if(portletSession != null) {
        MappingJacksonJsonView v = new MappingJacksonJsonView();
        view.setView(v);
        view.addObject("dataListCustomer", portletSession.getAttribute("listCustomer"));
        }

        init(renderRequest, view);
        return view;
    }

I have an error:
java.lang.IllegalArgumentException: application/json is not a supported mime type
    at com.liferay.portlet.MimeResponseImpl.setContentType(MimeResponseImpl.java:159)

Error is caused by view.setView(v);
How can I added listCustomer to JSON? In listCustomer I have a ModelMap

I have code:
    @ResourceMapping(value="customer")
        public ModelAndView customer(
                ResourceRequest req,
                ResourceResponse res) {

    log.debug("List Customer Resource: " + context.getCustomer());

            ModelAndView mav = new ModelAndView();
            MappingJacksonJsonView v = new MappingJacksonJsonView();
            v.setBeanName("ajaxResult");

            mav.setView(v);
            mav.addObject("customer", context.getCustomer());

            return mav;

}

Customer is set in @ActionMapping function and it is OK.
In JSP I have:
<portlet:resourceURL escapeXml="false" id="customer" var="customer"/>

How can I call @ResourceMapping function? Because I don't see result of  log.debug("List Customer Resource: " + context.getCustomer()); in logs.
Comment: See sample example of Liferay AJAX.

http://stackoverflow.com/questions/17592144/respond-to-http-request-with-json-object-in-portlet/17593935#17593935
Comment: See sample example of Liferay AJAX.

http://stackoverflow.com/questions/17592144/respond-to-http-request-with-json-object-in-portlet/17593935#17593935
Answer: For ajax (with portal) you cannot use RenderMapping (or ActionMapping), you must use ResourceMapping (and if needed ResourceRequest and ResourceResponse as method parameters).
For example, not using spring but change is trivial, see this SO answer.

Liferay + JSON + AJAX


Could Hawkeye tell us the probability of runs and wickets from a given ball?

Question: Suppose the information recorded by Hawkeye was combined with information about the number of runs scored (including boundaries, but excluding overthrows) and wickets taken in each delivery.
An enterprising new bowler might want to know the types of delivery that reduce the runs and increase the likelihood of wickets, or an experienced first-class bowler may want to know what types are affecting their productivity.
Could a large enough amount of Hawkeye data be used to calculate expected runs and expected wickets for each delivery?
Comment: *[This question originally asked](https://area51.stackexchange.com/proposals/102995/sports-analytics/103026#103026) by **[Steve](https://stackexchange.com/users/9221695/steve)** on proposal Sports Analytics, which recently closed.*
Answer: Yes, here is some work on calculating expected runs and expected wickets.
Comment: Link-only answers are prone to linkrot and the Princess-Castle problem. Please expand on the information in the links and provide your own commentary/explanation where appropriate.


Spring tutorial noClassDefFoundError

Question: I am following the Spring tutorial located  here (link is to chapter 1, but I'm currently on chapter 2, part 2.2). I have about 2 years experience with Java from college, but I have never done anything with Spring before, which is why I thought a step by step tutorial would be helpful.
The problem is, the tutorial provides a link to download all the necessary jar files, but the link now points to the spring projects page. The "Spring Framework" link there seems to require you to download it from GitHub, which I did, but there doesn't seem to be any jar files in this download. So whenever the tutorial said to use a certain jar file, I just Googled it and found it somewhere else, and everything seemed to work fine.
So here is the problem: on step 2.2 "Improve the controller" I have followed the instructions and get to the part that says

"We rerun our 'tests' target and the test passes"

but as you might have guessed, it did not work for me, giving the following error:
[junit] ------------- Standard Error -----------------
[junit] May 13, 2014 8:40:40 AM springapp.web.HelloController handleRequest
[junit] INFO: Returning hello view with Tue May 13 08:40:40 BST 2014
[junit] ------------- ---------------- ---------------
[junit] Testcase: testHandleRequestView(springapp.web.HelloControllerTests):
    Caused an ERROR
[junit] org/springframework/ui/ModelMap
[junit] java.lang.NoClassDefFoundError: org/springframework/ui/ModelMap
[junit]     at org.springframework.web.servlet.ModelAndView.getModelMap(Mode
lAndView.java:205)
[junit]     at org.springframework.web.servlet.ModelAndView.addObject(ModelA
ndView.java:227)
[junit]     at org.springframework.web.servlet.ModelAndView.<init>(ModelAndV
iew.java:127)
[junit]     at springapp.web.HelloController.handleRequest(HelloController.j
ava:26)
[junit]     at springapp.web.HelloControllerTests.testHandleRequestView(Hell
oControllerTests.java:13)
[junit] Caused by: java.lang.ClassNotFoundException: org.springframework.ui.
ModelMap
[junit]     at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
[junit]
[junit]
[junit] Test springapp.web.HelloControllerTests FAILED
BUILD FAILED

I have Googled NoClassDefFoundError, and one of the causes seems to be missing jar files. I think that is the case here, since I found them all through Google.
So my question is, am I correct in assuming that this is the problem, and if so does anyone know what jar file I am missing and where to find it? Or has anyone completed this tutorial before and can provide me with these jars?
Thanks in advance!
EDIT: These are the jars that i currently have in war/WEB-INF/lib, they have all been added to the build path:
commons-logging-1.1.3.jar
servlet-api.jar
junit-4.11.jar
jstl.jar
standard.jar
spring-webmvc.jar
spring.jar

Comment: The tutorial you are following is pretty old!!! I suggest you check out the tutorial here https://spring.io/guides/
Comment: Yes, it is pretty old, but it was the first one that I found with "step-by-step" in the title, so I thought it would be perfect. I didn't realize how old it was until I was on chapter 2! Anyway, I'll check out the tutorials you linked to, hopefully they will be more useful.
Comment: That's a good idea. If you have any problems, SO is always here to help :)
Comment: In response to Imran: 1) I have the jars in the Web-Inf\lib folder, I have edited my question with all the jars in there 2) I'm not sure what you mean by "Deployment Assembly", do you mean add to build path?  The answer in the question that you linked to suggests that there might be a conflict between duplicate classes in the jar files, so I removed spring-webmvc.jar and got some errors in eclipse, and spring.jar which gave me the same NoClassDefFoundError error. Also, I am not using maven as the tutorial does not mention it at all
Comment: You probably should have added the comment to the specific answer :)
Comment: Good idea, just did that, thanks :)
Answer: IN Dynamic web project you need to make sure two things regarding this  java.lang.NoClassDefFoundError:  error

Place all requires Jar in Web-Inf\lib folder
Add these jars reference in Deployment Assembly as well.

Right now you are missing Jar that is required by Spring at run-time.. Please see details here
java.lang.ClassNotFoundException: org.springframework.ui.ModelMap
There may be the other reason if you are using maven etc..
This error org/springframework/ui/ModelMap means that class not found by server at load time.. Its not compilation issue, infact run-time issue..
Comment: 1) I have the jars in the Web-Inf\lib folder, I have edited my question with all the jars in there 2) I'm not sure what you mean by "Deployment Assembly", do you mean add to build path? The answer in the question that you linked to suggests that there might be a conflict between duplicate classes in the jar files, so I removed spring-webmvc.jar and got some errors in eclipse, and spring.jar which gave me the same NoClassDefFoundError error. Also, I am not using maven as the tutorial does not mention it at all
Comment: Right click of project properties in eclipse you got the tab of "Deployment Assembly"
Comment: I right click and went to Properties, but "Deployment Assembly" isn't there
Comment: I've added screenshots please see it.... ALso see..
http://stackoverflow.com/questions/2753464/java-lang-classnotfoundexception-org-springframework-ui-modelmap
Comment: Here is what I see in properties: http://s14.postimg.org/v5j5ohuch/properties.png
Comment: I think it is a regular java project. The tutorial didn't say to create web project

Spring tutorial noClassDefFoundError


In reinforcement learning, what is the formal definition of the symbols $S_t$ and $A_t$?

Question: In both the reinforcement learning course given by David Silver and the latest draft of Richard S. Sutton's RL book what is the formal definition of the symbols $S_t$ and $A_t$?
Do these definitions depend on the policy being used until time-step $t$?

Some context for the question:
I realize that this question might seem trivial, since the authors explicitly define these variables in their textbook/lecture. However, I'm currently trying to make sense of their definitions, but no interpretation I think of seems to yield a coherent/consistent notation. What follows is my line of thought, showing which interpretations I tried and why they seem to be inconsistent.
These authors seem to define the following symbols like so:
$$S_t\triangleq\text{The state we visit at time-step }t.$$
$$A_t\triangleq\text{The action we take at time-step }t.$$
Where both $S_t$ and $A_t$ are commonly treated as random variables.
However, what confuses me is that in order to properly define $S_t$ for $t>0$ it seems necessary to first define all the $S_i,A_i$, for $0\leq i <t$. Hence, it seems that the definition of $S_t$ only makes sense if we specify with which policy we're choosing our actions at all the time-steps before we reached time-step $t$.
This is already ambiguous, and personally confusing, since the symbol $S_t$ has no mention whatsoever to which policy was used to sample the actions until that point. For example, the same symbol $S_5$ can represent completely different random variables, if they're specified in different contexts with different policies being used (or different starting states).
This ambiguity didn't strike me as very impairing, since I thought one could always use, say, a superscript to indicate the policy being used at all the previous time-steps, e.g. $S_5^\pi$. Also, for most of the discussions it was very clear which policy was being used (and almost as clear what was the starting state), so it seemed harmless to drop the extra notation.
However, I later encountered definitions like, for instance, the action-value function of a state action pair:
$$ Q_\pi(s,a)=\mathbb E_\pi[G_t | S_t=s, A_t=a] $$
This is supposed to be defined for all legal actions $a$ in state $s$. However, if I interpret $S_t$ as $S_t^\pi$ and $A_t$ as $A_t^\pi$, respectively, this definition seems to break down when $a$ is an action that policy $\pi$ would never choose, or $s$ is an unreachable state given policy $\pi$ and some starting state $s_0$ (since we'll be conditioning the expectation on an impossible event). So it seems that these authors are not simply dropping the superscript I mentioned before, and instead $S_t$ and $A_t$ have some other definition.
Answer: In the summary of notation (page xvi) of Sutton and Barto's book, they define $S_t$ as:

state at time $t$, typically due, stochastically, to $S_{t-1}$ and $A_{t-1}$

This is similar to what you observed:

However, what confuses me is that in order to properly define $S_t$ for $t>0$ it seems necessary to first define all the $S_i, A_i$, for $0≤i<t$.

The main difference between the book's definition and your observation is that they only take $i = t-1$, not $0 \leq i < t$. Only that single prior step is sufficient due to the Markov property which is basically assumed to hold throughout the entire book, we're almost always talking about Markov Decision Processes.
Another difference is that $S_t$ does not require $S_{t-1}$ and $A_{t-1}$ to be well-defined necessarily, those values only happen to typically explain how we ended up where we are now ($S_t$). The obvious exception is the initial state $S_0$, which we simply end up in... out of the blue kind of.

Hence, it seems that the definition of $S_t$ only makes sense if we specify with which policy we're choosing our actions at all the time-steps before we reached time-step $t$.

This is not necessary. An agent could theoretically change their policies during an episode too. In fact, as a random variable, $S_t$ doesn't even really represent just a single value. It's a symbol that we use to denote the state that we happen to be in during some episode at time $t$, without caring about what we did before that or plan to do after it. See the wikipedia page on random variables.

\begin{equation}
Q_\pi (s,a) = \mathbb{E}_\pi \left[ G_t \mid S_t = s, A_t = a \right]
\end{equation}
This equation simply says that the value of $Q_\pi$ is equal to the returns that we expect to obtain if:

we start following policy $\pi$ from now on (it doesn't matter which policy we've been following up until now)
we happen to currently be in state $s$ (this is a specific value, this is no longer a random variable), and we happen to have chosen to select action $a$.

Note how the definition does not depend directly on what policy we've been using in the past. It only depends on the policy we've been using in the past indirectly, in the sense that that explains how we may have ended up in state $S_t = s$. But we do not require knowledge of our past policy to properly define anything in this equation, and that past policy will often not even be the only requirement for a complete explanation of how we ended up where we happen to be now. For example, in nondeterministic environments, we may also require knowledge of a random seed and a Random Number Generator to completely explain why we are where we are now. But the definition of the equation does not rely on the ability to explain this. We just take for granted that, at time $t$, we are in state $S_t = s$, and the equation is well-defined from there.
This equation happens to rely on the future policy $\pi$, but that may be a different policy from our past policy, and this reliance is denoted by the subscript on $Q_\pi$ and $\mathbb{E}_\pi$.
Comment: Hey Dennis, thanks for your time! However, I'm having some trouble digesting your answer:
- You say "Only that single prior step is sufficient due to the Markov property which is basically assumed to hold throughout the entire book (...)". I don't see how the Markov property plays any role in this. Defining $S_t$ in terms of $S_{t-1}$ and $A_{t-1}$ is ok for me, but then you need to define $S_{t-1}$, which will make you have to define $S_{t-2}$ and $A_{t-2}$, and so forth, until $S_0$.
Comment: - You also say "Another difference is that $S_t$ does not require $S_{t−1}$ and $A_{t−1}$ to be well-defined necessarily". To discuss this, I'd like to give a more concrete example: let's say I give you the full MDP dynamics (the entire tuple that defines it, including transition probabilities, reward function, etc). I argue that with this information only, $S_t$ is not well-defined. Or can you specify its probability distribution using only the information given? I think it's also necessary to completely specify the distribution (or the values) of $S_{t-1}$ and $A_{t-1}$.
Comment: @JLagana $S_t$ is just a random variable, it's not a specific value. It's the variable we always use to denote ''the state we happen to be in at time $t$''. So yes, we don't know the exact value we assign to that state until we've actually reached that point in time, but the variable that will ''contain'' that value is already well-defined, and we can already use it in the definition of various equations (we just can't compute exact numbers yet, since we can't replace the random variables with actual values/numbers
Comment: The distinction between random variables on one hand, and values on the other, is important
Comment: Hey again. I think I have the distinction between random variable and values very clear already. When I say that $S_t$ is not well-defined I *don't* mean we don't know the value that this random variable will actually take when we sample from the MDP. Instead, I mean that the probability distribution function of this random variable is not well-defined.
Comment: @JLagana Yes, that's correct, without knowledge of the MDP (transition probabilities) and the policy we're following up until time $t$, we do not know the probability distribution over values that can be assigned to the random variable $S_t$. This shouldn't be a problem in any of the equations where the book uses $S_t$ though. For example, in the equation in your question, we do not need knowledge of all the different states that $S_t$ could be; we explicitly say, assume $S_t = s$, and then go from there. The equation should be correct even if $S_t$ can't possibly be equal to $s$.
Comment: I have come up with a possible interpretation for these symbols. Please check my answer. In the interest of impartiality, I will refrain from choosing the correct answer for, say, a week. After that period I'll choose whichever answer has the most votes as the correct one. In any case, thank you again for your time, it helped me get closer to the solution.
Answer: I came up with one possible interpretation of these symbols that seem to be consistent with all the material I've seen so far in these courses.
As pointed out in Dennis Soemers' answer, Sutton's book define $S_t$ as:

state at time $t$, typically due, stochastically, to $S_{t−1}$ and $A_{t−1}$

The "typically due" led me to think that perhaps $S_t$ doesn't refer to the same thing in all contexts. Maybe, $S_t$ in one context is actually a random variable, with a distribution that depends on $S_{t-1}$ and $A_{t-1}$. Then, in another context (or in the same context but for other $S_i$, $i\neq j$), it is a deterministic quantity, already specified for us.
Which leads me to interpret $S_t$ as simply a placeholder symbol. With this I mean that the symbol $S_t$ doesn't mean much without a context. The context then specifies if that state is supposed to be random, with a distribution conditioned on the state and action at the previous time step, or if it is a deterministic value. Furthermore, given a context, it's not necessary for all $S_i$ to share the same nature, some can be random and some can be deterministic (although the case where more than one state in the chain is deterministic is probably meaningless$^{[1]
}$).
Hence, when we write things like
$$ Q_\pi(s,a)=\mathbb E_\pi[G_t | S_t=s, A_t=a] ~,$$
we mean that $S_t$ and $A_t$ are not random (not even random variables that we have observed their values). Instead, they are simply deterministic values given by us. However, the subscript $\pi$ in the expectation is then the context that defines all the $S_i$ and $A_i$ for $i>t$ to be random, with distributions that depend on the previous state and action, or the policy $\pi$ and the previous state, respectively. Whether or not the subscript $\pi$ also determines the nature of all the $S_i$, $A_i$ for $i<t$ seems irrelevant, since (because of its definition) the quantity $G_t$ won't depend on them (but I would argue it doesn't, otherwise $S_t$ shouldn't be deterministic).
This previous equation is in some sense asking: "What is the expected value of $G_t$, in the context that we start at state $s$, take the action $a$, and from that point onward we sample states and returns from the MDP model we defined somewhere else, and sample actions from our policy $\pi$.
I think it's important to repeat that in that equation $S_t$ and $A_t$ are not (at least according to what I could come up as a sensible interpretation of this notation) random variables! They are not random variables that we have somehow observed their values. Otherwise, this equation would suffer from the problem I described earlier: if policy $\pi$ never chooses action $a$, or never reaches state $s$, then we would be conditioning on impossible events. Instead, they're deterministic quantities. I would even go as far as advocate towards using the notation:
$$ Q_\pi(s,a)=\mathbb E_\pi[G_t] \quad,\quad S_t=s \text{ and } A_t=a$$
instead, to clear up any possible confusion that these variables might be random.
[1]: Note that this is fundamentally different from the case where these states are all random, but we have observed the value of them.
Comment: Your interpretation of $S_t$ as a placeholder symbol seems correct, but that's kind of what "random variable" means. It's always a random variable. Random variables can be "deterministic" too, in that it's possible for all the probability mass to be on only a single value, they're still random variables though. See for example the first paragraph here: https://en.wikipedia.org/wiki/Degenerate_distribution
Comment: $S_t$ and $A_t$ very much still are random variables in that equation, but in the equation we indeed fix their values to $s$ and $a$. That's because, when we use that equation, we specifically want to ask "what return are we going to get if we choose action $a$, given that we have observed ourselves to be in state $s$ right now?" We will often repeat that question for every action $a$ that is legal in the current state $s$, and then select the action that gives us the highest $Q$-value. So $a$ can very well be an action that would never be picked by policy $\pi$, and that's no problem at all.
Comment: When, in the equation, we say "$S_t = s$", the symbol $S_t$ is still the random variable as originally defined. However, by adding "$= s$" after it, we specify that we fill in a specific value for the random variable. In the case of $S_t = s$, we fill in that particular value because we have observed it, whereas in the case of $A_t = a$, we fill in that particular value because we want to make a prediction for it, "what would happen if ...?" That last thing will generally be repeated in a loop for all possible $a$, to make predictions for all of them
Comment: In that equation, if you regard $A_t$ as a random variable, then what is its distribution? Is it $\pi(\cdot | S_t)$? If it is, assume that for this policy $\pi$, $\pi(a_1|s_0)=0$. Then, when defining the value of $Q_\pi(s_0,a_1)$, you'll be forced to take the expected value of $G_t$ conditioned on an impossible event, namely $A_t=a_1$. What would that value be?
Comment: It seems impossible to me to take the expected value of a random variable conditioned on an impossible event. Since conditioning on an impossible event $B$ would give you a new sample space in which all the outcomes are $\in B$, but all of them initially had probability 0. How can you renormalize the distribution to this new sample space?
Comment: The distribution of $A_t$ is not important. The equation for $Q_\pi(s, a)$ explicitly says that we decide to fill in the value $s$ for the variable $S_t$, and the value $a$ for the variable $A_t$, and then we move on from there. It doesn't matter if $\pi$ would never pick $a$, as long as it's a legal action in state $s$ we can use the equation to predict what the future returns from executing that action would be. We do make the assumption that $a$ is a legal action, and then it's not an impossible event
Comment: It might be an impossible event given the policy $\pi$, but that doesn't matter, it's not an impossible event given any other policy. Typically we're using these kinds of equations because we're still learning our policy $\pi$, it might not be the optimal policy yet, so we do want to make predictions for all legal actions $a$.
Comment: I understand the meaning of the definition of the state-action value function. It's supposed to ask "if I'm in state $s$ and perform action $a$, then what is the expected value of my return?". I just mean that this is not equivalent to saying "if I'm in state $s$ and *observe* the action taken to be $a$, then what is the expected value of my return?", simply because the latter is undefined if the observation is impossible. Hence, it makes more sense to say that $S_t$ and $A_t$ are deterministic quantities which we know the values of $s$, and $a$, rather than random variables which we
Comment: have observed outcomes.
Comment: It may make more intuitive sense to no longer call them random variables, but "random variable" is still the correct term to use mathematically. Even if, by the time you've reached time $t$, you know exactly which values you're going to plug in for them, they're still named "random variable" (which I suppose you may want to argue is a poor name, but that's not up to me to decide, I didn't come up with the name)
Answer: I am scratching my head about this as well... In principal what follows is more of a comment than an answer. Everything I say is just guessing because I have neither read a formal description yet.
I think that most applied statisticians have a very deep understanding what they are doing but the do not allow the rest of the world to understand it properly because, as you said: apparently they like it very much to confuse random variables, values, measures, distributions, densities and so on. Nevertheless: in all cases there is a clean, mathematical, unambigous interpretation behind the symbols: We start with a probability space $\Omega$ (with some $\sigma$-algebra and some measure $P$ on it). In Markov processes we have some easy 'input' that we are given and we need to interpret and understand it. The input is a (for now finite) set of possible state values $S = \{s_1, ..., s_n\}$ and a (for now finite) set of actions $A = \{a_1, ..., a_m\}$ and a deterministic transition function $\Delta : S \times A \to S$ that, when evaluated like so $\Delta(s,a)$ giving us a completely fixed description of what happens (of what is the next state) when we are in state $s$ and take action $a$. Nothing probability related so far. The first thing that people seem to have confusion about is the policy (is it random or not?). The input we are given is what they call $\pi : S \times A \to [0,1]$ such that for all $s$ we have
  $\sum_{a \in A} \pi(s,a) = 1$
The first mistake is to say that $\pi$ is some sort of random or random variable. Up to now we can read that as a matrix of size $|S| \times |A|$ such that the row sums are $1$. Absolutely deterministic. I think what they actually mean is the following: We are given a whole set of random variables $(\alpha_s)_{s \in S} : \Omega \to A$ that are responsible for sampling the action that we take. We will write this as $\alpha(s, \omega) = \alpha_s(\omega)$. Now what their $\pi$ means is nothing else but
  $$P[\alpha(s, \omega) = a] = \pi(s, a)$$
i.e. their $\pi$ gives the distribution of the variables $\alpha_s$. I think that you are absolutely right in saying that we must define the random variables $S_t$ and $A_t$ now recursively:
  $$ A_t(\omega) = \alpha(S_t(\omega), \omega) $$
i.e. the action we take at time $t$ is defined by what the policy "randomly" choses when inserting the current state $s_t = S_t(\omega)$ and the general information $\omega$. $S_t$ in turn is defined as
  $$S_t(\omega) = \Delta(S_{t-1}(\omega), A_{t-1}(\omega))$$
i.e. the state $s_t$ at time $t$ is the one that we get by the transition function $\Delta$ when evaluated at the state $s_{t-1} = S_{t-1}(\omega)$ and the action $a_{t-1} = A_{t-1}(\omega)$ that we took before.
The mere fact that this definition is recursive is not too bad: On the one hand this seems to be the nature of the RL game: take the current state and do something with it in order to get to the next state. In mathematics in general there are many recursive things: the faculty function, the Fibonacci numbers, ...
Now the only question that remains is how to define $S_0$! However, this is something that must come from the input: When considering a Markov process we are usually given a finite state graph. When unflating that and doing probability theory with it we always end up in terms like
  $$p(s_{t}|s_{t-1}) \cdot ... \cdot p(s_1|s_0) \cdot p(s_0)$$
i.e. that tiny little $p(s_0)$ stays there no matter what you do. I think it is something the user must specify (like a prior in the Bayesian setup). However, as we gain more and more information with many states and the current situation only depends on the very last state and not the thing we did initially, I guess that it is not so important how to define $S_0$ so I think it is fine to start defining $S_0$ to be just some uniformly distributed random variable over the states. Or maybe it is like this: The thing we want to do in the end is to compare policies (in order to get the best one). When comparing them I think that $p(s_0)$ has little influence. For example, if you get some KPI that somehow needs to divide the expressions above for different policies then the $p(s_0)$ cancels out...
Does that make sense?
edit: Now thinking about what you said about the deterministic policy and the "impossible" event in the comments...
Comment: Hey Fabian, thank you for your time! Indeed, I think we agree with many things. However, I'm having trouble completely understanding your answer. Can you tell me if you agree with my statement that in the state-action value function definition, $S_t$ and $A_t$ are **not** random?
Comment: @JLagana: Humm, we can give a 'natural' definition and people write it into expected contionals... that must mean that these are normal random variables... otherwise we could never write these expressions... but as stated: I am unsure how to do it cleanly :-(
Comment: well, just because someone wrote it into expected conditionals doesn't make it random. The person could be abusing notation, for instance.
Comment: @JLagana totally agreed but there is a difference in abusing the notation like this: $P[X=x]$ <-> $p(x)$ and abusing notation in an expected conditional... at least I cannot imagine anything else to write there as a replacement. Also my (little amount of) experience with applied stats is that one has to think hard but this is then rewarded with a deeper understanding because there always is a clean probabilistic model behind it.


Serving html from linux ramdisk

Question: I have seen a somewhat dated tutorial that suggest serving html files with a ramdisk
like this:
mkfs -q /dev/ram1 102400

I also find another source that use something like this:
mount -t tmpfs -o size=1024 none /mnt/rds

Are these two methods equally valid? I am using Centos 6.3 with nginx. So in practice I want to serve the files in /usr/share/nginx/html from RAM.
And in case I mounted the disk, do I have to mount again whenever there is a genuine change in the original folder?
Comment: As is evidenced by @michael-hampton's answer, this question is unclear. The title talks about serving html from ramdisk, but the actual questions asked are not about serving html files, but about the differences between two ramdisk implementations. It would be better if you were asking one single clear question.
Answer: Why bother? Linux is just going to cache them in RAM anyway, the first time they get read from disk. And if they're read frequently enough they'll always be cached.
Comment: We're generally all about practical solutions here. Neither ramdisk "solution" is nearly as practical as just letting Linux handle it itself, like it's been doing for many years.
Comment: Hmm, I guess technically this does answer the question in a roundabout way. Are you saying "yes, the two methods are equally [in]valid"? Despite all the upvotes, though, it really sidesteps the question. I shall abstain from voting in either direction.
Answer: From your question (last paragraph), I assume you think that the ramdrive will have the same contents as the original file system below. That's not the case. You will have an empty directory and need to fill it first. I don't think this is what you want.
Linux has a very good cache system. Every memory page which is not used for application memory will be used as cache. This means: even without a tmpfs (the method I would recommend), your file will stay in memory until there is real need to flush it from there.
Given it really happens and your memory gets too full:

if you use tmpfs, your tmpfs contens will move to your swap memory, which means, it is also saved on disk and not faster anymore than using a real file system.
if you don't use tmpfs, your cached version will be flushed from memory, which consumes almost no time. when it is accessed next time, it will be read from disk and comes back into the cache.

So I don't see any advantage to use tmpfs as long you don't generate those files dynamically and in very short interval. Linux normally is much more efficient if you let it decide over memory usage and swapping.
Answer: The tmpfs method has less overhead. In the /dev/ram1 example, you have an entire filesystem with inodes, directories, etc stored in a block device. With tmpfs it is essentially only the disk cache.
Yes, if you create a ramdisk and copy files into it, you need to copy those files again whenever there is a change.
Comment: This answer could be improved by references or benchmarks.
Answer: Without saying that using an RAM disk is a good idea: I remember having read an article (unfortunately no URL at hand) about benchmarking the two kinds of RAM disks which surprisingly showed relevant differences (I have forgotten which was better).
Comment: I'd +1 this if you found the article, or at least could summarize if from memory. As it is, though, your answer doesn't really answer the question in any way, and would really be better as a comment.

Serving html from linux ramdisk


How to auto update working copy svn when someone commit?

Question: We have a SVN server (UberSVN) and we have a test server (Ubuntu 11.10). Test server is running SVN-client and LAMPP.
We were looking for a solution that auto update the working copy's our developer on Test Server as soon as someone commit the changes to SVN server.
How to auto update working copy svn when someone commit ?
Comment: Google post-commit hooks, then try it first and let us know if you get any problem.
Comment: I know that. In the post-commit hook: all you need is setup an password-less account to ssh from production server to test server and do a `svn update`.
Comment: Which OS your production server is running: Windows or Linux?
Comment: Hi quanta, Server is Ubuntu 11.10 ( have SVN-client and LAMPP)
Comment: HI quanta, I need config `post-commit hooks` on `SVN server` to update to `Test Server`. `SVN server` and `Test Server` are two separate servers
Answer: A few options spring to mind

Take the simple sledge hammer approach of having a simple cron job that does and SVN update every few minutes on the test server.
Use an SVN Post-commit hook on the SVN server to signal to the Test server that a commit has taken place so the test server can update.  Signaling could be simply by placing a file in a shared location that the test server looks for in a script.
Use a proper "Continuous integration" server such as http://jenkins-ci.org/.

Option 2 would need a bit of work in terms of writing some scripts but shoudl be fairly straight forward.
Comment: I'm interested in option is Use an SVN Post-commit hook on the `SVN server` to signal to the `Test server`. But, I don't know how to config `SVN Post-commit hook` on SVN server to update to `Test Server`. Can you help me more about `SVN Post-commit hook` to another server ? Or document about it.
Answer: I had used No 2 that Phil has mentioned.
What I  configured was I made a Working copy on the svn server for every repository just to as for Auto Deployment.
So whenever someone commits to a repository my post-commit script updates the working copy and then the working copy is rsync'd to the Client's Servers using a cron that used to run every 2 mins to rsyen the working copy among different client machines.
I was using Subversion. Here are the commands that I used.

svn co file:///path/to/$SvnRepoName /working/$ProjectName   --> A local working copy on svn server
/usr/bin/svn update /working/$PROJECTNAME     --> in my post-commit script.
A shell script to rsync /working/$PROJECTNAME  among client machines.
Comment: Nice way of doing it with rsync.  Neat


Is there a relation between eigenvectors and homogeneous functions, and what is it?

Question: when I worked with idea of something being homogeneous. I always felt I reverse engineering what we are doing in linear algebra to find the eigenvectors and eigenvalues. could someone explain it simply
Comment: The word may be a corruption of  *Till Eugenspiegel*  who was a sort of folk hero, earliest published versions about 1500.
Comment: Mina, same spelling in your title
Answer: Yes, there is a relationship. Let's recall that a function, say $f : \mathbb{R} \to \mathbb{R}$, is homogeneous of degree $k$ if it satisfies
$$f(sx) = s^k f(x)$$
for all $x \in \mathbb{R}, s \in \mathbb{R}^{\times}$. This condition says exactly that $f$ is a simultaneous eigenvector for the scaling operators
$$T_s : f(x) \mapsto f(s x)$$
acting on the vector space of functions $f : \mathbb{R} \to \mathbb{R}$, such that $T_s$ has eigenvalue $s^k$.
The scaling operators satisfy $T_{s_1 s_2} = T_{s_1} T_{s_2}$, and you can check that this implies that if $f$ is a simultaneous eigenvector for all of the $T_s$ then the corresponding eigenvalues $\lambda_s$ satisfy $\lambda_{s_1 s_2} = \lambda_{s_1} \lambda_{s_2}$. All of this can be understood using the language of representation theory.
Answer: Any homogeneous function $f$ of $n$ variables $x_i$ is an eigenvector of the Euler operator $\sum_{i=1}^nx_i\,{\partial }/{\partial x_i}$ with its degree of homogeneity  $k$ as eigenvalue
$$\sum_{i=1}^nx_i\left.\frac{\partial f}{\partial x_i}\right|_{(x_1, \dots, x_n)}=kf(x_1, \dots, x_n)$$ per  Euler's therorem. You can see that $f$ fed into the linear operator comes out again scaled, as eigenvectors do.


Return the smallest number from the list. It should return -1 when an empty list is encountered

Question: Here is a recursion program
numbers = [1, 2, 3, -3, 5]
numbers0 = [1, 2, 3, 4, 5]
numbers1 = []

def smallest(myList):
    if len(myList) == 0:
        return -1
    else:
        return min(myList[0], smallest(myList[1:]))

print(smallest(numbers))
print(smallest(numbers0))
print(smallest(numbers1))

Comment: Why not `def smallest(lst): return min(lst) if lst else -1`?
Comment: what's the problem you are facing?
Comment: must use recursion
Answer: If you just want return the smallest number from the list, you don't need to use recursion
numbers = [1,2,3,-3,5]
numbers0 = [1,2,3,4,5]
numbers1 = []

def smallest(myList):
    if len(myList)==0:
        return -1
    else:
        return min(myList)

print(smallest(numbers))
print(smallest(numbers0))
print(smallest(numbers1))

Output:
-3
1
-1

Answer: Hey this question was pretty easy:
#--Lists--
numbers = [1,2,3,-3,5]
numbers0 = [1,2,3,4,5]
numbers1 = []

#--Store all list in a list--

myList = [numbers, numbers0, numbers1]

#--List to store the minimum values--

a = []

#--For loop on each list--

for i in myList:
  if len(i)==0: #--If it is empty print -1
    print(-1)
  else: #--If it is not empty, find the minimum--
    b = min(i)
    a.append(b) #--And then append in a--

print(a) #--Show the values of a--

This should do it and is pretty self explanatory
Answer: You can try and do something like this.
numbers = [1,2,3,-3,5]
numbers0 = [1,2,3,4,5]
numbers1 = []

#make a list of all the lists but in sorted order

n = [sorted(numbers),sorted(numbers0),sorted(numbers1)]

#then take the first element of each list. If list is empty, use -1

x = [-1 if not i else i[0] for i in n]

#x will now contain the smallest values from each list

print (x)

Output
[-3, 1, -1]

Another way to do this would be:
#create a list with all the lists

n = [numbers, numbers0, numbers1]

#run thru them and identify the minimum value of each list
#if list is empty, then -1

x = [-1 if not i else min(i) for i in n]

#print the final result

print(x)

Output:
[-3, 1, -1]


How do I restart a Thread after I stop it in Java?

Question: I was trying to restart a thread after I stop it manually in my Project written in java. When I try to restart it I was give an IllegalThreadStateException error.
I simplified my code as the following sample code. My questions are:

How can I restart the logtest thread, do I have to start a new thread instead of restarting it?
As you can see from the following code, in the run method of the class LogThread, I used Thread.Sleep(3) to output these numbers row by row. If I delete this line, the thread will either die in the middle or output all these 10000 rows all at once. Do I have to force the thread to stop 3 milliseconds to sacrifice its performance? Are there any better way to solve this?

The Code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.StyledDocument;

public class LogTest {
  private LogThread logtest;
  public LogTest() {
    JFrame frame = new JFrame("LogTest");
    Container con = frame.getContentPane();
    final JTextPane pane = new JTextPane();
    final JScrollPane scollPane = new JScrollPane(pane);
    JButton button = new JButton("Start Test Log");
    JButton button1 = new JButton("Stop Test Log");
    logtest = new LogThread(pane);
    con.add(scollPane);
    con.add(button, BorderLayout.NORTH);
    con.add(button1, BorderLayout.SOUTH);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        logtest.start();
      }
    });
    button1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        logtest.stop();
      }

    });
    frame.setSize(600, 500);
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new LogTest();
  }

}

class LogThread implements Runnable {
  private final Thread t;
  private String newline;
  private volatile boolean shouldStop = false;
  private StyledDocument doc;
  private JTextPane pane;
  private static int counter = 0;

  public LogThread(JTextPane pane) {
    this.doc = pane.getStyledDocument();
    this.pane = pane;
    t = new Thread(this, "Log Thread");
    newline = System.getProperty("line.separator");
  }

  public void start() {
    t.start();
  }

  public void run() {
    try {
      if (doc.getLength() > 0) {
        doc.remove(0, doc.getLength());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    if(shouldStop) shouldStop=false;
    for (int i = counter; i <= 1000 && !shouldStop; i++) {
      try {
        doc.insertString(doc.getLength(),
            i + "-------------------------------------------------------------"+ newline,
            null);
        pane.setCaretPosition(doc.getLength());
        Thread.sleep(3);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public void stop() {
    shouldStop = true;
  }
}

Comment: You can't.  `Thread` is non-reentrant, meaning you can't call `start` on it more than once.  You need to create a new `Thread` and pass it a reference to a `Runnable` instance and start that `Thread`
Answer: Basically, you can't, from the JavaDocs...

It is never legal to start a thread more than once. In particular, a
  thread may not be restarted once it has completed execution.

What you need to do is, when start is called, is create a new Thread, passing this to it and starting that thread.  You will need to determine if a Thread is already running and take action to terminate it first
class LogThread implements Runnable {
  private final Thread t;
  //....

  public LogThread(JTextPane pane) {
      //...
      //t = new Thread(this, "Log Thread");
      //...
  }

  public void start() throws InterruptedException {
    if (t != null && t.isAlive()) {
        shouldStop = true;
        t.join();
    }
    shouldStop = false;
    t = new Thread(this, "Log Thread");
    t.start();
  }

  //...

  public void stop() throws InterruptedException {
    shouldStop = true;
    t.join();
    t = null;
  }
}

You are also violating the single thread rules of Swing by modifying the state of the UI from outside the context of the Event Dispatching Thread...
In particular...
pane.setCaretPosition(doc.getLength());

A safer solution would be to use a SwingWorker and update the UI from within then the process method.
Take a look at How to use SwingWorker for more details


$ \frac{Q\left(x_1\right)}{P'\left(x_1\right)}+\frac{Q\left(x_2\right)}{P'\left(x_2\right)}+\frac{Q\left(x_3\right)}{P'\left(x_3\right)}=? $

Question: $ P\left(x\right)=x^3+ax^2+bx+c $
$ x_1,x_2,x_3$ distinctive in pairs(and are the roots of $P$)
$Q(x)$ is a first degree polynomial
$ \frac{Q\left(x_1\right)}{P'\left(x_1\right)}+\frac{Q\left(x_2\right)}{P'\left(x_2\right)}+\frac{Q\left(x_3\right)}{P'\left(x_3\right)}=? $
How should I approach this? I tried the long polynomial division on the first term, but didn't seem to get anything useful out of it. (the answer is $0$)
Comment: is $Q(x)=Ax+B$?
Comment: are $x_1,x_2,x_3$ Zeros of $P(x)$?
Comment: I think it is mx+n, the exercise doesn't say anywhere that the coefficients would be the same. @Dr.SonnhardGraubner
Comment: yes, they are @Dr.SonnhardGraubner
Comment: and $x_1,x_2,x_3$? what are These numbers?
Comment: They are the roots of the polynomial P @Dr.SonnhardGraubner
Answer: Consider the polynomial
$$f(x):=\sum_{i=1}^3\,Q\left(x_i\right)\frac{\left(x-x_{i-1}\right)\left(x-x_{i+1}\right)}{P'\left(x_i\right)}\,,$$
where the indices are consider modulo $3$.  Then, $f(x)$ is a polynomial in $x$ of degree at most $2$ such that $f\left(x_i\right)=Q\left(x_i\right)$ for every $i=1,2,3$ (i.e., $f(x)$ is the Lagrange polynomial interpolating $Q(x)$ at $x=x_1$, $x=x_2$, and $x=x_3$).  Therefore, $f(x)=Q(x)$.  That is, the coefficient of $x^2$ in $f(x)$ is $0$.  This means
$$\sum_{i=1}^3\,\frac{Q\left(x_i\right)}{P'\left(x_i\right)}=0\,.$$

More generally, suppose that $P(x)$ is a monic separable polynomial in $x$ over a field $K$ of degree $n\in\mathbb{Z}_{>0}$.  Write $x_1,x_2,\ldots,x_n$ for the roots of $P(x)$ in the algebraic closure of $K$.  Let $Q(x)\in K[x]$ be a polynomial of degree at most $n-1$; that is, $Q(x)=\sum\limits_{j=0}^{n-1}\,q_j\,x^j$ for some $q_0,q_1,\ldots,q_{n-1}\in K$.  Then,
$$\sum_{i=1}^n\,\frac{Q\left(x_i\right)}{P'\left(x_i\right)}=q_{n-1}\,.$$
Answer: Hints (this is an elementary argument, see @Batominovski for deeper reasoning):
Recall that (since $P(x)$ is monic), it can be factored as:
$$P(x)=(x-x_1)(x-x_2)(x-x_3)$$
and
$$P'(x)=(x-x_1)(x-x_2)+(x-x_1)(x-x_3)+(x-x_2)(x-x_3).$$
Therefore,
$$
P'(x_1)=(x_1-x_2)(x_1-x_3).
$$
Now, continue in this way and combine fractions.  If you write out the sum (assuming $Q(x)=mx+n$), you should get:

$$\displaystyle\frac{mx_1+n}{(x_1-x_2)(x_1-x_3)}+\frac{mx_2+n}{(x_2-x_1)(x_2-x_3)}+\frac{mx_3+n}{(x_3-x_2)(x_3-x_1)}.$$

If you simplify, you should get

$0$


What could cause a View template to ouput wrong row index?

Question: Context
I have a weird issue on my live environment that I have never seen on my local environment. Cache bins are disabled on my local environment and enabled on live server.
When clearing all caches on live server, the problem disappears for some time, then reappears. When disabling cache bins on live server the problem doesn't seem to happen anymore.
Issue
In my custom theme, I use a simple "Single field" template to override a given view field.
/**
 * @file
 * Theme override for a single field in a view.
 *
 * Available variables:
 * - view: The view that the field belongs to.
 * - field: The field handler that can process the input.
 * - row: The raw result of the database query that generated this field.
 * - output: The processed output that will normally be used.
 *
 * When fetching output from the row this construct should be used:
 * data = row[field.field_alias]
 *
 * The above will guarantee that you'll always get the correct data, regardless
 * of any changes in the aliasing that might happen if the view is modified.
 *
 * @see template_preprocess_views_view_field()
 */

In the output HTML of this field, I need a simple incremental id from 0 to n where n would be the total number of rows in the view results. Something like below for a View with 5 results:

...

...

...

...

...

So in my field template, I use:

...

This works fine, except on some occasions, only on my live server with caching enabled where the output will be for example:

...

...

...

...

...

Important notes:

I sometimes get indices such as 19 when there are only 10 or 15 results in the view so that number seems to come out of the blue.
This happens when the view is filtered using a single taxonomy term.

Question
Am I wrong assuming that row.index should give me an incremental sequence of integers for every view, with or without caching? If I am wrong, then what should I be using? And if not, what could cause this behavior?
Comment: The rendered result of a views row is cached and re-used even if displayed in a different row index. Did you try to configure caching for the specific View instead of disabling the render cache for the entire site?
Comment: Yes, one of those should work. The issue here is with the rendered field template, so it should work if you only set the rendered output to *Never Cache*.
Comment: No I haven't yet. Do you suggest I disable caching on the View UI by setting *Caching* to `none`? Or should I go with `time-based` caching and disable only the query result or the rendered output? I am not sure what to do. Thanks.
Comment: Ok thanks a lot for your input. I will find another way to define that index then, as I'd really like to keep caching enabled on the view.
Answer: To solve it using views-view-field.html.twig
First in view settings, add field "View Result Counter" and hide from display.
Now in your twig you can do

...

Comment: +1, Views caching ignores the row index, but it shouldn't be able do this any longer for a real field. You can even get rid of the template by moving the Twig to "Rewrite Results" of the field.
Comment: Nice. I had no idea we had that field available! Good to know ;)
Answer:
If I am wrong, then what should I be using?

Instead, you could do it using views-view--unformatted.html.twig
and modify the row part to
{% set count = 0 %}
{% for row in rows %}
  set count = count + 1
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{ row.content }}

{% endfor %}

Comment: That would not work if I really had to have that logic on field level, though it will work in my case if I adapt my logic a bit and move it up to the row level and that's actually exactly what I thought doing. Because I'd really like to not disable caching on the view as this seems to be my only option if I want to use `row.index`. So indeed it sounds like a better option to somehow define that variable increment by myself.
Comment: There might be a creative way to solve via field template file, but I don't have access to Drupal right now. I'll look into it later.


Erro ao gerar um objeto JSON

Question: Estou tentando criar esse objeto:
<code>{
    "schema": [
        "urn:ietf:params:scim:schemas:core:2.0:User",
        "urn:ietf:params:scim:schemas:core:2.0:User",
        "urn:ietf:params:scim:schemas:core:2.0:User"
    ],
    "endereco": "Rua 0",
    "nome": "Fulano",
    "sobrenome": "de Tal"
}
</code>
porém ele sai assim:
<code>{
    "{\"schema\":[\"urn:ietf:params:scim:schemas:core:2.0:User\",\"urn:ietf:params:scim:schemas:core:2.0:User\",\"urn:ietf:params:scim:schemas:core:2.0:User\"]}": {
        "endereco": "Rua 0",
        "nome": "Fulano",
        "sobrenome": "de Tal"
    }
}
</code>
meu código
<code>import org.json.simple.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

public class Main {

    public static void main(String[] args) throws JSONException {

        JSONArray arr = new JSONArray();
        JSONArray headers = new JSONArray();
        JSONObject usuario = new JSONObject();
        JSONObject head = new JSONObject();
        JSONObject obj = new JSONObject();

        usuario.put("nome", "Fulano");
        usuario.put("sobrenome", "de Tal");
        usuario.put("endereco", "Rua 0");

        headers.put("urn:ietf:params:scim:schemas:core:2.0:User");
        headers.put("urn:ietf:params:scim:schemas:core:2.0:User");
        headers.put("urn:ietf:params:scim:schemas:core:2.0:User");

        head.put("schema", headers);

        obj.put(head, usuario);

        System.out.println(obj);
    }

}
</code>
Answer: A logica esta incorreta, pq vc esta criando um objeto do usuário, e adicionando ele junto ao head, e o head não tem nenhum valor, basta fazer assim
<code>    obj.put("nome", "Fulano");
    obj.put("sobrenome", "de Tal");
    obj.put("endereco", "Rua 0");
</code>

Erro ao gerar um objeto JSON


Generate a nested object structure by string key/path

Question: I want to make a function called createAssociativeArray which will recive two parameters: string and object, like this:
function createAssociativeArray(string, object) {
  //...
}

The last item of string should get the object data. See an use/return example:
createAssociativeArray('key1.key2.key3', {
  data1: 1,
  data2: 2,
  data3: 3
});

// key1: {
//   key2: {
//     key3: {
//       data1: 1,
//       data2: 2,
//       data3: 3
//     }
//   }
// }

What's the most simple and robust method to do it?
Use eval isn't is a possibility.

What I was tried:
function createAssociativeArray(string, object) {
  string = string.split('.');
  return string.reduce(function(_object, _target, i) {
    _object[_target] = (i + 1 === string.length ? object : {});
    return _object;
  }, {});
}

It didn't produced the expected result because the object is reseted to {}.
[JSFiddle]
Comment: Are you trying to implement namespaces? Also, where does the `i` variable come from?
Comment: @StefanBaiu, something like... It's a `index` from `reduce` (updated).
Answer: Here's what I came up with:
function createAssociativeArray(string, object) {
  var parts = string.split('.');
  var last = parts[parts.length - 1];
  var tree = {};

  var node = parts.slice(0, -1).reduce(function (memo, current) {
     return (memo[current] = {});
  }, tree);

  node[last] = object;
  return tree;
}

Comment: Try this if you want to merge with an exitsing Object (set the value on a JSON path in a given object): http://stackoverflow.com/a/32791758/2045312
Answer: I was curious to see if I could make a recursive solution, so here it is:
function createAssociativeArray(string, object) {
    if (string === "") return object;
    var stringarr = string.split('.');
    var laststr = stringarr.pop();
    var newobj = {};
    newobj[laststr] = object;
    return createAssociativeArray(stringarr.join("."), newobj);
}

Working JSFiddle demo: https://jsfiddle.net/pt352dxg/
Answer: Possible implementation:
Working demo
function createChain(keys, value) {
  var obj = {};
  var target = obj;
  keys = keys.split('.');
  keys.forEach(function(key, index) {
    target = target[key] = index === keys.length - 1 ? value : {};
  });
  target = value;
  return obj;
}

Answer: This function actually can accept an optional existing Object ({k:2, kk: 3, key1: 4}) and merge that with given json path. e.g. Try on chrome debugger console:
JSON.stringify(createAssociativeArray('key1.key2.key3', {  data1: 1,  data2: 2,  data3: 3}, {k:2,kk:3, key1:{}}))

will print this:
"{"k":2,"kk":3,"key1":{"key2":{"key3":{"data1":1,"data2":2,"data3":3}}}}"

..
  function createAssociativeArray(key, value, data) {
         if(!finalData && data)
           finalData = data;
         var finalData;
         if (!data)
             data = finalData = {};
         var keys = key.split('.');
         if (keys.length < 2) {
           data[keys[0]] = value;
         } else {
           if (!data[keys[0]])
               data[keys[0]] = {};
           data = data[keys.shift()];
           createAssociativeArray(keys.join("."),value,data);
         }
         return finalData;
    };

Answer: You were pretty close in your original attempt.
function createAssociativeArray(string, object) {
    return string.split('.').reverse().reduce(function (inner, key) {
        var outer = {};
        outer[key] = inner;
        return outer;
    }, object);
}

http://jsfiddle.net/xewoa06t/
Answer: This worked for me:
function createAssociativeArray(string, object){
    var array = string.split('.');
    var aArray = {};
    if(array.length > 1){
         aArray[array[array.length - 1]] = object;
         array.splice(array.length - 1, 1);
         createAssociativeArray(array.join('.'), aArray)
    }else{
        aArray[array[array.length - 1]] = object;
        return aArray
    }
};

createAssociativeArray('key1.key2.key3', {data1: 1, data2: 2, data3: 3});

Basically, builds object from ground up, starting with the original object, then wrapping the 'layers' around it recursively
Answer: Nice case for a recursive function!
function createAssociativeArray(string, object) {
  if (string.split('.').length == 1) {
    var outObj = {};
    outObj[string] = object;
    return outObj;
  } else {
    var outObj = {};
    outObj[string.split('.')[0]] = createAssociativeArray(string.split('.').slice(1).join('.'), object);
    return outObj;
  }
}

Answer: It's easier with a simple loop, the key point is doing in reverse (like @JustcallmeDrago)

function createAssociativeArray(keys, data)
{
  var temp, keyPart

  for(keys = keys.split('.'); keys.length; data = temp)
  {
    keyPart = keys.pop()
    temp = {}
    temp[keyPart] = data
  }
  return data
}

// TEST

x = createAssociativeArray("key1.key2.key3", { data1: "value1", data2: "value2" })

document.write('
'+x+'\n'+x.key1 +'\n'
               +x.key1.key2 + '\n'
               +x.key1.key2.key3 +'\n'
               +x.key1.key2.key3.data1 +'\n'
               +x.key1.key2.key3.data2 +'
')
Answer: Since no one have proviced a while-loop solution:
function namespace(path, context) {
    var obj = context;
    var s = path.split('.');
    var p;
    while (s.length) {
        p = s.shift();
        obj = obj[p] || (obj[p] = {});
    }
    return context;
}

Answer: ES6 one liner
(str, obj) => str.split('.').reverse().reduce((inner, key) => ({[key]: inner}), obj);


How can I center my two blue boxes here?

Question: I would like to center my two blue boxex shown in the example below using CSS Flexbox. I tried to center them with both align-items: center; and justify-content: center; but it is not working.
Thanks for the help.

body {
  margin: 0;
  padding: 0;
}

#container {
  width: 100%;
  height: 500px;
  background-color: green;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

#first {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50%;
  display: inline-block;
  background-color: red;
}

#loadingBar {
  width: 100%;
  height: 20px;
  background-color: purple;
}

#inner {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-color: blue;
}

Comment: Declare the `flex-box` rules to the containing element of the two boxes you need to align center, `flex-box` has a direct parent-to-child sort of relationship. To achieve the intended behaviour, using `flex-box`, `display: flex`, and any flex alignment properties, should be declared on the parent element.
Comment: @UncaughtTypeError I have tried wit that method. I added ```display: flex; align-items: center; justify-content: center;``` to the parent div with id #first for the two inner divs with id #inner, but they are not working. I have updated my code. Please see.
Comment: Your `display: flex` rule on `#first` is being over-qualified by another `display` rule (`display: inline-block`) further down the cascade order for that (`#first`) selector. Remove it, `display: inline-block` on `#first`, to observe the intended behaviour.
Answer: I added to the "First" Class display:flex align-items: center;Then margin for the boxes

body {
   margin: 0;
   padding: 0;
  }
  #container {
   width: 100%;
   height: 500px;
   background-color: green;
   display: flex;
   align-items: center;
   justify-content: center;
   flex-direction: column;
  }
  #first {
   width: 50%;
      display: flex;
     background-color: red;
      align-items: center;
      justify-content: center;
   background-color: red;
  }
  #loadingBar {
   width: 100%;
   height: 20px;
   background-color: purple;
  }
  #inner {
    width: 50px;
    margin-left: 1%;
    margin-right: 1%;
    height: 50px;
    display: inline-block;
    background-color: blue;
  }

Comment: I do not want to add any extra div though. Is it possible?
Comment: @Zip Yes sure, I've Edited my answer, check it out.
Answer: Use the display: flex and justify-content: center on the element containing the blue boxes. Justify content centers the elements inside it, if you use it in the blue box it will center content inside the blue box, if any.


Android fake touch screen

Question: Is it possible to generate a fake touch at a particular point (say (x,y)) on the screen from the code? There is a button on my activity and I dont want to click it through touch screen? Is there any way to achieve this?
Comment: I am sure there must be , as you may know there is a program called "Monkey" to test your application...Try googling for "How monkey clicks on screen?"
Answer: This method should help you.
http://developer.android.com/reference/android/view/View.html#performClick()
myButton.performClick();

Comment: yeah... okk.. it works for my question. At the end  I want all of this from a background service to click on any screen not just activity`s screen. I think I will have to use monkey for that.
Answer: The following code generates touch event as if the screen is really touched.
CAUTION: rooted devices only
public class Tap {
private static final String SU = "su", TAG = Tap.class.getSimpleName(),
        COMMAND = "/system/bin/input tap %d %d ", ASCII = "ASCII";

public Tap() {

}

public void tap(int x1, int y1) {
    TapTask t = new TapTask(x1, y1);
    t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

private class TapTask extends AsyncTask<Void, Void, Void> {
    private int x1, y1;

    public TapTask(int x1, int y1) {
        this.x1 = x1;

        this.y1 = y1;

    }

    protected Void doInBackground(Void... args) {
        try {
            Process sh = Runtime.getRuntime().exec(SU, null, null);

            OutputStream os = sh.getOutputStream();

            os.write((String.format(COMMAND, x1,y1)).getBytes(ASCII));
            os.flush();
            os.close();
            sh.waitFor();

            Log.i(TAG,String.format("tap %d %d ",x1,y1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

Android fake touch screen


Add arguments to custom submit

Question: I added an extra submit-function to my form:
$submit = array('_check_value_public_catalog');
$form['actions']['submit']['#submit'] = array_merge($submit, $form['actions']['submit']['#submit']);

So the form looks like:
array
  0 => string '_check_value_public_catalogue'
  1 => string 'node_form_submit'

But I would like to pass some arguments to my _check_value_public_catalog function. How do I do this?
Comment: Are the arguments you wish to pass to your submit handler elements in the original form (i.e. results)?
Comment: @Chapabu, Jep, they are!
Answer: You can't as such but you can store the values in the form somewhere and pick them up in your submit handler:
function mymodule_my_form($form, &$form_state) {
  $form['saved_value_1'] = array(
    '#type' => 'value',
    '#value' => 'The Value'
  );

  $form['#submit'][] = 'mymodule_my_form_submit';

  return $form;
}

function mymodule_my_form_submit(&$form, &$form_state) {
  $saved_value_1 = $form_state['values']['saved_value_1'];
}

Exactly the same principle applies if you're doing this in a form alter hook.
Answer: Submit handlers have $form and $form_state automatically passed to them as arguments ($form_state will contain the submitted values for your form).
Assuming there are no arguments already supplied, your submit handler should look like below:
_check_value_public_catalog($form, $form_state) {
 //do funky stuff here
}

If you need specific arguments sent to the function, you could either write a different submit callback to pull the data out of $form_state and send it to your _check_value_public_catalog function, or re-write your submit function as below (before arguments are assumed).
Before:
function _check_value_public_catalog($foo, $bar) {
//cool stuff here with $foo and $bar
}

After:
function _check_value_public_catalog($form, $form_state) {
 $foo = $form_state['values']['foo'];
 $bar = $form_state['values']['bar'];

//cool stuff with $foo and $bar
}

See here for some more information.
Answer: Form submission handlers don't use anymore custom parameters as reported in $form['#submit'] and $form['#validate'] and $form['#process'] no longer support custom parameters. In  that page, which is for converting modules from Drupal 5 to Drupal 6, it is suggested to use $form['#custom_parameter'], where "#custom_parameter" is a string that doesn't conflict with one already used by Drupal.
function my_form() {
  // form definition code goes here...
  $form['#submit'][] = 'my_submit_function';
  $form['#my_form_param1'] = $param1;
  $form['#my_form_param2'] = $param2;
}

As alternative, the arguments passed to the form builder are available in $form_state['build_info']['args']. (See drupal_build_form(), which describes the values contained in $form_state.)
If the form builder is defined as in the following code, then $form_state['build_info']['args'] is an array containing "this is", and "a test".
$item['mymodule/test'] = array(
  'title' => 'Test',
  'description' => 'This is a test menu.',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('node_admin_content', 'this is', 'a test'),
  'access arguments' => array('access test pages'),
);

In fact the code of drupal_get_form() is the following one:
function drupal_get_form($form_id) {
  $form_state = array();

  $args = func_get_args();
  // Remove $form_id from the arguments.
  array_shift($args);
  $form_state['build_info']['args'] = $args;

  return drupal_build_form($form_id, $form_state);
}

The function removes the first argument it gets, which is the form ID, and put the other arguments in $form_state['build_info']['args'].
Answer: found a good way to do this by attaching the parameters to the button:
when generating from
/**
* Implements hook_form_alter
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  $nrbuttons = 10;
  for($i = 0; $i < $nrbuttons; $i++){
    $form['button_' . $i] = array(
      '#type' => 'submit',
      '#value' => t('button ' . $i),
      '#submit' => array('MYMODULE_form_submited'),
      '#attributes' => array(
         'button_index' => $i,
         'other_parameter'=>'value',
      ),
    );
  }
}

/**
* Custom submit handler
*/
function MYMODULE_form_submited($form, &$form_state){
    $i           = $form_state['clicked_button']['#attributes']['button_index'];
    $other_param = $form_state['clicked_button']['#attributes']['other_parameter'];
}

Comment: This is good way to achieve this. Small code, lots of buttons with values 'attached' to the buttons. Answers the OP and is flexible in other use cases.
Comment: Wow! I have not tried this out but does look brilliant to me.

Add arguments to custom submit


Proof of Monotone Convergence Theorem

Question: I am currently studying the proof of Monotone convergence theorem for Lebesgue measurable functions and I have a doubt about the proof. In the book from Ash Probability and Measure Theroy they make use of a simple positive finite-valued function to prove that
$\lim_{n} \int f_n d\mu \ge \int \lim_n f_n d\mu$
In fact, they say that letting $s<f$ with s simple and f the limit of the sequence, we can take $0 \lt b \lt 1 $ and
$B_n=\{\omega : f_n (\omega) \ge bs(\omega)\} \uparrow \Omega$
one can say
$\int f_n d\mu \ge \int_{B_n} f_n d\mu \ge b\int_{B_n} s d\mu$
and taking the limits on both sides and letting $b \rightarrow 1$ yields the result.
My question is: why use the simple function? Could one directly use the limit function f to prove the statement?  Like for example letting
$B_n = \{\omega : f_n (\omega) \ge (1- \varepsilon) f(\omega)\}$
for given $\varepsilon$
$\int f_n d\mu \ge \int_{B_n} f_n d\mu \ge (1-\varepsilon)\int_{B_n} f d\mu$
and since $\varepsilon$ is arbitrary we can say
$\int f_n d\mu \ge \int_{B_n} f d\mu$
Taking limits on both sides would yield the result.
Is there something wrong in the statements I made? Why Ash uses the simple function instead of the limit function?
Thanks a lot.
Comment: You write $B_n$ but shouldn't that be $B_{n,\epsilon}$?
Comment: How do you know that $\lim_n\int_{B_n}f\,d\mu=\int f\,d\mu$? For *simple* $s$, the analogous fact is seen by explicit calculation using the fact that $\lim_n\mu(A\cap B_n)=\mu(A)$ for each measurable $A$.
Comment: In a previous theorem it was stated that $\int f d\mu$ is a measure when f is nonnegative, so I assumed that the limit above is just the measure of the limit which is in fact Omega.
Comment: drhab, assuming $\varepsilon$ arbitrary, the sets shouldn't depend on it, right?
Comment: the set $\{f_n\geq(1-\epsilon)f\}$ is evidently a set that depends on $\epsilon$. You disregard that by calling it $B_n$. If you let $\epsilon\to0$ to come to your "result" $\int f_nd\mu\geq\int_{B_n}fd\mu$ then also the set that you called $B_n$ will get smaller.
Comment: Why does the same not apply to the set $\{f_n \ge bs \}$? That should depend on b too, right? Furthermore, I don't see how this invalidate the proof.
Comment: In the proof in the book they first let $n\to\infty$ (this with a fixed $b$) and secondly they let $b\uparrow1$. That's why it is irrelevant there to write $B_{n,b}$ instead of $B_n$. You are doing it the other way arround: first $\epsilon\downarrow0$ and after that $n\to\infty$.
Answer: If for $\epsilon>0$ we define $B_{n,\epsilon}:=\{f_n\geq(1-\epsilon)f\}$ then indeed we have $\int f_n\geq(1-\epsilon)\int_{B_{n,\epsilon}} f$.
From this however we cannot conclude that also $\int f_n\geq\int_{B_{n,\epsilon}}f$ under argumentation that $\epsilon$ is "arbitrary".
Look e.g. what happens if we let $(\epsilon_k)_k$ be a sequence with $\epsilon_k\downarrow0$. Then we can observe that: $$\forall k\left[\int f_n\geq(1-\epsilon_k)\int_{B_{n,\epsilon_k}} f\right]$$
In that situation $B_{n,\epsilon_k}\downarrow\{f_n\geq f\}$.
So by an $\epsilon$ that gets smaller we at most find that  $\int f_n\geq\int_{\{f_n\geq f\}}f$ which we allready knew.
Nothing is gained.
Comment: So if I first let $n \rightarrow \infty$ I'd obtain $lim_n \int f_n d\mu \ge (1-\varepsilon) \int f d\mu$ and then $\varepsilon \downarrow 0$, would it be correct?
Comment: On what do you base that RHS converges to $(1-\epsilon)\int f$ if $n\to\infty$ ?
Comment: From the fact that $\lambda (A) = \int_A f d\mu$ is a measure, and since $B_n \uparrow \Omega$ we get $\lambda (B_n) \rightarrow \lambda (\Omega )$ which means $\int_{B_n} f d\mu \rightarrow \int f d\mu$
Comment: Then actually you base it on $f1_{B_n}\uparrow f\implies \int f1_{B_n}\uparrow \int f$. So you use MCS in order to prove MCS. This is strictly forbidden of course.
Comment: If you go the route of proving that $A\mapsto\int_Af$ then you will encounter usance of MCS.  So it cannot be used to prove MCS afterwards.
Comment: You sure? In Ash the fact that $\int_A f d\mu$ is a measure is proven before and independently from MCT (Theorem 1.6.1 of the book, MCT is 1.6.2) and then I'm just applying continuity of measures wrt Monotone sequences of sets.
Comment: I am not completely sure. If it can be done without then this might be a way to prove MCT after all. By bringing in measures it can be reduced to proving that $B_n\uparrow B$ implies  $mB_n\uparrow mB$

Proof of Monotone Convergence Theorem


Slackware scripts started at boot time need env vars from /etc/profile.d/* to be set

Question: Hey, I have this problem, that scripts started at boot time from rc.local don't have environment variables (defined at /etc/profile.d/*) set at the time of their startup. What should I do ?

"su - lisak -c /opt/atlassian-jira-enterprise-4.1.1-standalone/bin/startup.sh"
"su - lisak -c /opt/aaa2/at-22/bin/startup.sh"
Answer: The scripts at /etc/profile.d/* are executed in their own shells rather than sourced so the environment variables they set are not available anyway.What variables do you need? Can you make use of /etc/environment? Can you write the variables into a file in a var=value format from the appropriate scripts and source that file in your rc.local scripts?
This is from the Bash man page. You may find it helpful.

When  bash  is  started  non-interactively,  to run a shell script, for
         example, it looks for the variable BASH_ENV in the environment, expands
         its  value if it appears there, and uses the expanded value as the name
         of a file to read and execute.  Bash behaves as if the  following  com‐
         mand were executed:
                if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
         but  the  value of the PATH variable is not used to search for the file
         name.

The Bourne shell similarly uses the ENV variable.
Comment: I don't want to do such workarounds, if I do this often I wouldn't do anything but administration :-)
Comment: /etc/profile and /etc/profile.d/* are accessed for each login shell...and I'm starting the script by su, which doesn't start a login shell I suppose...
Comment: I meant that you should add code that automates the creation of the variable-holding file. Anyway, I was think about this backwards. `rc.local` is run at boot time, but the files in `profile.d` are executed at user login time. You're trying to mix two different worlds - system boot and user login.
Comment: I know that the proper way of doing it would be via /etc/bashrc which is loaded for each interactive shell start. .. btw those $BASH_ENV or $ENV are not visible to users, are they....root doesn't see them...is it something under the hood ?
Comment: Those variables aren't set by default. You set them, for example, in a script that calls another or on the command line of a call to a script. `BASH_ENV=foo /path/to/bar` (on one line, this sets the variable for the environment of "bar").
Answer: Quote from the su manpage (Slackware 13.1):
       -, -l, --login
       Provide an environment similar to what the user would expect had
       the user logged in directly.

       When - is used, it must be specified as the last su option. The
       other forms (-l and --login) do not have this restriction.

In your example, you don't specify - as the last su option. Try doing that or using an alternate argument.
Comment: you are maybe right, but I can't figure out how it would look like... su - lisak -c /opt/aaa2/at-22/bin/startup.sh  is the only order of arguments that is actually possible
Comment: Btw where do you get this manpage from, the mine doesn't mention anything you pasted
Comment: I just typed man su in Slackware 13.1
Answer: I think the best solution is to source /etc/profile.d/*.sh or run /etc/profile from rc.local cause I don't want to duplicate configuration for boot time scripts and scripts started from login shell...
NOTE: I don't know what might be the consequences of running /etc/profile from rc.local ...so the best way would be sourcing them at rc.local from /etc/profile.d/*.sh

AKA:  for file in /etc/profile.d/*; do source $file; done

ALTERNATIVE:  echo ". /etc/profile" >> $HOME/.bashrc     - for single user