What does the CreateMask function of BitVector32 do?

Question: What does the CreateMask() function of BitVector32 do?
I did not get what a Mask is.
Would like to understand the following lines of code. Does create mask just sets bit to true?
  // Creates and initializes a BitVector32 with all bit flags set to FALSE.
  BitVector32 myBV = new BitVector32( 0 );

  // Creates masks to isolate each of the first five bit flags.
  int myBit1 = BitVector32.CreateMask();
  int myBit2 = BitVector32.CreateMask( myBit1 );
  int myBit3 = BitVector32.CreateMask( myBit2 );
  int myBit4 = BitVector32.CreateMask( myBit3 );
  int myBit5 = BitVector32.CreateMask( myBit4 );

  // Sets the alternating bits to TRUE.
  Console.WriteLine( "Setting alternating bits to TRUE:" );
  Console.WriteLine( "   Initial:         {0}", myBV.ToString() );
  myBV[myBit1] = true;
  Console.WriteLine( "   myBit1 = TRUE:   {0}", myBV.ToString() );
  myBV[myBit3] = true;
  Console.WriteLine( "   myBit3 = TRUE:   {0}", myBV.ToString() );
  myBV[myBit5] = true;
  Console.WriteLine( "   myBit5 = TRUE:   {0}", myBV.ToString() );

What is the practical application of this?
Answer: It returns a mask which you can use for easier retrieving of interesting bit.
You might want to check out Wikipedia for what a mask is.
In short: a mask is a pattern in form of array of 1s for the bits that you are interested in and 0s for the others.
If you have something like 01010 and you are interested in getting the last 3 bits, your mask would look like 00111. Then, when you perform a bitwise AND on 01010 and 00111 you will get the last three bits (00010), since AND only is 1 if both bits are set, and none of the bits beside the first three are set in the mask.
An example might be easier to understand:
BitVector32.CreateMask() => 1 (binary 1)
BitVector32.CreateMask(1) => 2 (binary 10)
BitVector32.CreateMask(2) => 4 (binary 100)
BitVector32.CreateMask(4) => 8 (binary 1000)

CreateMask(int) returns the given number multiplied by 2.
NOTE: The first bit is the least significant bit, i.e. the bit farthest to the right.
Comment: How is the mask created? eg how does myBit3 specify the 3rd bit?
Answer: BitVector32.CreateMask() is a substitution for the left shift operator (<<) which in most cases results in multiplication by 2 (left shift is not circular, so you may start loosing digits, more is explained here)
BitVector32 vector = new BitVector32();
int bit1 = BitVector32.CreateMask();
int bit2 = BitVector32.CreateMask(bit1);
int bit3 = 1 << 2;
int bit5 = 1 << 4;

Console.WriteLine(vector.ToString());
vector[bit1 | bit2 | bit3 | bit5] = true;
Console.WriteLine(vector.ToString());

Output:

BitVector32{00000000000000000000000000000000}
  BitVector32{00000000000000000000000000010111}
Answer: Check this other post link text.
And also, CreateMask does not return the given number multiplied by 2.
CreateMask creates a bit-mask based on an specific position in the 32-bit word (that's the paramater that you are passing), which is generally x^2 when you are talking about a single bit (flag).
Answer: I stumbled upon this question trying to find out what CreateMask does exactly. I did not feel the current answers answered the question for me. After some reading and experimenting, I would like to share my findings:
Basically what Maksymilian says is almast correct: "BitVector32.CreateMask is a substitution for the left shift operator (<<) which in most cases results in multiplication by 2".
Because << is a binary operator and CreateMask only takes one argument, I would like to add that BitVector32.CreateMask(x) is equivalant to x << 1.
Bordercases
However, BitVector32.CreateMask(x) is not equivalant to x << 1 for two border cases:

BitVector32.CreateMask(int.MinValue):
An InvalidOperationException will be thrown. int.MinValue corresponds to 10000000000000000000000000000000. This seems bit odd. Especially considering every other value with a 1 as the leftmost bit (i.e. negative numbers) works fine. In contrast: int.MinValue << 1 would not throw an exception and just return 0.
When you call BitVector32.CreateMask(0) (or BitVector32.CreateMask()). This will return 1
(i.e. 00000000000000000000000000000000 becomes 00000000000000000000000000000001),
whereas 0 << 1 would just return 0.

Multiplication by 2
CreateMask almost always is equivalent to multiplication by 2. Other than the above two special cases, it differs when the second bit from the left is different from the leftmost bit. An int is signed, so the leftmost bit indicates the sign. In that scenario the sign is flipped. E.g. CreateMask(-1) (or 11111111111111111111111111111111) results in -2 (or 11111111111111111111111111111110), but CreateMask(int.MaxValue) (or 01111111111111111111111111111111) also results in -2.
Anyway, you probably shouldn't use it for this purpose. As I understand, when you use a BitVector32, you really should only consider it a sequence of 32 bits. The fact that they use ints in combination with the BitVector32 is probably just because it's convenient.
When is CreateMask useful?
I honestly don't know. It seems from the documentation and the name "previous" of the argument of the function that they intended it to be used in some kind of sequence: "Use CreateMask() to create the first mask in a series and CreateMask(int) for all subsequent masks.".
However, in the code example, they use it to create the masks for the first 5 bits, to subsequently do some operations on those bits. I cannot imagine they expect you to write 32 calls in a row to CreateMask to be able to do some stuff with the bits near the left.


The execution of stored procedure and triggers in SQL Server

Question: Suppose that I have the following situation in a SQL Server database.
These are the tables on the database:

Table1
Table2

Associated triggers: trigger on insert (trigger1)

Table3

The database contains one stored procedure sp1 (with parameters).
Now, this is how sp1 works:

sp1 is collecting some rows from Table1 in 2 seconds
Depending on these row's values, maybe some rows will be inserted into table2 (the insert takes 1 second) and off course the insert causes trigger1 to fire
trigger1 inserts or updates some rows in Table3 (it takes 2 seconds more)
sp1 is not done yet after steps 1-3, it continues to work for 2 seconds of processing and then it's finished

Imagine that there's an application (say Java, C# or whatever) calling sp1 100 consecutive times (the calling is much faster than the execution of sp1).
I want to understand how the processing flow works.
Is there any parallelism?
Does sp1 wait for trigger1 to finish before continue to step 4?
While calling sp1 from the application, does every call have to wait before continuing to the next call?
Comment: You've asked 3 different questions here. Try to keep in mind that the rule is one question per post. Btw, you could set up a demo and test all of them in less time than the 1 hour that passed since you published this post....
Comment: @ZoharPeled, I think the three questions are related. I could combine them to make one question but it wouldn't be easy to be understood.
I'm setting up a demo to find out myself and if I do, off course I'll share the knowledge here to let everyone know.
Answer: I have made a demo to test this situation and here's what I found:
1- sp1 always waits for the trigger before continue the rest of the processing.
2- Calling the sp1 from an application will wait for the execution to be finished unless the calling is asynchronous.


Limit timer thread execution time

Question: How can I restrict timer thread execution time? I have long running timer work that should work no more than 30 seconds.
Comment: What's the reason for restricting the thread's executing time? Surely if you want to execute a task on another thread, you would normally leave it to finish it's execution. If you are waiting for an operation to complete and want some form of time-out on that operation, then killing the thread forcefully after a period of time is not the most graceful of ways to go about it.
Comment: You can't directly do that - do you have some kind of loop somewhere that you can check the elapsed time,inside the thread itself?
Comment: Not duplicate, but related: http://stackoverflow.com/questions/299198/implement-c-sharp-generic-timeout
Comment: @ShadowWizard I don't have that loop in timer thread, any ideas?
Comment: Try the code in the accepted answer to the linked question
Answer: The only way to do this is to have a second thread (possibly the one that created the worker thread) monitor and then kill it or gracefully call it to quit immediately. Killing threads you should avoid, and only use as the last resort. Here is example how:
<code>        Thread t = new Thread(myLongThreadProc);
        t.Start();
        Thread.Sleep(30000);
        t.Abort();
</code>
By 'gracefully call it to quit', I mean to set some stop variable to some value, and give the thread some short time to quit itself, otherwise you kill it. But it is the design of your thread function to make it actually quit. Here is the sample code:
<code>        Thread t = new Thread(myLongThreadProc);
        threadRun = true;
        t.Start();
        Thread.Sleep(30000);
        threadRun = false; //this variable is monitored by thread
        if (!t.Join(1000))  //inside your thread, make sure it does quit in one second
        {                   //when this variable is set to false
            t.Abort();
        }
</code>
And should I mention that your caller thread does not have to sleep for 30 seconds, but you can use a timer instead (if it is a form thread) or do something useful and check periodically - or have a third worker thread just counting 30 seconds...
Comment: No need to spin up a separate thread for this. That's a huge waste of resources. And if the thread that started the background thread was going to wait for exit, why start a thread at all? You're better off using a one-shot timer, and having the callback function signal the other thread to stop.
Answer: Just have your worker method start a 30-second timer and check to see if it's elapsed as your worker does its thing:
<code>    bool timerElapsed;

    public void DoWork()
    {
        timerElapsed=false;
        System.Timers.Timer timer = new System.Timers.Timer(30000);
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        timer.Start();

        while (true)
        {
            if (timerElapsed)
            {
                // handle 30-sec elasped error
                break;
            }
            // continue doing work and break when done
        }
        timer.Stop();
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timerElapsed = true;
    }
</code>
Comment: Why use a timer when you could just use `var sw = Stopwatch.StartNew()`, and then have your loop check `sw.ElapsedMilliseconds > 30000`?
Comment: @Mim Mischel - Checking elapsed time could work just as well (BTW, why don't you offer that as an answer?) However, if the OP's code is complex it may be simpler to relegate the elapsed check to a timer.

Limit timer thread execution time


Likert Scale scoring - can I assign negative scores?

Question: I am going to conduct a survey with a 4-point Likert scale. The questions are divided into headers. The responses will be scored and each header will be given a score.
I would like to know if its ok to assign negative scores to the Likert scale
E.G.:
Strongly Agree: 2
Agree: 1
Disagree: -1
Strongly Disagree: -2

or should i just go with positive numbers:
Strongly Agree: 4
Agree: 3
Disagree: 2
Strongly Disagree: 1

I would like to know which one is a better practice and what are the implications of each method.
Comment: I'm not sure what's to be gained from using negative numbers, what's your logic for considering this? Interesting that you've chosen to avoid the neutral middle...thus forcing a choice.
Comment: The respondent will never see the negative numbers. In the survey form they will be simply  as options 1,2,3,4. However, like I mentioned, each question is categorized into 8 different impact areas. The impact area will get a final calculated score based on the responses. i.e if EVERYONE answers "strongly disagree" for all the questions in one area the avg score for that impact area will be '-2' if I use negative numbers and '1' if I use 1,2,3,4 as the scores. I would like to know which one is more correct mathematically and statistically.
Comment: I've updated my answer below with some thoughts on the different scoring methods you're considering.
Answer: Don't show the numbers to the test takers; it will only confuse them. But you may want to use them internally.
Balanced keying (using an approximately equal amount of positively and negatively keyed items) is often used in psychometry and is considered good practice. It allows you to approach a topic from different perspectives.
Some sample items (measuring extraversion):
+ keyed: Feel comfortable around people; Make friends easily; Am skilled in handling social situations.
– keyed: Have little to say; Keep in the background; Don't like to draw attention to myself.
With a four-point scale, you'll probably find that option 3 will collect most of the 'neutral' or 'don't know/don't want to tell/don't understand' responses that would otherwise go into the middle option. For analysis, you can just assign scores 1 (strongly disagree) to 4 (strongly agree) for positively keyed items, and reverse them for negatively keyed items (4 for strongly disagree and 1 for strongly agree). If you allow to skip items, it makes sense to use a scale with a mean of 0 so you can count any non-answered questions as 0 while still using simple addition to calculate the total score.
As for the number of categories in your Likert scale: fewer categories allow for faster decisions and faster completion times of the questionnaire, more categories are slower but people will (subjectively) feel that they can express their feelings more precisely.
Addition:
Something to keep in mind with Likert scales is that they are ordinal scales, not interval scales. It often works quite well though if you assign numerical values to the categories and use them to calculate a total score. There are alternative methods available for working with polytomous items and calculating totals, such as item response theory, taking into account individual item characteristics, but they're not as clear and practical as simple addition.
The main difference between a scale scored from 1 to 4 (or a shifted version: -2.5, -1.5, +.5, +1.5) and your proposed idea of -2 to +2 is the width of the middle interval, between disagree and agree. With a normal (small) middle interval it takes 3 disagrees to offset 1 strong agree (3*2+4=10; mean 2.5); with a larger middle interval it only takes 2.
With Likert scales people (especially introverts) tend to avoid the extreme categories (I did a research project on this, and it was striking how often for the same question people would answer 'yes, absolutely!' in natural language while in the Likert scale questionnaire they didn't choose 'strongly agree'). If you give the extreme categories less weight, that could influence the totals.
Here's an example: total scores for a 5-question extraversion scale calculated with both methods and plotted against each other (for 2700 people):

The scores don't fit perfectly and the differences are statistically significant, but for most of the scores it doesn't make a large difference. The maximum difference on the total score here is only 2.5 (and if you adjust for the different ranges only 2). Looking at the score distribution (range adjusted again) you see the same pattern:

So in short: if you want to use a coding scheme -2/-1/+1/+2, go ahead; it probably won't matter for the end results. The extreme response categories will count a little less, and the range of possible scores differs from the other scheme. Results will differ, but you can expect the difference to be small. (However, I'd go with the simplest scheme.)
Comment: Thoughtful response, Marielle. +1
Comment: A found another interesting upon googling a little (method 4): http://www.measuringusability.com/blog/interpret-responses.php   what do you think?
Comment: Short answer (can't post pictures in comments): could be quite useful in practice, I'm not sure if I like it. It basically compares the mean score from your results with another normal distribution (combining the standard deviation from your results with a chosen cut-off point).
Comment: yeah i dont understand how and why they choose 80% as a benchmark. Any idea or links on how to choose an appropriate benchmark in case I wish to apply this method? Also, why dont you like it?
Comment: The 80% part as a cut-off makes sense to me, for most kinds of satisfaction surveys. If you ask people to agree/disagree with 'I'm satisfied with this product', an average score of 3 on a 5-point scale is not a good result, you'll need at least 4.
Comment: Ok is seems like this statistical approach is definitely giving more consistent results. In the other methods, the moment you change your metrics the results change dramatically.  So I have tons of questions and a z-score and percentile for each is calculated. Each question is divided into 9 headers. Should I simply take the average percentile for each header as the header score? or Should I again take a benchmark and use this same method - basically a percentile of the percentiles - a 2nd iteration?
Comment: Also, some of my questions have 0 standard deviation, since all respondents gave the same answer. So the above method gives errors in excel for that. Now I know that this is not a normal distribution but what I've done for them is simply taken the average response rating and divided it by the highest possible - which gives you a percentage for each of those questions, which goes into the calculation of the average percentage for the header. Is that ok, or do you suggest some other way?
Answer: Building on Marielle's excellent answer, I just want to add that you should be careful when assigning numerical values to a scale that is still basically qualitative in nature. That doesn't mean you shouldn't, you should just be careful how you use those values. When you have a value, you can calculate things like percent changes between two measurement periods.... but these percent changes, and many other statistics, are sensitive to what numbers you arbitrarily assign to the scale.
As an example, an insurance company was considering awarding a special bonus for x% improvement in customer satisfaction scores for each agent. They used a mean of 1->5 satisfaction scores to rank the employees, until somebody pointed out that going from a 1 to a 2, or going from utterly dismal to less dismal, was a 100% increase, while going from a 4 to a 5, from great to flawless, was only a 25% increase. Arguably, the second employee was better deserving of a bonus, but they only looked 1/4 as good on paper. Basically, their use of numerical scales and means wasn't working for what they were trying to do.
Because of these difficulties, I prefer to avoid assigning numerical values to responses if I can get away with it - but I can't always.
Comment: +1 Lies, damn lies and statistics...wish I was the first to say that.
Comment: Thanks for your response. Please see my response to @Roger Attrill above. i wont really be calculating improvement or change, just a score. the problem with the negative scores is that the distance between options 2 and 3 is is two units and the distance between others is one unit. But my logic for considering the negative scores is that I wanted the "disagree" responses to subtract from the score and be able to show a negative final average score if most people answer this way. not sure if its mathematically correct though.   @Marielle @Gary Franceschini
Comment: Neither is more "correct" from a mathematical perspective. I see your point that you are varying the difference in scores between each verbal anchor, and that probably would be more likely to raise questions than the other method. But "agreement" is not a fundamentally numeric measure and any numerical assignment is arbitrary. People don't necessarily see these verbal anchors as equally spaced from each other, and they don't necessarily see their mental "0" point in the same place as others would. Have you thought about reporting top-2-box (Agree, Strongly Agree) percentage?
Comment: This is all just a question about reporting - while it's best to decide on a reporting method before you run the survey, you can always try all three methods after you have your data (1->4 mean, -2 -> +2 mean, T2B%) and see how they vary.
Answer: Use positive numbers only.
A Likert scale gains nothing from the use of negative numbers. In fact, you are likely introducing a bias into your responses because the negative numbers will create an emotional response - driving users to selecting the most moderate of the positive responses (partially due to central tendency bias).
Answer: A couple of things:
1/ Your scale is lacking the neutral value in your Likert scale (Neither agree nor disagree) as most such scales are based on five points.
2/ You can add values to each scale item but indeed, you should not display these to your user / respondent at all as they could induce a perspective.
Often, such values can be negative in survey methodologies (market research, opinion polls, ...):
Strongly disagree (2)
Disagree (1)
Neither agree nor disagree (0)
Agree (-1)
Strongly agree (-2)
The above is generally used to analyse the data as a numerical variable rather than a closed question (thus allowing the analyst to apply Mean and such other statistical calculations)
Comment: No neutral value is known as a forced response. This is an accepted form of the scale.


Indexing data.frames using arrays of TRUEs and FALSEs

Question: I'm having some trouble indexing data.frames in R. I'm an R beginner. I have a data.frame called d which has 35512 columns and 77 rows. I have a list called rd which contains 35512 elements. I'd like all the columns of d which correspond to the items in rd less than 100. Here's what I'm doing:
# just to prove I'm not crazy
> length(colnames(d))
[1] 35512
> length(rownames(d))
[1] 77
> length(rd)
[1] 35512
# find all the elements of rd less than 100 (+ unnecessary faffing?)
> i <- unlist(rd<100)
> names(i) <- NULL
# try to extract all the elements of d corresponding to rd < 100
> d <- d[,i]
Error in `[.data.frame`(d, , i) : undefined columns selected

I don't really want to be doing the unlist and names(i) <- NULL stuff but I'm getting seriously paranoid. Can anyone help with what the hell this error message means?
In case it helps, the rd variable is created using the following:
rd = lapply(lapply(d, range), diff)

Which hopefully tells me the difference in the range of each column of d.
P.S. bonus awesomeness for anyone who can tell me a command to find the shape of a data.frame other than querying the length of its row and column names.
Edit: Here's what rd looks like:
> rd[1:3]
$`10338001`
[1] 7198.886

$`10338003`
[1] 4748.963

$`10338004`
[1] 3173.046

and when I've done my faffing, i looks like this:
> i[7:10]
[1] FALSE FALSE FALSE  TRUE

Comment: What is the length of i?  Confirm that this is true: `length(i) == ncol(d)`.  Also, check if you have any NA's in i.  `any(is.na(i))`  Lastly, check `is.logical(i)`.
Comment: Argh! `any(is.na(i))` returns `TRUE`. Thanks for this clue!
Comment: Why do you have such a wide data.frame? Are you sure you don't want a long data.frame instead? Or if everything's numeric, just a matrix? Internally, data.frames are lists of column vectors, so very wide dfs are not very efficient to manipulate.
Comment: Hi Harlan - my data.frame has simply ended up this way after days of my inexpert hacking. I didn't know about the internal representation, and I guess I'm used to a row-centric representation from Python! Will transpose... It's a data.frame not a matrix as there were factors in there until i decided to be interested in the range of each column. Essentially there's no design here; i just follow chalk...
Answer: Have you tried this:
d[,rd < 100]

Here's a self-contained example:
d <- data.frame(matrix(1:100, ncol=10))
rd <- as.list(1:10)
d[,rd < 5]

To get the shape of a dataframe, use nrow and ncol.
Edit:
Based on your response to my NA question, it sounds like you have non-logical values in your index that result from missing values in your list.  The best thing to do is to first decide how you want to treat a missing value.  Then deal with them using the is.na function (here I extend my example from above):
rd[[3]] <- NA
d[,rd < 5]
# => Error in `[.data.frame`(d, , rd < 5) : undefined columns selected

To deal with this, I will set that NA value to 0 (which means that it the respective column will be included in the final data.frame):
rd[is.na(rd)] <- 0
d[,rd < 5]

You need to decide for yourself what to do with the NA values.
Comment: yep! That's what I tried first. I got the same error. That's when I started unlisting and removing the names and such.
    > d[,rd < 100]
    Error in `[.data.frame`(d, , rd < 100) : undefined columns selected
Comment: Please provide a small sample of the data for rd.
Answer: For the bonus Q, you get "shape" of a data frame or matrix using the "dim" command.
A = matrix( ceiling(10*runif(40)), nrow=8)
colnames(A) = c("col1", "col2", "col3", "col4", "col5")
df = data.frame(A)
b = ceiling(100*runif(5))

ndx = b < 50
result = df[,ndx]     # just the columns of df corresponding to b < 50

Comment: thanks for the 'dim' command! I think i need to purchase some yellow springer


why retracted fact template is still available?

Question: I am trying to modify a fact of a fact-template in clips using ClipsPY. Following code retracts and reasserts the fact. Why is it that after the fact is retracted, the slot value s_2 is not nil on reassert?
run.py
import clips

clips_env = clips.Environment()

def py_pfact():
    for fact in clips_env.facts():
        print(fact)

def py_modify(p):
    print("\nfacts:")
    py_pfact()

    p.retract()
    print("\nfacts after retracted:")
    py_pfact()

    p["s_1"] = clips.Symbol("v_2")
    p.assertit()
    print("\nfacts after re_assert:")
    py_pfact()

clips_env.define_function(py_pfact)
clips_env.define_function(py_modify)

clips_env.load("KB.clp")
clips_env.reset()
clips_env.run()

This is the clp file
;; KB.clp
(deftemplate t
            (slot s_1 (type SYMBOL))
            (slot s_2 (type SYMBOL))
    )

    (defrule main-intent
            (initial-fact)
            =>
            (assert (t (s_1 v_1) (s_2 v_2)))
    )

    (defrule rule_1
            ?p<-(t (s_1 ?v&~v_2))
            =>
            (py_modify ?p)
    )

The output is:
facts:
(initial-fact)
(t (s_1 v_1) (s_2 v_2))

facts after retracted:
(initial-fact)

facts after re_assert:
(initial-fact)
(t (s_1 v_2) (s_2 v_2))

I expected output to be (t (s_1 v_2) (s_2 nil)), however s_2 is not nil but previous set value v_2 which was set before the fact retracted.
Comment: It is not necessary to add the initial-fact to a rule with no other conditions; it is added automatically in versions of CLIPS prior to version 6.3. The initial-fact functionality was deprecated in the 6.3 release; it is still asserted by a reset, but rules without conditions no longer rely on it. In the 6.4 release, the initial-fact is no longer asserted, so rules that explicitly match this fact will no longer be activated.
Answer: Asserting and retracting a fact does not modify it. It simply adds/removes it from the engine knowledge base.
You can see a deftemplate as a class and a fact created from it like an object. You can extend the engine knowledge base by adding and removing facts either from the API or through the rules.
# define a fact template within the engine
environment.build('(deftemplate foo (slot bar) (slot baz))')
template = environment.find_template('foo')

# create a new fact and set its values
fact = template.new_fact()
fact['bar'] = 1
fact['baz'] = 1

# assert the fact within the engine
fact.assertit()

assert fact in environment.facts()

# retract it
fact.retract()

assert fact not in environment.facts()
assert fact is fact  # fact is the same object as before

fact['baz'] = 2

assert fact is fact  # still the same object

fact.assertit()

assert str(fact) == '(foo (bar 1) (baz 2))'


Orphan users/application users

Question: How an orphan user can be an application user at the same time?
If I delete an orphan user at database level, how can I affect his access at application level?
Comment: Are you referring to an application user who is a login or a user that an application (such as a c# program) uses to access a database? An orphan user is typically means that a SQL Server database user and SQL Server login at the instance level (while they share a name) don't refer to each other.
Comment: Both?...I mean, I understand that an orphan user is useless to connect to a database, because there is no login, but maybe It was created as a role. But if not, how can I access to the database eather way? Sorry if I can't be more clear about it, but my english is not so good.
Answer: The concept of Orphan User is a bit different than what you have explained.
An Orphan User in a database is a user which isn't mapped to a login. Usually it happens when we move databases across servers or you delete a login without deleting all the users mapped to that login.
Say on ServerA you took a backup of DatabaseA which has a UserA with LoginA.
Now you restored this backup on ServerB which also has a login LoginA. when you restore the database on ServerB the UserA will become an Orphan User and you will fix it by executing the following command:
ALTER USER [UserA] WITH LOGIN = [UserA];

This will map the UserA to LoginA on ServerB.And if you do not fix this whether it be your application or anything who uses this UserA's credentials will not be able to access the Database on ServerB.
Comment: Thank you. So, If I'm using VB, C# or any other application like those, I cannot be able to connect to my database because I don't have login mapped to that user....I'm I correct?? So, that user is useless. But what if I'm using an end user application? same result? thank you again.

Orphan users/application users


Using anchorString seems to break radio groups

Question: If I specify a radio group using anchor strings, then when selecting one of the radio buttons, either the previous or next radio is marked as selected, not the one clicked.
<code>"\"radioGroupTabs\": [
    {
    \"documentId\": \"1\",
    \"recipientID\": \"1\",
            \"groupName\": \"RadioGroup1\",
            \"radios\": [
                        {
                           \"pageNumber\": \"1\",
                           \"selected\": \"false\",
                           \"anchorString\": \"!!radio1\"
                        },
                        {
                            \"pageNumber\": \"1\",
                            \"selected\": \"false\",
                            \"anchorString\": \"!!radio2\"
                        }
                    ]
                }
]"
</code>
If I specify the position using x & y co-ordinates then it works....
Very confused here!
Comment: It's possible you've encountered an API bug, I'd reach out to your account manager to get this logged and fixed if that's the case.
Answer: Try adding the "value" node. When the expected behavior is to choose between the two, you should have a distinct value for each.
Example:
<code>                        "radios": [
                            {
                                "pageNumber": "1",
                                "selected": "false",
                                "anchorString": "!!radio1",
                                "value": "Male"
                            },
                            {
                                "pageNumber": "1",
                                "selected": "false",
                                "anchorString": "!!radio2",
                                "value": "Female"
                            }
                        ]
</code>


Probabilities of errors in three independent transmissions

Question: i have been working through some old exam papers and have gotten stuck on this last one. can anyone help?
When a piece of information (a bit) is transmitted over a communications channel, it may be wrongly communicated. One method of improving reliability is to transmit the same piece of information an odd number of times, and use a majority decoder. The information is taken to be the bit received the most (from the odd number). A simple model for noisy communication is to assume that each transmitted bit is independently corrupted during transmission with the same probability $p$ where $0 < p < 1$. Now consider a two-out-of-three majority decoder.
(a) Let $Y$ be the random variable that counts how many (out of the three bits) are correctly communicated. What are the possible values of $Y$ ?
(b) Find the probability mass function of $Y$ , writing it either in a table or as a list.
(c) For which values of $Y$ will the majority decoder correctly interpret the information sent?
(d) In terms of $p$, what is the probability that a piece of information is correctly communicated? Also write this in terms of $F(y)$.
(e) For what values of $p$ is the majority decoder more reliable than transmitting the message only once?
i am assuming the answer to (a) is $Y=0,1,2,3$ but my answers for the rest are not making sense
Thanks!
Answer: (a) You are correct, $Y$ can be either $0,1,2$ or $3$.
(b) You simply need to calculate $P(Y=0), P(Y=1), P(Y=2)$ and $P(Y=3)$. How would you calculate $P(Y=0)$? Remember, $P(Y=0)$ is the probability that no errors occured, which means that it is the probability that no error occured in the first transmission and no error occured in the second transmission and no error occured in the third transmission.
(c) Is the decoder correct if $Y=0$? What about if $Y=1$? If $Y=2$? What about $Y=3$?
(d) After you answer (c), this answer will be easier.
(e) After you answer (d), this answer will be easier.
Comment: how do i calculate P(Y=0), P(Y=1), etc with what i have been given? that's whats really got me?
Comment: @Rachael Did you read the part where I said that $P(Y=0)$ is the probability of (something **and** something else **and** something else)? Do you remember how you calculate $P(A\text{ and } B$ if $A$ and $B$ are independent?


Animations in ipython (jupyter) notebook - ValueError: I/O operation on closed file

Question: I have a jupyter notebook that produces an animation. It was working on my old laptop (xubuntu gnu/linux). Now on my new laptop (trisquel gnu/linux) it's not working. This makes me think I have a missing library or something like that but I can't work it out.
As a test, I went back to the tutorial where I learned how to do jupyter notebook animations in the first place (http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/). I get the same problem when I run code cell [7].
The error is shown below.
Any help in solving this problem would be greatly appreciated.
Many thanks :)
[edit 1] If I try anim.save(...) instead of HTML(anim.to_html5_video()), I get the same problem.
[edit 2] If I download the notebook as a *.py file and run it using regular python (rather than ipython), then I get the same problem.
[edit 3] My ffmpeg installation appears to be working as I am able to manually create an animation from a series of images. I can use this as a work-around for now but it's very clunky and the HTML(anim.to_html5_video()) solution should work so still needs to be sorted.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-5114ccf53b4c> in <module>()
----> 1 HTML(anim.to_html5_video())

/usr/local/lib/python2.7/site-packages/matplotlib/animation.pyc in to_html5_video(self)
   1157                                 bitrate=rcParams['animation.bitrate'],
   1158                                 fps=1000. / self._interval)
-> 1159                 self.save(f.name, writer=writer)
   1160
   1161             # Now open and base64 encode

/usr/local/lib/python2.7/site-packages/matplotlib/animation.pyc in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs)
   1011                         # TODO: See if turning off blit is really necessary
   1012                         anim._draw_next_frame(d, blit=False)
-> 1013                     writer.grab_frame(**savefig_kwargs)
   1014
   1015         # Reconnect signal for first draw if necessary

/usr/local/lib/python2.7/contextlib.pyc in __exit__(self, type, value, traceback)
     33                 value = type()
     34             try:
---> 35                 self.gen.throw(type, value, traceback)
     36                 raise RuntimeError("generator didn't stop after throw()")
     37             except StopIteration, exc:

/usr/local/lib/python2.7/site-packages/matplotlib/animation.pyc in saving(self, *args, **kw)
    254             yield self
    255         finally:
--> 256             self.finish()
    257
    258     def _run(self):

/usr/local/lib/python2.7/site-packages/matplotlib/animation.pyc in finish(self)
    274     def finish(self):
    275         'Finish any processing for writing the movie.'
--> 276         self.cleanup()
    277
    278     def grab_frame(self, **savefig_kwargs):

/usr/local/lib/python2.7/site-packages/matplotlib/animation.pyc in cleanup(self)
    309     def cleanup(self):
    310         'Clean-up and collect the process used to write the movie file.'
--> 311         out, err = self._proc.communicate()
    312         self._frame_sink().close()
    313         verbose.report('MovieWriter -- '

/usr/local/lib/python2.7/site-packages/subprocess32.pyc in communicate(self, input, timeout)
    925
    926         try:
--> 927             stdout, stderr = self._communicate(input, endtime, timeout)
    928         finally:
    929             self._communication_started = True

/usr/local/lib/python2.7/site-packages/subprocess32.pyc in _communicate(self, input, endtime, orig_timeout)
   1711             if _has_poll:
   1712                 stdout, stderr = self._communicate_with_poll(input, endtime,
-> 1713                                                              orig_timeout)
   1714             else:
   1715                 stdout, stderr = self._communicate_with_select(input, endtime,

/usr/local/lib/python2.7/site-packages/subprocess32.pyc in _communicate_with_poll(self, input, endtime, orig_timeout)
   1767             select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
   1768             if self.stdout:
-> 1769                 register_and_append(self.stdout, select_POLLIN_POLLPRI)
   1770                 stdout = self._fd2output[self.stdout.fileno()]
   1771             if self.stderr:

/usr/local/lib/python2.7/site-packages/subprocess32.pyc in register_and_append(file_obj, eventmask)
   1746             poller = select.poll()
   1747             def register_and_append(file_obj, eventmask):
-> 1748                 poller.register(file_obj.fileno(), eventmask)
   1749                 self._fd2file[file_obj.fileno()] = file_obj
   1750

ValueError: I/O operation on closed file

Answer: I ran into the same issue (on a mac os 10.12.2), and fixed it by reinstalling ffmpeg and enabling the x264 codec , which the to_html5_video() function needs to convert the animation to html5.
To install x264:
cd /my/path/where/i/keep/compiled/stuff
git clone git://git.videolan.org/x264.git
cd x264
./configure --enable-static --enable-shared
make
make install
ldconfig # note: use for linux, not necessary for mac

source
To install ffmpeg with the x264 codec enabled:
cd /my/path/where/i/keep/compiled/stuff
git clone http://source.ffmpeg.org/git/ffmpeg.git
cd ffmpeg
./configure --enable-gpl --enable-libx264
make
make install
ldconfig # note: use for linux, not necessary for mac

source
Comment: @Biggsy, were you able to fix the issue?
Comment: YES! It worked! Apologies for the delay - I've been so busy with other things I've only just had a chance to try it now but yes, it works. Thank you so much :)


What is the difference between a point transformation and a vector transformation?

Question: This is what my lecturer told me in the coursework:
We only consider 4*4 matrices. These are used to rotate, scale or translate objects (or any combination of these operations). Matrices are also used later in the implementation of the virtual camera model. If you do not know the difference between a vector transformation and point transformation, look it up.
I can't seem to find an answer and made an account for this website just for this question.
Comment: In complement to all the other answers and because other people already answered this question in length elsewhere you can check:

https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/geometry/transforming-points-and-vectors
Answer: Here's the simple answer.
In 4D, to be able to multiply them by a 4x4 matrix, vectors are represented as (x,y,z,0) and points are represented as (x,y,z,1).
Since the 4th row of a 4x4 matrix represents the translation of the matrix, the above representations make it so points are affected by translation, but vectors are not.
Both vectors and points are affected by the rotation, scaling, etc though.
Caveat:
There is deeper discussion to be had if you expect the vectors to have certain properties.  For instance, if you transform a triangle's normal by the same matrix you transform the triangle's vertices, it likely won't actually be the normal vector of that triangle anymore. This is because normal vectors have a sort of inverse relationship to the vertices that they are calculated from.
Comment: surface normals are bivectors, not vectors.  We can find a normal by the cross product of two vectors, the result is a bivector.  SEE Per Vogensen's: https://gist.github.com/pervognsen/c6b1d19754c2e8a38b10886b63d7bf2d
Comment: Normals don't work because they're not vectors.  Don't know of a good intro to the concept though.
Answer: From what I've learnt, since I'm also a student, is that you want to work with $4 \times 4$ matrices in order to treat rotations, scaling and translations in the same way, that is, multiplying by a matrix (i.e., a $4 \times 4$ matrix).
Remember that without these $4 \times 4$ matrices, translations would be represented by summing with a vector, whereas rotations and scaling are represented using multiplications with respectively a vector and a scalar factor.
Now the question is: how do we pass from a 3D coordinate systems to a 4D one? The answer is "homogenous coordinates".
So, what does it mean? We construct $4 \times 4$ matrices to represent rotations, scaling and translation, so that we only use matrix multiplications to represent transformations (e.g., rotations, scaling, etc). How we construct them individually, it's more specific, but you can have a look it on the web.
At this point, we have $4 \times 4$ matrices and 3D vectors, not useful yet, because you can't multiply $4 \times 4$ matrices and $3D$ vectors, since the dimensions do not match. That's why, when we work with homegeneous coordinates, we also need to convert our given 3D points into corresponding 4D ones.
How do we do it?
We distinguish between direction and position vectors. Direction vectors, as the name suggests, have a direction at which they are pointing; we also care about their length, but they are not affected by translations, since we don't care about their position. Position vectors (or simply "points") can be translated or moved around; they are usually represented with respect to the origin, i.e. as a vector from the origin to the point itself.
We transform 3D direction vectors by adding a $0$ as the $4$th coordinate of the corresponding homogeneous vector: we add a zero because this basically eliminates the effect of translations. We do a similar thing with position vectors, but instead of a $0$ we add a $1$, for the opposite reason.
For example, if we have a $3D$ direction vector $v = \begin{pmatrix} v_1 \\ v_2 \\ v_3\end{pmatrix}$, we transform it by doing $v' = \begin{pmatrix} v_1 \\ v_2 \\ v_3 \\ 0\end{pmatrix}$. Similarly, if we had a point vector $u = \begin{pmatrix} u_1 \\ u_2 \\ u_3\end{pmatrix}$ we would transform it to $u' = \begin{pmatrix} u_1 \\ u_2 \\ u_3 \\ 1\end{pmatrix}$
Note: to convert from homogeneous coordinates back to corresponding $3D$ ones, you can't simply remove the $4th$ coordinate, unless it's still equal to $1$ (or $0$ respectively).
Comment: This answer would be more complete if you noted that, in actual [homogeneous coordinates](https://en.wikipedia.org/wiki/Homogeneous_coordinates), $(wx, wy, wz, w)$ for any $w \ne 0$ is also a valid representation of the point $(x, y, z)$. When converting from ordinary 3D coordinates to 4D projective coordinates, it's convenient to choose $w = 1$, but allowing other values of $w$ in the inverse conversion lets us represent [perspective transformations](https://en.wikipedia.org/wiki/Perspective_transform) using 4D matrix multiplication, too.
Answer: If you would look up the definition of a vector and a point, then a vector is:

A quantity, such as velocity, completely specified by a magnitude and a direction.
  http://www.thefreedictionary.com/vector

And a point is:

A dimensionless geometric object having no properties except location.
  http://www.thefreedictionary.com/point

So you could say that a vector is a direction with scale, and a point is a location.
So, if you transform a vector you just rotate and scale it. With a point you also translate it (the rotation and scaling of a point is around the origin, since it iss just a location the point itself cannot be rotated).
Most of the times a vector and a point are put into the same container, a vector with 4 components. The only difference is the w component. If the w component is 0, then it is a direction. If it is 1 then the vector is a point.
The reason for this can be found in the matrix itself.
It makes use of the way you multiply a vector with 4 components with a 4x4 matrix. If you do not know how that works, I would suggest a quick google.
Most of the times you use a 4x4 matrix. A normal transformation matrix could look like this:
\begin{bmatrix}rot+scale&rot+scale&rot+scale&translation\\rot+scale&rot+scale&rot+scale&translation\\rot+scale&rot+scale&rot+scale&translation\\0&0&0&1\end{bmatrix}
(The rotation and scale are put in the 3x3 area you could say, so for just rotation and scale a 3x3 matrix could also be used, but when translation comes in, we need that 4th column.)
As you can see, if the last component is 0, then you have a multiplication with 0 and therefore the result is 0 and there is no translation.
This makes it easy in computer graphics with polygonal objects. You have the same transformation matrix to transform the positions but also the normals. Because the normals have their w component set to 0 and the positions' w component is 1, the normals are just rotated (and also scaled which can lead to some weird stuff, so most of the times the normal is normalized after. It isn't actually recommended to use the same matrix for positions and rotations because of the weird stuff! Look at @JarkkoL 's comment.) and the positions are translated (and rotated and scaled around the origin).
Hope I did not make a mistake :P, and this helped you!
Comment: Normals are not transformed with the same transformation matrix as positions. You need to calculate inverse of the transpose of the 3x3 sub-matrix to properly transform normals for transformations with non-uniform scaling and/or skewing.
Comment: @JarkkoL yeah that is true, you are right with that. It is best to not use the same matrix, but depending on the implementation, it is done. Most of the times people do not care about the skewing of the normals that much, because they either do not use non-uniform scaling or scaling at all. That part about transforming positions and normals was more about that it could be useful to use one container.
Comment: super late to the party but... what if you have vertex positions of an object in its own local frame, and want to rotate the object. it would seem that representing the vertex positions as locations would make them un-rotatable, so the correct representation would actually be vectors (direction + scale)?


running ruby on rails function without opening the browser

Question: Hi
I need to build an ruby on rails application which will call every 1 second to a remote Api url,  in order to catch an event that should be occurred in that remote web server
the url is

"remoteservername.com/folder/folder/waitforevents"

once the wanted event is occurred I need to perform some actions and call again to the "remoteservername.com/folder/folder/waitforevents" url.
This should be a continuously task and done without the opening of a browser. It means that this application should start running immediately after my web server is started.
so my question is how can I run a ruby on rails application without opening the browser
just the server
until now I had experience in writing rails applications which started when the browser was opened and some url was invoked.
so I will be glad if you could guide me on this issue
THANKS
Comment: I think you're looking for a cron job. See the whenever gem. Tutorial available in Railscasts.
Answer: Are you sure you need rails for that kind of application? I suggest you try doing the job with raw ruby code, easier to maintain. As others already said, you can use cron to launch your application at regular intervals.
Answer: You may use cron together with ./script/rails runner, which can execute any method from your rails application.
Since you need to execute some action every second, you may start that runner once, and create a loop. You may start it from the cron, save the PID somewhere and later ask the cron to kill given process, OR you may just timeout in your Ruby code, in the loop. A simple example:
class MyModelOrAnything
  def self.start_loop
    stop_fname = "./stop_the_loop"
    while !File.exist? stop_fname
      do_this_action
      sleep 1
    end
  ensure
    File.unlink stop_fname  if File.exist? stop_fname
  end
end

A cron task may then create a file "stop_the_loop" in known directory, and your task will stop after a second.
In fact, cron may not be necessary in this case. Since you should have only one instance of this script, it would be better to start it manually, and stop it manually. If you want to use cron, you could add a semaphore-like file, which will tell the script that one process is already running (The file should be removed by the 'ensure' block).
An example of the cron config:
0 8  * * 1 cd /my/app && bundle exec ./script/rails runner ThisObject.start_loop
0 22 * * 5 touch /my/app/stop_the_loop

..and an example with this 'semaphore':
class MyModelOrAnything
  def self.start_loop
    running_fname = "./i_am_working"
    return :already_running if File.exist? running_fname
    stop_fname = "./stop_the_loop"
    begin
      File.open(running_fname,'w') {|f| f.write Time.now.to_s(:db) }
      while !File.exist? stop_fname
        do_this_action
        sleep 1
      end
    ensure
      File.unlink running_fname if File.exist? running_fname
      File.unlink stop_fname  if File.exist? stop_fname
    end
  end
end

Comment: in order to listen to the api remote server event I need to call the
Comment: in order to listen to the api remote server event I need to call the

"remoteservername.com/folder/folder/waitforevents" url **every 1 second**

from what I sow the minimum cron job interval is 1 minute.
so is it possible to do the url continues call from my application with some kind of loop and ask the cron job just to perform the function without setting an time interval ?
Comment: I mean can i tell the corn job to start some task in a predefined time and end it in a predefined time. for example start the job now and end it three days from now?
Answer: A good way is to use delayed job:
https://github.com/collectiveidea/delayed_job
There is a railscast on the topic which may help:
http://railscasts.com/episodes/171-delayed-job
Comment: can I run delayed job without opening my browser?


Is it possible to declare dynamic constants in Laravel models using records for the model?

Question: Say for instance I have a status model and I want to create constants from the status table using the status specific field records
class Status extends BaseModel
 {
    protected $table = 'Status';

    protected $primaryKey = 'id';

    //here or in the constructor, I wants to query records for the same model then declare constants like
     foreach($records as $key => val){
       const $key = $val;
     }
 }

Comment: No, it is __not__ possible.
Answer: You lack in basic programming knowledge.
A const variable is supposed to never change
A static variable is supposed to be accessed as class member without initializating class (using a new keyword)
A non-static non-const variable is accessible only after initializating  a class with new keyword
You probably want to replace a bad
const $key = $val;

with
$this->$key = $val;

Which will work in Laravel
class Status extends BaseModel
{
    protected $table = 'Status';

    public function __construct(array $attributes) {
        parent::__construct($attributes);

        $records = [
            'some_reflected_field_1'  = 100,
            'some_reflected_field_2'  = 101,
            'some_reflected_field_3'  = 102
        ];

        foreach($records as $key => val) {
            $this->$key = $val;
        }
    }
}

Execution:
$foo = new Status([
    'name'  => 'active'
]);

echo $foo->some_reflected_field_2; // 101

Comment: A question implies that there is lack of knowledge
Comment: A question is soliciting an explanation, not an attack.


PHP shuffle, multiple loop

Question: I want to shuffle 2 loops (or function) in the same correct order, in PHP.
The code currently looks like:

<?php

    // Get the list of all files with .jpg extension in the directory and save it in an array named $images
    $directory = "uploads/_gallery/*.jpg";

    // Create an array of images found in the uploads directory
    $images = glob($directory);

    // Randomise/shuffle the images
    shuffle($images);

    foreach( $images as $image ):
        if ($image) { ?>

                <?php echo ""; ?>

        <? }
    endforeach;

?>

<?php

    // Get the list of all files with .jpg extension in the directory and save it in an array named $images
    $directory = "uploads/_gallery/thumbs/*.jpg";

    // Create an array of images found in the uploads directory
    $images = glob($directory);

    // Randomise/shuffle the images
    shuffle($images);

    foreach( $images as $image ):

        if ($image) { ?>

                <?php echo ""; ?>

        <? }

    endforeach;

?>

I've tried creating two separate image arrays and merging those with Shuffle, but no luck.
Answer: I assume the file has the same name in both directory.
So shuffle $images and then use basename($images) to get the filename :
$directory = "uploads/_gallery/*.jpg";
$images = glob($directory);
shuffle($images);

// For full sized images
foreach ($images as $image) {
    // Your stuff
}

// For thumbnails
foreach ($images as $image) {
    $basename = basename($image);
    $thumbnailPath = "uploads/_gallery/thumbs/". $basename;
    // Your stuff
}

Comment: Thanks for the speedy reply @JesusTheHun (fun nick btw).
I tried your suggestion, but the thumbs are loading the top most base directory, not the thumbnail directory. Should I wrap each foreach in a function?
Comment: Did you just copy my code ? Because I forgot a slash in the thumbnail path (edited now). Is the path correct when you look at your html render ? If yes and it doesn't work, then I don't understand the result you expect
Comment: To answer your previous question: and I realised this might be the issue, the thumbs have the same name besides, filename_1_thumb.jpg.

And yes, I did add the slash to the thumbnail path
Comment: So, I renamed the images and change this: `"; ?>` to `"; ?>`. And it works. Thanks a million!

PHP shuffle, multiple loop


Codeigniter - passing form input information to the controller and displaying it on next view

Question: This question is possibly a duplicate but I cannot find the exact answer I am looking for.
I have two forms and two controllers.
I want to input data into the fist controllers view. on that page submit the data tot he second controller and display it on that controllers view.
Now I have tried to insert the form input data in an array in my controller and then access it as a normal variable in the view but without luck.
My Controller for first form
function new_order_details()
  {
      $this->load->view('sales/new_order_details');
  }

My input form view: new_order_details'
<form id="sales_order_details" action="/sales/new_blank_order_lines" method="post">
<input type="text" id="customer" />
<input type="submit" name="blank_order" id="blank_order" value="Continue">
</form>

My Controller for second form
function new_blank_order_lines()
  {
     $data = array(
    'customer' =>$this->input->post('customer')
       );
      $this->load->view('sales/new_blank_order_lines',$data);
  }

and my view where I want to display data
<?php echo "--".$customer."--"; ?>

The output of the above is that the variable $customer is empty.
Any ideas would be appreciated.
Thanks and Regards.
Answer: It is empty because you have not given name parameter to customer input field in view file.
Write html as below
<input type="text" id="customer" name="customer" />

Comment: perfect answer! +1 :) Made my day!!!
Answer: your are missing name attr there for your input..
<input type="text" id="customer" name="customer"/>
                            //----^^^^^^^----- here

the value is then posted with the name you provided to the controller


JavaScript triangle code?

Question: I am very new to programming, so this might be a simple solution that I simply don't know. I have been trying to write a code that takes a specific number, for example "10", and returns a pyramid where the base has the number of asterisks matched by the value you enter. We are supposed to use this in our code:
function makeLine(length) {
  var line = "";
  for (var j = 1; j <= length; j++) {
    line += "* "
  }
  return line + "\n";
}

For example:
image of triangle where the base is matched by the number entered by the programmer
My code so far looks like this. I know it's completely wrong because I am not at all getting the required results. What am I doing wrong??
function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
    function makeTriangle(length) {
        var line = "";
        for (var j = 1; j <= length; j--) {
            line += "* ";
        }
    }
}
console.log(makeTriangle(8));

Comment: I think that, you're supposed to use the method makeLine that was given to you, meaning that anything you add to your program shoud not modify it. It seems you added some code to it, which is probably not what was expected. Try using the function for what it is, a "function", or a tool, that can be called to serve its purpose from other parts of the program. This function has one and only one responsibility which is to return a string representing a line, try to think of the general algorithm that would make non intrusive use of this responsibility to reach the final objective.
Comment: think of the steps *you* would go through to do this. a general rule of thumb is: if you can work it out on paper, then you can turn the steps you used to work it out on paper into code that does it automatically.
Answer: You need two for loops: one to keep track of the length, and another one to keep track of the current line you are on.
function makeLine(length) {
  var line = "";
  for (var i = 1; i <= length; i++) {
    for (var j = 1; j <= i; j++) {
      line += "* "
    }
    line += "\n";
  }
  return line
}

Answer: Example implementation if you are on es2015.
function makeLine(length) {
  return Array(length).fill('*').join('');
}

function makePyramid(height) {
  const result = [];
  for (let i = 0; i < height; i + 1) {
    result.push(`${makeLine(i + 1)}\n`);
  }
  return result.join('');
}

//*
//**
//***
//****
console.log(makePyramid(4));

Answer: I had this question on a course I was taking and solved it like this:

    function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
}

    function buildTriangle(height) {
    var triangle = "";
    for (var i = 1; i <= height; i++) {
        // call makeline function
        triangle += makeLine(i);
    }
    return triangle;
}

    console.log(buildTriangle(10));
Answer: let newElem = document.createElement("span");
for (let i = 0; i <= string.length; i++) {
for (let j = 0; j < i; j++) {
    newElem[j] = document.createElement("span");
    newElem[j].setAttribute("class", "display");enter code here
    newElem[j].innerHTML = string[j]
    document.body.appendChild(newElem[j])
    console.log(string[j]);
}
    document.write("
")

}
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

JavaScript triangle code?


Can I see what my active bounties are while doing an expedition?

Question: I picked up some bounties while in the town, and then started an expedition. I couldn't remember exactly what the bounties were I picked up. I opened both the map and the field guide, but didn't see them anywhere.
Is there anywhere in the UI while out on an expedition that I can see my active bounties, or do I need to go back to town / remember what they are?
Answer: Sure is! On PS4, the path is:
Options
<code>-> Info

   -> Resource Center

      -> Bounties
</code>
(I assume XBox has something approximately equivalent)
Comment: Yep, it's in the same place on Xbox. Thanks for the help!


Quicksort - which sub-part should be sorted first?

Question: I am reading some text which claims this regarding the ordering of the two recursive Quicksort calls:

... it is important to call the smaller subproblem first, this in conjunction with tail recursion ensures that the stack depth is log n.

I am not at all sure what that means, why should I call Quicksort on the smaller subarray first?
Comment: "why should I call Quicksort on the smaller subarray first?" - because  "in conjunction with tail recursion  ensures that the stack depth is log n"
Comment: Where did you read this from?
Answer: Look at quicksort as an implicit binary tree. The pivot is the root, and the left and right subtrees are the partitions you create.
Now consider doing a depth first search of this tree. The recursive calls actually correspond to doing a depth first search on the implicit tree described above. Also assume that the tree always has the smaller sub-tree as the left child, so the suggestion is in fact to do a pre-order on this tree.
Now suppose you implement the preorder using a stack, where you push only the left child (but keep the parent on the stack) and when the time comes to push the right child (say you maintained a state where you knew whether a node has its left child explored or not), you replace the top of stack, instead of pushing the right child (this corresponds to the tail recursion part).
The maximum stack depth is the maximum 'left depth': i.e. if you mark each edge going to a left child as 1, and going to a right child as 0, then you are looking at the path with maximum sum of edges (basically you don't count the right edges).
Now since the left sub-tree has no more than half the elements, each time you go left (i.e. traverse and edge marked 1), you are reducing the number of nodes left to explore by at least half.
Thus the maximum number of edges marked 1 that you see, is no more than log n.
Thus the stack usage is no more than log n, if you always pick the smaller partition, and use tail recursion.
Comment: Because sadly these days many people on SO have a fetish for closing questions that are completely reasonable, interesting, and have high-quality answers. FWIW, this is a great answer -- don't be discouraged.
Comment: Why has the question been closed?
Comment: @j_random_hacker: Hey thanks! Not to worry, I used to be a regular here, but got my account deleted(huge time sink!), but do contribute sometimes under various non-registered accounts(afraid to register :-)). I am actually immune to such fetish closings. Only wanted to know if the scope of SO has changed drastically...
Comment: @j_random_hacker True that. Why'd you think when you can simply reap points by doing some inept guy's job while he's off having coffee with a coworker.
Answer: Some languages have tail recursion. This means that if you write f(x) { ... ... .. ... .. g(x)} then the final call, to g(x), isn't implemented with a function call at all, but with a jump, so that the final call does not use any stack space.
Quicksort splits the data to be sorted into two sections. If you always handle the shorter section first, then each call that consumes stack space has a section of data to sort that is at most half the size of the recursive call that called it. So if you start off with 10 elements to sort, the stack at its deepest will have a call sorting those 10 elements, and then a call sorting at most 5 elements, and then a call sorting at most 2 elements, and then a call sorting at most 1 element - and then, for 10 elements, the stack cannot go any deeper - the stack size is limited by the log of the data size.
If you didn't worry about this, you could end up with the stack holding a call sorting 10 elements, and then a call sorting 9 elements, and then a call sorting 8 elements, and so on, so that the stack was as deep as the number of elements to be sorted. But this can't happen with tail recursion if you sort the short sections first, because although you can split 10 elements into 1 element and 9 elements, the call sorting 9 elements is done last of all and implemented as a jump, which doesn't use any more stack space - it reuses the stack space previously used by its caller, which was just about to return anyway.
Comment: What's a "jump"? Do you mean a goto?
Answer: Ideally, the list is partitions into two roughly similar size sublists.  It doesn't matter much which sublist you work on first.
But if on a bad day the list partitions in the most lopsided way possible, a sublist of two or three items, maybe four, and a sublist nearly as long as the original.  This could be due to bad choices of partition value or wickedly contrived data.  Imagine what would happen if you worked on the bigger sublist first.  The first invocation of Quicksort is holding the pointers/indices for the short list in its stack frame while recursively calling quicksort for the long list. This too partitions badly into a very short list and a long one, and we do the longer sublist first, repeat...
Ultimately, on the baddest of bad days with the wickedest of wicked data, we'll have stack frames built up in number proportional to the original list length.  This is quicksort's worst case behavior, O(n) depth of recursive calls.  (Note we are talking of quicksort's depth of recursion, not performance.)
Doing the shorter sublist first gets rid of it fairly quickly. We still process a larger number of tiny lists, in proportion to the original list length, but now each one is taken care of by a shallow one or two recursive calls.   We still make O(n) calls (performance) but each is depth O(1).
Comment: The wildly unbalanced partition is *also* quicksort's worst performance.
Answer: Surprisingly, this turns out to be important even when quicksort is not confronted with wildly  unbalanced partitions, and even when introsort is actually being used.
The problem arises (in C++) when the values in the container being sorted are really big. By this, I don't mean that they point to really big objects, but that they are themselves really big. In that case, some (possibly many) compilers will make the recursive stack frame quite big, too, because it needs at least one temporary value in order to do a swap. Swap is called inside of partition, which is not itself recursive, so you would think that the quicksort recursive driver would not require the monster stack-frame; unfortunately, partition usually ends up being inlined because it's nice and short, and not called from anywhere else.
Normally the difference between 20 and 40 stack frames is negligible, but if the values weigh in at, say, 8kb, then the difference between 20 and 40 stack frames could mean the difference between working and stack overflow, if stacks have been reduced in size to allow for many threads.
If you use the "always recurse into the smaller partition" algorithm, the stack cannot every exceed log2 N frames, where N is the number of elements in the vector. Furthermore, N cannot exceed the amount of memory available divided by the size of an element. So on a 32-bit machine, the there could only be 219 8kb elements in a vector, and the quicksort call depth could not exceed 19.
In short, writing quicksort correctly makes its stack usage predictable (as long as you can predict the size of a stack frame). Not bothering with the optimization (to save a single comparison!) can easily cause the stack depth to double even in non-pathological cases, and in pathological cases it can get a lot worse.
Comment: AFAICT what the OP wants to know is *why* "the stack cannot every exceed log_2 N frames" if you always recurse into the smaller partition. The fact that this is a good thing, especially when the objects are large, isn't in dispute!
Comment: @j_random_hacker, you're probably right about the OP, and I should have summarised better the reason. However, that there is no dispute is incorrect; the only reason I know about this problem is that it happened because the standard introsort implementation, following the original introsort paper, fails to optimize for stack depth, presumably because of the cost of the one extra comparison per loop.


PHP - Get All values from object without knowing properties

Question: I'm having an issue with displaying object properties.
normally you would call them using :
$obj["name"]

but what if you did not know the properties e.g "name"
for an array , you can simply call $arr[0] , $arr[1] etc...
But if i have this object (print_r):
stdClass Object ( [id] => 1 [Name] => george  [Number] => 437439742 [Email] => email@example.com)

stdClass Object ( [id] => 2 [Name] => tom  [Number] => 4343554643 [Email] => email@example.com)

how can i use a foreach to display all the values e.g : 1 , george , 437...
-Without knowing the name of the properties -> NOT $o["id"];
foreach($object as $o)
{
  echo $o[i];    // doesn't work on objects
}

I tried converting it to arrays , but it will be an array of the objects so i can;t get the inside info.
//$array = array ($object);

Comment: It sounds like you're looking for [`get_object_vars`](http://php.net/manual/en/function.get-object-vars.php).
Answer: You have a couple of options. One is the get_object_vars() function, and another is to cast the object to an array.
foreach (get_object_vars($object) as $var => $val) {
    // ...
}

or
foreach ((array) $object as $var => $val) {
    // ...
}

Answer: You can use:
$array = get_object_vars($obj);

Comment: Please try to add more description to your answer.


Change value of css in components

Question: I am new to React/Javascript and can't really solve this issue for a day.
I have object with names of players.
let players = {'Amber', 'Thomas', 'Trump', 'Michael', 'Someone'};

Basically players is the input function where users type their names and I store them here.
And I have a css for displaying them as a grid.
const styles = {
   section: {
     display: 'grid',
     gridGap: '5px',
     boxSizing: 'border-box',
     borderColor: 'black',
     padding: '5px',
     gridTemplateColumns: 'repeat(1, 1fr)',
}

I would like to change the value in  'repeat(value, 1fr)' when the length of players increases.
In volleyball, there are six members in each team, so:
style = {list.length > 6 ? changeValueMoreSix : changeValueSixOrLess

I would like to separate them each six in case there are more players.
E.g.
Case1: Just 5 player, it should display:
Player1
Player2
Player3
Player4
Player5

Case 2: 11 Players:
Player1   Player7
Player2.  Player8
Player3   Player9
Player4   Player10
Player5   Player11
Player6

Basic idea is to create a column if it exceeds more than 6, 12, 18, etc, or column = player.length / 6
Answer: You could create css classes for each required number (6, 12 etc):
.lessThanSix {
    gridTemplateColumns: 'repeat(1, 1fr)',
}

.moreThanSix {
    gridTemplateColumns: 'repeat(2, 1fr)',
}

And in js file conditionally change class of component, for example:
let currentClass = "";
list.length > 6 ? currentClass = moreThanSix : currentClass = lessThanSix;

Finally you'll get as more classes as many cases you have. You can change classes in switch/case block.
Comment: Thank you for your reply. However, I am sure there must be a way to change the 'repeat(value, 1fr)' where value is 1, 2, or anything based on the length of the list.
I don't think I need to create six css classes if length of the list is 6*6.

Can I set the value of value in 'repeat(value, 1fr)' based on the length of list?
Answer: In case you want to calculate value based on length of the list in repeat(**value**, 1fr), you can use CSS values, attached in inline style of wrapper of list elements:
Calculate column amount (based on list length and 6 divider;
const columnAmount = Math.ceil(list.length / 6);

Then, use this value in your template:

And update your CSS:
const styles = {
   section: {
     display: 'grid',
     gridGap: '5px',
     boxSizing: 'border-box',
     borderColor: 'black',
     padding: '5px',
     gridTemplateColumns: 'repeat(var(--column-amount, 1), 1fr)',
}

where --column-amount in var(--column-amount, 1) is dynamic CSS value, 1 is callback value.
Comment: @MarkEzberg Using CSS variables with JS: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties#values_in_javascript and CSS var itself: https://developer.mozilla.org/en-US/docs/Web/CSS/var
Comment: Hey man, thank you a lot. It is what I have been looking for!
Comment: hey, would you please give me the source of documentation where I can read more about this, please?

Change value of css in components


Java Fest consuming console output

Question: I'm trying out testing Java Swing with Fest. My problem is that closing the frame fixture ( frameFixture.close() ) as a part of @After tearDown() method of my tests somehow blocks/hides/consumes (don't know which one) the console output from the test classes runner.
( That is printout derived from Result result = JUnitCore.runClasses(testClasses) ).
Any idea what might be the cause? Below are the relevant setUp() and tearDown() methods,
  as well as piece of code running all tests and printing out the aggregate results, or what gets mysteriously suppressed by (presumably) Fest.
setUp() and tearDown() of test class:
    @Before
    public void setUp() {
        this.frameFixture = new FrameFixture( new DesktopView() ) ;
        this.frameFixture.show() ;
    }

    @After
    public void tearDown() {
        this.frameFixture.close() ;
        this.frameFixture = null ;
    }

Tests summary from the tests classes runner (that gets suppressed when I call frameFixture.close()) :
    Result result = JUnitCore.runClasses(testClasses) ;

    for( Failure failure : result.getFailures() ) {
        System.out.println( failure.toString() ) ;
    }

    System.out.println("Tests called: " + result.getRunCount() ) ;
    System.out.println("Tests failed: " + result.getFailureCount() ) ;
    System.out.println("Execution time: " + result.getRunTime() + " ms" ) ;
    System.out.println( "All tests passed: " + result.wasSuccessful() ) ;

Answer: I don't have enough reputation score to add a comment, so I'll add my notes to the answer.
It could that the System.exit() is called when your main frame gets closed, for example, if it's been created with JFrame.EXIT_ON_CLOSE option. If this is the case, then check how to handle System.exit() with FEST.
Comment: This does appear to be the case. I'll need to test further, but indeed adding a second test didn't get it executed. Silly I didn't think of that before.

Java Fest consuming console output


Python: Binary to Base64

Question: So I have a binary number, 001000 i.e. 8.
If I do base64.b64encode(001000) I get an error.
So I do base64.b64encode(b'001000') and I get b'MDAxMDAw'.
But I need to get the base64 character in the index of the original number, 001000 or 8, which in this case would be 'I'. Or if the number was 011100 (28), then the corresponding character on the base64 table with a value of 28 would be: 'd'.
For example: here are some values in the b64 table
0 == A, 1 == B, 2 == C, 3 == D, 4 == E
So what I want to do is: First, convert the binary number to decimal (000011 == 3) . Then take that number and compare it to the base64 table, and you will see that 3 or 000011, is equal to 'D'.
Does anyone know how I could do this?
Comment: you tried `0b001000` ?
Comment: if you do `base64.b64encode(b'0b001000')` you get `b'MGIwMDEwMDA='`
Comment: or if you do `base64.b64encode(0b001000)` you get an error
Answer: If I understand correctly, the following should do what you want:
base64.b64encode(bytes([0b001000]))

Explanation:

0b001000: the 0b notation returns the integer 8
[0b001000]: creates an array of length 1
bytes([0b001000]): converts an iterable to bytes
b64encode(bytes([0b001000])): converts these bytes to base64 encoding
Comment: that returned `b'CA=='` for me, but what i was hoping for was `'I'`
Comment: if you look at a base64 table you will see the value column and character column and since the value of 'I' is 8 when i do `001000` i expected an 'I', thanks anyway
Comment: `CA==` is the base64 encoding of the byte `0001000`, right? Where does the `'I'` come from?
Comment: well,  `001000` in decimal is `8` and in the base64 table 'I' in base64  is equal to 8 in decimal right?
Comment: sorry if that is confusing
Comment: You are completely right. Now I am confused as well :-D I hope the `0b` notation helps you a little, at least.
Comment: The total input is treated as a single bitstream, then broken into blocks of 6 bits each. If the number of bits isn't a multiple of 6, additional 0 bits are appended to the stream. Further, the output is padded with `=` to make the length a multiple of 4.

Python: Binary to Base64


Google Plugin for Eclipse 4.2 does not show up after installing

Question: I am running on Mac OS X 10.5.8.
The problem is that the "g" toolbar icon does not show up after I finish installing GPE 4.2 and GWT SDK 2.4 plugin. When I go to "preferences", there should be a google tab, but that does not show up either.
There was no problems with the installation. If I go to "Install new software..."->"already installed...", both GPE 4.2 and GWT SDK 2.4 are listed.
Can anyone kindly help me resolve this issue?
Comment: Have you glanced at the **Customize Perspective** dialog (**Window** --> **Customize Perspective** in the main menu)? Check out the **Tool Bar Visibility** tab: is the **Google** tree item there, with **GDTPulldown** item as its child?
Comment: I misread your question and thought you were referring to the blue **G** in the toolbar when I made the comment above. Still, its presence is also an indicator of correct installation.
Comment: The Google tree item does not exist in the Tool Bar Visibility tab. I tried uninstalling and reinstalling the plugins to no avail. The Eclipse download I used is Eclipse Classic 4.2 Mac OS X 32bit.
Comment: Hmm ... I usually start with the **Eclipse IDE for Java Developers** package and have never had an issue. Maybe a GPE dependency is missing from the Classic version and is not properly resolved during the installation.
Answer: Mac was 64bit. Needed to install 64bit version of Eclipse.


Multiple highcharts on the same page

Question: I'm trying to load multiple charts on a page by including HighCharts on top of the page. Now when I'm try to load the page I get the following error,
Here's the stack trace.
Uncaught TypeError: undefined is not a function highcharts.src.jsx:6707.
My input JSON is well formed, I tried copy pasting the same JSON I'm passing to HighCharts on jsfiddle and I get the same error
highcharts.js
    http://jsfiddle.net/arjunbadarinath/GDBUL/1

Can you please tell me why I'm seeing this error?
Answer: Highcharts requires jQuery to be loaded prior to Highcharts.
Once you do that it works just fine.  In your fiddle, select jQuery from the drop-down on the top left where it currently says No-Library (pure JS) and run the fiddle, voila, it works! ;)
I recommend to make use of a jQuery CDN (such as Google) to load jQuery to take advantage of browser cached jQuery.  Do that like so:

Comment: I moved jquery include above Highcharts and it worked, thanks for the help!

Multiple highcharts on the same page


What could be the working of the statement with conditional operator?

Question: #include<stdio.h>
void main()

{

        int x=2,y=0;

        int z= (y++) ? y==1 &&x:0;

        printf("%d\n",z);

}

How does the compiler take the statement int z= (y++) ? y==1 &&x:0;
Comment: If you have a book that told you to use `void main()`, get your money back. `int main(void)` is correct.
Answer: in:
int z= (y++) ? y==1 &&x:0;

y is evaluated then incremented. Since the original value is 0, you're getting the "else" part of the ternary so z is 0.
Change to (++y) then you enter the "if" part of the ternary, and since y==1 and x is not 0, z takes the value 1
In that case it's guaranteed that y==1. It works with specified behavior because of the sequence point the ternary expression materializes, so the pre-incrementation has to have been performed.

Sequence points ...
Between the evaluations of the first operand of the conditional ? : operator and whichever of the second and third operands is evaluated

Such subtle and cryptic changes makes that code hardly maintainable. Don't do this at home.


conceptual issue in inheritence property of actionscript-3

Question: say, Child class is inheriting Father class and Father class is inheriting spark TextArea class. now from an mxml file (in FLEX4), i am creating multiple objects of Child class. Father class have few static attributes whose values are set by private methods, calling from constructor. Now the question is: all these static attributes are set every time while Child class objects are being created one by one?
If answer is yes then Is it possible that Father class static attributes are set only once and not depends upon the number of Child class objects creation.
Please provide any suggestion or tips
Thanks in advance.
Comment: You should change "father" to "parent".
Comment: It doesn't sound that you have a lot of variables, so I wouldn't worry. If there are a lot of classes that does not use the static variables I reccomend you to split up the classes. Don't inherit just because you can.
Comment: @Mattias: Thanks but I'm not getting your point. would you pls explain?
Comment: I am not sure what you question or problem is. Please clarify.
Answer: If you are setting static variables from an object's constructor or methods called from the constructor, then yes, they will be set every time. In order to prevent that, just check whether the variable is already set.
public class Foo {

    public static var bar:Object;

    public Foo(value:Object) {
        if (!bar) {
            bar = value;
        }
    }
}

Answer: First decide if those static members are really all that important to store as statics because statics are associated with a Class and not an instance it's usually a signal that you're probably doing something you shouldn't if instances are modifying or reading static members.  You probably should use a factory method if you need to share that information with the instances.  However, if you're sure you should do it then you can use a static initializer block to initialize the members when the class is loaded.  Downside is that block throws an exception it can be hard to track down:
public class SomeObject {
   private const _someStaticMember : String;
   private const _someOtherStaticMember : SomeOtherObject;

   static {
       _someStaticMember = "foobar";
       _someOtherStaticMember = new SomeOtherObject();
   }

}


Inject request scoped bean in servlet filter

Question: Is it possible to inject(CDI) request scoped bean in servlet filter?
My login.xhtml as below -
<h:form>
    <h:inputText id="uname" value="#{login.uname}" />
    <h:inputSecret id="pwd" value="#{login.upwd}" />
     <h:commandButton action="#{loginc.login}" value="Login"  />

</h:form>

On a POST on this page, I need Login bean in my servlet filter but it is always null. My backing bean
@Named("login")
@RequestScoped
public class Login {
    private String uname;//with getters and setters
    private String upwd;
}

Below is how I'm injecting it in my filter -
public class LoginFilter implements Filter {
@Inject
private Login login;
...
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//System.out.println(((Login)request.getAttribute("login")).toString()); **Not Working**
System.out.println("login ->" + login);//not working
}

Now working in the sense, the container injects a reference but all the fields are empty. I am expecting posted form data values i.e, values for the properties mentioned the the backing bean.
If its not possible, then is there any other way around? Intention is avoid session creation by using other types of scoped beans.
Update-
I did some changes as suggested in the comment section but still the values for the bean in question are null
public class LoginFilter implements Filter {

@Inject
private BeanManager beanManager;

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    findBean("login", req);
    chain.doFilter(req, res);
}

public void findBean(String beanName, ServletRequest req){
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println(facesContext == null);//always true
    System.out.println(beanManager==null);//is not null

    Bean bean = beanManager.getBeans(beanName).iterator().next();
    CreationalContext ctx = beanManager.createCreationalContext(bean);
    Login loginBean = (Login) beanManager.getReference(bean, bean.getBeanClass(),ctx);
    System.out.println(loginBean);//prints null as value for properties for post request also.
}

What I thought of doing - I had a Login request and LoginController view scoped bean. This is how I started initially. So, for username and password Login and loginController.login on sign in action. This worked as expected. I was injecting Login into LoginController all field/s values were there.
My requirement was to manage user sessions and implement remember me functionality too. So, to do that I started by creating cookie/s in the loginController and it worked.
Here, with the above setup - first I wanted to avoid unnecessary session creation. I wanted request to land on the login page but without a session. This requirement is the driving force behind all this filter/s and related re/work. I resorted to <c:view transient="true">. This I'm not sure, worked or not. Now, in one of your answers you wrote that we should not put cookie and other authorization and authentication related stuff inside backing beans.
So, I said to my myself - Okay, I'm not following good practice in my code and why not write a filter and if I could intercept the Login bean there I should be able to execute my authentication/ authorization and cookie related stuff there itself. This way, I can avoid hitting the view scoped loginController and no unwanted session. I can control the session programmatically. This never worked and so that's why I asked this question.
In one of your answers, you wrote - session creation is cheap - but I still wanted to avoid it when the login page of my application is accessed.
Now, what I have finally done and working is - my login form uses plain html input fields and then on login action I intercept these field value in old servlet way. For a valid attempt - I create a session programmatically and redirect.
Please, let me know if I can improve.
Comment: It is possible, tested in Wildfly 8.2. What container are you using? Do yo have a `beans.xml`? Is `Login` injection working outside of your filter?
Comment: @acm Using `Payara` latest. Yes, I have `beans.xml` in my project. And, yes I am able to inject and use `Login` bean otherwise.
Comment: I tested it using `payara-126.96.36.199`. I added a filter and injected a request scoped bean into it and it is working as expected. Could you provide more clues on how to actually reproduce the described behaviour? A [MCVE] would help a lot.
Comment: @acm Please see the update.
Comment: That's exactly what I've tried. Have you tried it in a clean project containing only your `Login` bean and your `LoginFilter`?
Comment: @acm NO. I will give it a try. Meanwhile, is it possible for you post what works for you as an answer.
Comment: @Tirath does your filter have any bean defining annotations, e.g. `@RequestScoped`?  If you could also post your `beans.xml` content.
Comment: @JohnAment The Filter is annotated only with the `@WebFilter` annotation and `beans.xml` is empty. It doesn't have any content.
Comment: Ok.. I added payara as a tag to help get attention to this.  I believe this should work though, I would recommend using a `beans.xml` from CDI 1.1 and adding a bean defining annotation to your filter, e.g. `@RequestScoped`.  Please give us some input if that worked, you already received one recommendation.
Comment: The bean you're getting has null fields because using basic injection means you're getting a brand new instance of the bean. What you need here is a contextual instance i.e. a specific instance of that bean that's already active within your context. Start with [this answer](http://stackoverflow.com/a/15685982/1530938) to get a specific instance. The risk you run is that you *may* get more than one bean, depending on your circumstances
Comment: This construct will never work. Filters run before servlets, including the JSF servlet. The JSF servlet is the one responsible for setting the submitted input values as bean properties. Before you call chain.doFilter(), JSF servlet hasn't run yet and thus the bean remains empty. If you inspect the bean *after* the chain.doFilter() line, you'll see the properties. However, this strongly indicates a http://xyproblem.info. If you elaborate the concrete problem for which you most likely incorrectly thought that this all would be the correct solution, then we may able to propose the right solution.
Comment: @BalusC I have added an update.
Answer: Try to use Spring Interceptors instead of Filters.
The example you can find HERE


Let [a, b] be divided into n equal parts, and let y1 be the value of f(x) at the midpoint of the ith subinvterval....

Question: Let $[a, b]$ be divided into n equal parts, and let $y_1$ be the value of $f(x)$ at the midpoint of the ith subinvterval. The arithmetic mean of $y_1, \dots, y_n$ is
$A_n = (y_1 + \dots + y_n)/n$
show that $u = \lim_{n \to \infty} A_n$. where
\begin{equation}
u = \frac{1}{b-a} \int_a^b f(x) \, dx.
\end{equation}
I know the arithmetic mean is the same thing as the avergae of the integral (in this case $u$) and I know how to prove the arithmetic mean but I don't know what the question wants me to do? do I have to show that the arithmetic mean of $A_n$ is equal to $u$? but I don't know what the function is?
Comment: What you need to know about the function $f$ is that it is Riemann integrable. Then contemplate how the $A_n$ relate to Riemann sums and how these behave - *by definition* of Riemann integrable - as $n\to\infty$.
Answer: Let's assume that $f$ is Riemann integrable.
Then write
$\sum_{i=1}^{n}f(x_i^{*})\Delta x_{i}=\sum_{i=1}^n y_{i}\left ( \frac{b-a}{n} \right )=(b-a)A_{n}$,
where we have used the evident partition obtained from the data in the exercise.
Now it only remains take the limit as $n\rightarrow \infty $ and use the defnition of the Riemann integral.


Greenhouse wood foundation and frost heave

Question: I'm a novice constructing a 8x12' saltbox style green house made from recycled single pane windows in climate 5 & 4 Marine. It does get freezing here in winter with maybe an inch to three of snow a year.
I plan to half lap treated 6x6's with 2x6 sills leveled on gravel with rebar anchors. Since this is a permit less structure (< 200sqft in my county) I'm concerned about possible frost heave and want to know if this foundation is sufficient for such a structure. Would I need to find my frost depth and put in say, 4 or 6 sonotubes/pads to anchor my 6x6's?
Answer: The short answer is: No, don't worry about it.
Your building is basically a yard barn and no building code I have seen requires frost footings for a yard barn.
I live in a Zone 5 with plenty of freezing and snow and separate buildings like garages are only required to have a 12" slab on grade footing. Yard barns can be place right on the grass if you want. Although, most people scape off the topsoil and place gravel to level the barn and provide some moisture reduction.
I don't think your building is large enough to be affected by frost heave in any appreciable way.
All that said, if you are an ovebuilder and want this to be permanent then a deep sonotube footing in each corner would certainly keep it from going anywhere. Anchoring it to these footings would also give you some wind stability.
Good luck with your project!
Comment: Not really. Small buildings (and 10x16 would still be pretty small) that essentially float on the ground are free to move up and down with the freeze and thaw of the soil. I would still remove the topsoil and stabilize the area with compacted sand and then pea-stone or crushed stone. The only other concern is mounting your panes of glass so they have a little room to move, expand and contract. If the building does flex slightly you don't want your glass held so rigidly it can't move without cracking.
Comment: Would scaling to 10x12 or even 10x16 make this a concern in your opinion?


setup local mail on ubuntu 12.04 not to the outside world just internally and use the mail command

Question: I would like simple local mail setup for Ubuntu 12.04. I would like to use the mail command. I will install the other clients at a later date, I just want to get this default working. I found a post that walked through installing
apt-get install exim4-daemon-light mailutils
dpkg-reconfigure exim4-config

which brought up a mail server setup I stepped through it and ran a test mail but everytime I check I get

no mail for ubuntuuser1

The setup options I chose were:

local delivery only; not on a network
fqdn  ubuntu.dev.local
ip addresses to listen for incoming smtp  127.0.0.1 ; ::1
other destinations  ubuntu.dev.local
Keep number of DNS-queries minimal no
Delivery method for local mail: mbox format in /var/mail/

I tested my hostname
user1@ubuntu:~# hostname
ubuntu
user1@ubuntu:~# hostname -f
ubuntu.dev.local

What am I missing?
Answer: I had to edit /etc/hosts and add my hostname:
127.0.0.1    ubuntu.dev.local