Qt can't access some .dll files

Question: I am working on a plugin for some application, and I am using libtiff. The filter is working just fine, but there is a problem. There are some .dll files that have to be included in compile path. When I add those .dlls in \QtSDK\Desktop\Qt\4.8.1\mingw\bin the plugin is working fine, but when i delete one or more of those .dlls, plugin is not recognised by the application. Those .dll are not included in the Qt SDK by default.
Is there any way I can include those .dll in my plugin and add a path to them without copying them to the Qt SDK bin folder.
Comment: Not where, what. The names :-). Your MinGW/bin is in your search path. No wonder that they are found there. You should be able to put them in the same folder in which your program is started.
Comment: The location of the source files is irrelevant. Try putting them in the same folder where the binary lies.
Comment: In a folder where plugin header and source files are
Comment: My fault :).
They should be located in the same folder as plugin's source file is. Is there a posibility to reach them without copying them in mingw/bin?
Comment: I did that and same thing is happening.
Comment: Then I am out of options. Things like that are extremely hard to debug 'remotely'. Position dependent dlls are strange. Only other example of something like that, which I know, are the Qt plugins.
Comment: I know this is a bit late, but QT is not Qt. QT refers to Apple QuickTime and not the Nokia Qt framework. I edited the question to replace all QT with Qt.
Answer: Usually I add my plugins to my application directory and add this line of code to main() in main.cpp like so:
qApp->addLibraryPath(QString("."));

Image plugins go in imageformats and SQL drivers (ODBC) go in sqldrivers. You can make the library path anything you want relative to your application root directory. I like to keep things simple and just reference the root directory.

Qt can't access some .dll files


Copy & paste inadvertently triggers Worksheet_Change sub

Question: I am having problems with a "Worksheet_Change" sub that copies and pastes the whole row into a second worksheet ("Completed") when the column "P" takes on the value "x". It reads like this:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
    Application.EnableEvents = False
    'If Cell that is edited is in column P and the value is x then
    If Target.Column = 16 And Target.Value = "x" Then
        'Define last row on completed worksheet to know where to place the row of data
        LrowCompleted = Sheets("Completed").Cells(Rows.Count, "A").End(xlUp).Row
        'Copy and paste data
        Range("A" & Target.Row & ":P" & Target.Row).Copy Sheets("Completed").Range("A" & LrowCompleted + 1)
        'Delete Row from Project List
        Range("A" & Target.Row & ":P" & Target.Row).Delete xlShiftUp
    End If
    Application.EnableEvents = True
End Sub

The sub itself works fine but if I copy and paste anywhere in the worksheet, the sub is activated and the row into which I paste is send to my "Completed" sheet.
I have played around with the "if-clause" without any luck so far. E.g.:
    If Not Target.Column = 16 And Target.Value = "x" Is Nothing Then

I fear I am missing the obvious and I am grateful for any help.
Thanks and regards
PMHD
Comment: You're dealing with a situation where Target is more than a single cell.  Maybe bandaid it with `if target.cont > 1 then exit sub` in the beginning of the sub or disclose what you want to happen when target is more than a single cell.'
Comment: Great call, @Jeeped! This led me to the solution. I ended up skipping the "Exit Sub" part so I could still activate the sub with the "x" in column 16. Thank you.
Answer: Thanks, Jeeped.
The problem arose due to Target referring to multiple cells. It was fixed by excluding cases where Target.Count > 1.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Application.EnableEvents = False
'Exclude all cases where more than one cell is Target
If Target.Count > 1 Then

'If Cell that is edited is in column P and the value is x then
ElseIf Target.Column = 16 And Target.Value = "x" Then
    'Define last row on completed worksheet to know where to place the row of data
    LrowCompleted = Sheets("Completed").Cells(Rows.Count, "A").End(xlUp).Row
    'Copy and paste data
    Range("A" & Target.Row & ":P" & Target.Row).Copy Sheets("Completed").Range("A" & LrowCompleted + 1)
    'Delete Row from Project List
    Range("A" & Target.Row & ":P" & Target.Row).Delete xlShiftUp
End If
Application.EnableEvents = True
End Sub

Answer: If you are concerned with muliple targets, deal with them; don't discard them.
Private Sub Worksheet_Change(ByVal Target As Range)

  If not intersect(target, range("p:p")) is nothing then
        on error goto meh
        Application.EnableEvents = False
        dim t as range, lrc as long
        lrc = workSheets("Completed").Cells(Rows.Count, "A").End(xlUp).Row + 1
        for each t in intersect(target, range("p:p"))
            if lcase(t.Value2) = "x" Then
                intersect(columns("A:P"), t.rows(t.row)).Copy _
                    destination:=workSheets("Completed").cells(lrc , "A")
                lrc = lrc+1
                'Delete Row from Project List
                intersect(columns("A:P"), t.rows(t.row)).Delete xlShiftUp
             end if
        next t
    End if

meh:
    Application.EnableEvents = true

end sub


Which search range for determining SVM optimal C and gamma parameters?

Question: I am using SVM for classification and I am trying to determine the optimal parameters for linear and RBF kernels. For the linear kernel I use cross-validated parameter selection to determine C and for the RBF kernel I use grid search to determine C and gamma.
I have 20 (numeric) features and 70 training examples that should be classified into 7 classes.
Which search range should I use for determining the optimal values for the C and gamma parameters?
Answer: Check out A practical guide to SVM Classification for some pointers, particularly page 5.

We recommend a "grid-search" on $C$ and $\gamma$ using cross-validation. Various pairs of $(C,\gamma)$ values are tried and the one with the best cross-validation accuracy is
  picked. We found that trying exponentially growing sequences of $C$ and $\gamma$ is a
  practical method to identify good parameters (for example, $C = 2^{-5},2^{-3},\ldots,2^{15};\gamma = 2^{-15},2^{-13},\ldots,2^{3}$).

Remember to normalize your data first and if you can, gather more data because from the looks of it, your problem might be heavily underdetermined.
Comment: Should peer testing be done manually? there is not a library to achieve it?
Answer: Check out section 2.3.2 of this paper by Chapelle and Zien. They have a nice heuristic to select a good search range for $\sigma$ of the RBF kernel and $C$ for the SVM. I quote

To determine good values of the remaining free parameters (eg, by CV),
  it is important to search on the right scale. We therefore fix default
  values for $C$ and $\sigma$ that have the right order of magnitude. In
  a $c$-class problem we use the $1/c$ quantile of the pairwise
  distances $D^\rho_{ij}$ of all data-points as a default for $\sigma$.
  The default for $C$ is the inverses of the empirical variance $s^2$ in
  features space, which can be calculated by $s^2 = \frac{1}{n} \sum_i K_{ii} - \frac{1}{n^2}\sum_{i,j} K_{ij}$
   from a $n\times n$ kernel
  matrix $K$.

Afterwards, they use multiples (e.g. $2^k$ for $k\in \{-2,...,2\}$) of the default value as search range in a grid-search using cross-validation. That always worked very well for me.
Of course, we @ciri said, normalizing the data etc. is always a good idea.
Comment: I think there are several equal rbf kernel formulations. One with gamma and another with sigma, i.e. gamma = 1/2sigma^2. Does the gamma in the above heuristic correspond to gamma, sigma or sigma^2? I have found other descriptions of the same heurstic which are for gamma.
Comment: If you check the linked paper, it is $\frac{1}{2\sigma^2}$
Comment: @fabee Should peer testing be done manually? there is not a library to achieve it?


Existence of inverse Laplace transform of $F(1/s)$

Question: I have two questions about inverse Laplace transform.
Given a function $F(s)$, does its inverse Laplace transform always exists?
If it's not, assume $F(s)$ has an inverse Laplace transform, does the inverse Laplace transform of $Q(s) = F(1/s)$ exists?
Answer: You have to have F(s)-->0 as s-->Inf because of how the Laplace transform is defined (integrate f(t) with exp(-st) over all positive t's). As s-->Inf, the exponential factor goes to zero as s --> Inf for all positive t's, so you have to have for any Laplace-transformable f(t) the corresponding transform F(s) --> 0 as s-->Inf. This is a necessary condition, but I'm not sure if sufficient.
This precludes the existence of inverse Laplace transforms of functions such as F(s) = s, sqrt(s) etc.


Kickstart installed nothing?

Question: I followed the install directions by deleting all but the /sites folder, copied the files into the drupal dir, deleted the cache but nothing changed except and notice that drupal core needed updating to 7.24, which i did.  What am i missing here?
Answer: By considering that you have gone through pre-installation checklist of Commerce Kickstart, following are the steps to install commerce kickstart :

Download Commerce Kickstart.
Extract the Files into root directory.
Installation Screen, welcome.
Requirements Problem Screen.
Setting up the database configuration.
Installation running through.
Site Configuration.
Configure Store Content.
Importing Products.

Kickstart installed nothing?


How to hide nodes in a VIEW where the user is not referenced?

Question: This is a follow-up to How to show nodes where the user is (not) in the reference field with Views?
I have a node with multiple user references and need a node VIEW that hides all nodes where the current user is NOT referenced. So, if the current user is not referenced, the node should not show up. The problem I just can't solve is that the node still shows up when other user are referenced (using exclude, it only excludes the current user from display, but it still displays the nodes for each other user that is referenced). I have unsuccessfully tried views_distinct module and VIEWs own "distinct" query settings.
If the user is referenced, the node should show up (this works from the above mentioned question)
CLARIFICATION:
Basically, it's for a simple pay-per-view site. I need 1 (or 2, whatever works) VIEWS that shows the videos where the user has purchased access to (where he is referenced) and where the user has not purchased access to (where he is not referenced). After 48 hours the references are removed using rules scheduler.
Ideally in one VIEW, when the user is referenced, the link should be "watch", where the user is not referenced, it should read "buy" using VIEWS conditional and rules link. But two separate VIEWS are also ok.
Right now I have a content view (also tried it with a user view unsuccessfully, but this might be a saner approach?!). All of that works well with the notable exception of showing the nodes with multiple user references.
UPDATE:
Added a screenshot using the views argument substitutions.
UPDATE 2:
I tried it with regExpressions and views substitutions. The UID of the currently logged in user is passed as !1, but what is the correct regEx syntax to show only the nodes, where this user is not referenced?
This does not work as value of the operator on the useraccess field filter:
<code>^***!1***
</code>
SOLUTION
Oh boy, this was a ride. Finally figured out a solution. Posting it if someone needs it. Basically, I added the username in the url and do a contains text comparison using views conditional. ID from the logged in user did not work as contains also shows user ID "13" or "14" when the user "1" is logged in. Simply excluding did not work in those cases where other users are referenced as well.

Comment: You need to elaborate on your View setup and output a bit more. Are you showing a row for each user referenced for a node, hence you have the same node showing up multiple times with a different user?
Answer: You have to add a filter under Filter Criteria Section which is, if a 'yourfield-name'is 'is not empty (NOT NULL)' from the select list.
This filter only shows results which have the value for this particular field. Otherwise it will not show you any result for that node.
I hope it will work.
Comment: Not saying you're wrong but right now, I don't think you can get the current user nid to filter that way. If that doesn't work, I'd add a global:null contextual filter or regular user contextual filter with provide default "logged in user". Then use the module "views arguments substitutes" to feed the users nid into the view filter. Can't test away from laptop so not posting this as an answer.
Comment: @ Niall: Thanks for the hint with views arguments substitutions. This indeed looks very much what I need. But as filter I only can use "is not equal" to the global null (logged in user). I guess I would need something like "does not contain" - the reference field is a multiple value (and not a text) field. I tried adding a custom text field to get the "contains" but this also doesn't seem to do the job
Comment: hey, when you add a filter criteria that I mentioned above, there will we be a option, is not empty (NOT NULL) option.
Comment: @ Pankaj! Thx for your suggestion. I tried this, but I can't get it to work properly. You mean setting a relationship to the user reference field, then adding the currently logged in user as a contextual filter and then add the filter criteria filtering the "user reference field" with (NOT NULL)?
Answer:
Add your user reference field has a Contextual Filter
In your contextual filter settings go to When the filter value is NOT available  and check Provide default value and select User ID from logged in user. Then under "More" tab, check "Exclude".

This might give you only those Articles where current logged in user is NOT referenced
Comment: Thx for the suggestion, xstean. This is how I have implemented the "positive" VIEW, i.e. showing nodes where the user has access to. The issue I am having is that I can't get the neagtive VIEW, i.e. show (only once) the nodes where the user is NOT referenced
Comment: Got it, i edited my answer in step 2. In your contextual filter settings go to "More" tab and check "Exclude"
Comment: Yes, I tried it with this. It does not work when other users are referenced as well. It excludes the current user (and removes one row where the logged in user is referenced), but if there are more user referenced, the node still shows up because for each user referenced one row is displayed.


EChart XAxis Line not rendered?

Question: Trying to draw the XAxis Line in this EChart Stackblitz Demo using Angular and Ngx-Echarts.
This is the line configuration.  It works on the Y Axis, however on the X axis the line is not being rendered.  Any ideas?
          axisLine: {
            lineStyle: {
              color: 'blue',
              width: '4',
            },
          },

Answer: You're missing the show option in the configuration. The docs say it should default to true, but that doesn't appear to be the case in your StackBlitz.
axisLine: {
  show: true,
  lineStyle: {
    color: 'blue',
    width: '4',
  },
},

Here's a forked StackBlitz.
Comment: Ah ... Good catch ... Yes it defaults to true on the Y Axis ...

EChart XAxis Line not rendered?


Using Theme() to output html/javascript in user edit

Question: I have a module that outputs a button to the user edit page. I use the form_user_profile_form_alter to append the button but I want to add html and javascript after it. I saw that the theme() function can do this but my attempt does not add any html. Also I saw that the theme needs two parameters but I do not know what the 1st parameter is supposed to be. I was only following examples.
function myModule_form_user_profile_form_alter(&$form, &$form_state, $form_id) {

  $form['actions']['myButton'] = array(
    '#type' => 'submit',
    '#value' => 'Click Here'
  );
  $form['actions']['myButton']['#submit'][] = 'myModule_callback';

  return $form;
}

Here is my callback function
function artsci_pubmed_biblio_callback($form,$form_state){
  drupal_set_message('Button Clicked');
  return theme('box', '
Item 1

Item 2

Item 3
');
}

Answer: If you just want to add some markup and Javascript, you don't need a submit callback because that's for handling form submissions.
Requirement 1: Add html
Options:

#prefix and/or #suffix form element attributes. (If just simple short html this will do)
#theme to use you custom theme function declared hook_theme and place your markup in your tpl.php file. (If too much markup and want your module/theme to be clean)

Requirement 2: Add javascript
You can use #attached form/form element attribute
In the links, there are example codes that you can follow.


HTML5 Video showing both Source and Flash fallback

Question: I'm experiencing a sudden problem with an embedded HTML5 video on my Drupal site. At first I thought it was a problem with my HTML5 code, but I believe the problem is with the WYSIWYG editor within Drupal.
I have a video in several formats, and want have a Flash fallback for those less fortunate.
Here is my code:
 <video width="480" height="320" controls="controls" poster="poster.png">
    <source src="video.webm" type="video/webm" />
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" />

    <object width="480" height="320"
            data="moxieplayer.swf" type="application/x-shockwave-flash">
       <param name="src" value="moxieplayer.swf" />
       <param name="flashvars" value="url=video.mp4&poster=poster.png" />
       <param name="allowfullscreen" value="true" />
       <param name="allowscriptaccess" value="true" />
    </object>
 </video>

Everything was working as expected. Then I opened the WYSIWYG editor, Disabled rich-text to get to the HTML, and added the "poster" attribute. I clicked save and, ever since, it has been showing TWO videos: the main source and the Flash fallback.
I found that odd so I removed the poster attribute (going back to what I had before), but the problem remained.
I know what the problem is... It became apparent when I viewed the source in the browser. The source is being rendered like this:

<video width="480" height="320" controls="controls" poster="poster.png">

      <source src="video.webm" type="video/webm"></source>

      <source src="video.mp4" type="video/mp4"></source>

      <source src="video.ogv" type="video/ogg"></source>
    </video>

  <object width="480" height="320" data="moxieplayer.swf" type="application/x-shockwave-flash">
     <param name="src" value="moxieplayer.swf" />
     <param name="flashvars" value="url=video.mp4&poster=/" />
    <param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="true" />
 </object>

Notice that in the rendered code, "object" is now outside the video tag. I'm guessing that's the problem. For whatever reason it was fine, then I edited the code to add the poster, and rocking the boat has resulted in this issue. I am in "Full HTML" mode when making my edits.
Unfortunately, disabling WYSISWG isn't an option as my customer needs to use it. This is a bit frustrating as I suspect that may be the issue. I'm using TinyMCE 3.5.10.
Does anyone have any suggestions on how to deal with this problem?
Thank you very much!
Comment: Have you tried manually putting the video code back to how it was before with rich text disabled? @Mołot I think this might be more to do with TinyMCE's HTML correction
Comment: if this has something to do with putting in paragraph tags to mimic a line break, have you tried it without the line break between your last source and the object tag?  drupal could be trying to close the tags to do this for you (eg, the video one) before closing the p tag.
Comment: I agree with @Clive.  Dealing with the WYSIWYG quirks with mangling HTML is a common Drupal problem.
Comment: Thank you for the comments, everyone!
I did try putting the video code back in manually (with rich text disabled). What's odd is that the code is correct when viewed within the Drupal admin. But when it's viewed in a browser, it's changed. So something is happening when the page is loaded.
I did try removing the paragraph tags as well, but Drupal/WYSIWYG insists that they need to be there. :-P
Comment: @mrbranden That's what happens when you have an input filter active. Try set it to FULL HTML or disable it completely ("Disable rich text" link doesn't do this, it just disables the editor temporarily)
Answer: In these kinds of cases, the easy fix would be to add a second text field for "embed code" outside the main wysiwyg area. If you set it to use a new "HTML without linebreaks" text formatter, that'll help eliminate any wackiness on the "Full HTML" default setting.
Protip: use the Better Formats module to stop the user from having to choose a format for this field. That way, they can just paste and forget.
Comment: Hmm... that's interesting. I'm going to try to figure out how to do that and give it a try. Thanks!
Answer: It happened for me too when the "Convert line breaks into HTML" filter is activated in the corresponding text format... although there is absolutely no line break in the video/object tag (?!). But disable the filter fixed the problem.
As I absolutely need this filter to be enabled, I resolved fixing it with a bit of jquery, putting the object back inside the video tag.


In Glenn Gould's "So you want to write a fugue", what's that instrumental part?

Question: I come from learning about fugues and encountered the seemingly famous "So you want to write a fugue" piece by Glenn Gould.
In the middle, there is this instumental part:

To my (rock music listening) ears, this sounds quite like the equivalent of a guitar solo in the middle of a piece, but in classical music.
Is this instrumental part intended to be some sort of joke, in the context of this specific piece? It feels so misplaced there.
Comment: I once listened to a piano transcription of this piece, and I don't remember *anything* sticking out.
Answer: Yes, it's a little joke. After the words "... John Sebastian must have been a very personable guy" the instrumental part starts with the first 4 bars of J S Bach's Brandenburg Concerto No 2.


How can I analyze / compare point-of-sales data between stores with different product offerings?

Question: Let's say I have two stores, A and B, and let's say I have two products in the same department: product 1 and product 2. Let store B have product 2 which store A doesn't have, both stores have product 1. Is there a way to calculate how much cannibalization will take place on product 1 by implementing product 2?
Or, can I do a general approach and use a chi square on their department to see if store B has a higher performance in that department and then if that's the only difference in the products offered, and if they're similarly performing stores that introducing product 2 will increase that departments performance for store A?
If you have some scholarly articles that would be great as well!
Comment: Your question seems to be asking multiple questions in one; and some of them are about inferring causality. Even if products 1 and 2 were in the same category, how do you know one cannibalized the other, as opposed to simple correlation or anticorrelation? Example: fishing rods do not cannibalize icecream sales in July, although they're both seasonal items. Can you ask more specific examples and post some example data?
Comment: Right, sorry my question is vague. I recently started working as a data  analyst for a company and I have tons and tons of POS data that I can analyze and I'm not even sure where to begin. I'm a graduate student right now but haven't had any real world experience. I guess at this point I want ideas on how to analyze this data and what conclusions I'll be able to draw from it.
Comment: (getting offtopic a little, but) **What is the most important business question they want you to answer?** How to increase overall sales? sales in a certain product category? customer segment? store? geo region? How to segment the customer base? How to understand individual customer behavior? customer segments? How to prevent churn of loyal customers? What promotions/discounts/loyalty rewards you should offer to increase sales? Which competitors you lose sales to? If all else fails, plot them some graphs.
Comment: Take a look at e.g. Kaggle Dunnhumby Shopping Challenge and Walmart Store Sales Forecasting challenges.
Comment: Thanks smci, those look really interesting. I already have a lot of graphs showing how items sell at different prices, which items were sold with others, items sold the most, items sold the least. I just want to do something more insightful. The graphs I have are great at showing trends but I'm hoping I can do something to predict what will happen. Like predict how a departments performance will increase if a new item is added to the inventory. But I'm not sure how to do something like that. I can see how often it's sold at stores that currently have it but if it's added to the new store I'd h
Answer: In terms of scholary articles I co-wrote a paper http://www.autobox.com/cms/index.php/news/131-102706-white-paper-on-cannibalization-qtesting-market-hypothesisq-by-john-c-pickett-david-p-reilly-view on this thorny subject which was subsequently printed by the International Business Forecasting Journal. Time series procedures (ARIMA , Transfer Function) were used to examine sales from two Staples stores and to test the hypothesis that sales for the new store cannibalized sales from the old store OR actually improved sales due to enhanced brand awareness.
Comment: @kristofferson You're a grad student. A grad student in what? Beware of suggestions that are software sales pitches, and not in your comfort zone or wheelhouse of expertise. They can take you down the garden of forking paths, so to speak. Consider this a research question and challenge where, as noted, you have to define the question or objective first. Go through it methodically, think rigorously. It's not an insuperable problem...use your education, training and instincts to work down to a solution. And, yes, read, read, read but read the technical literature after HBR case studies.
Comment: Hi Mike, I'm getting my MS in statistics. I'm new to statistics though. I did my undergrad in math so I don't have a ton of experience analyzing data, just the first year of grad school. The stuff I'm using is all locked in so no sales pitches. Just after ideas how to do something really insightful with this data.


Difference between "no statement" and continue

Question: In the code below, please take a look at the part which has the 'continue' statement. What difference would it make if I remove 'continue' statement and I put nothing in the place of it.
int prime_or_not(int x){
    int i;
    if (x == 1 || x == 2){
        return 1;
    }else if (x % 2 == 0){
        return 0;
    }else if (x > 2){
        for (i = 3; i < x; i += 2){
            if (x % i == 0){
                return 0;
                break;
            }else {
                continue;
            }
        }
        return 1;
    }else {
        return 0;
    }
}

Comment: Btw, 1 is *not* a prime number.
Comment: Neither the `break` nor the `continue` are necessary.
Comment: What did you find out by single-stepping in the debugger?
Comment: there are some people who, in the name of "best practices" will **always** have an `else` for every `if`.  In the code you show, the given `else { continue; }`, an empty `else {}`, and no `else` at all would all have the same effect.  additionally, putting a break after the `return` is unreachable code.
Comment: regarding this line: 'for (i = 3; i < x; i += 2){' you could cut the max execution time in half by using: 'for (i = 3; i < (x>>1); i += 2){'
Comment: there is lot of unwanted statements present in your code.
Answer: It would make no difference at all. The continue statement is a jump statement. Basically, it jumps back to your loop not executing the code after it.
Since the continue statement is last executed in your loop it has no effect.
Answer: It makes no difference in your code, but think about something like this:
(Pseudo code):
for(int i = 10; i > -5; i--) {
    if(i == 0)
        continue;

    printf("%d", 10/i);
}

Answer: 'continue' jumps straight to the end of the 'for' or 'while' bracket, "}". In your case, since there is nothing after the continue keyword anyways, it makes no difference.
Just to make it clear, normally, there IS a big difference between 'continue' and no statement. For example,
for (code-condition){
 code-1
 code-2
 continue;
 code-3
 code-4
}

Once the 'continue' line is executed, it jumps straight to the closing "}", ignoring the code-3 and code-4. The next piece of code that gets executed here is code-condition.
Answer: In your case there would be no difference.
However continue will move to the next iteration of the loop immediately and skip any code after it if there is any.
Consider this:
int x;
for(x = 0; x < 100; x++){
    if(x == 50){
        //do something special
        continue;
    }
    //code here is skipped for 50
    //do something different for every other number
}

So the continue statement can be useful in some instances but for your code here it makes absolutely no difference whatsoever(maybe depending on the compiler it will but then it would only increase the size of the end executable adding another jmp instruction, or maybe not since it may unwind the loop fully).
Answer: I would simplify the block
    for (i = 3; i < x; i += 2){
        if (x % i == 0){
            return 0;
            break;
        }else {
            continue;
        }
    }

to
    for (i = 3; i < x; i += 2){
        if (x % i == 0){
            return 0;
        }
    }

The additional lines don't change the behavior of the code.
Answer: The continue statement is useless in your example. It is supposed to be used to move code execution to the end of a loop:
while (is_true)
  {
    ...

    if (foo)
      continue;

    if (bar)
      break;

    ...

    /* 'continue' makes code jump to here and continues executing from here */
  }
/* 'break' makes code jump to here and continues executing from here */

You can think of continue as "evaluate the loop condition and continue the loop if the condition is false", and you can think of break as "exit the loop, ignoring the loop condition".
Same thing with do-while:
do
  {
    ...

    if (foo)
      continue;

    if (bar)
      break;

    ...

    /* 'continue' moves execution to here */
  }
while (is_true);
/* 'break' moves execution to here */


App xamarin mostrando uma hora adiantada

Question: Aqui na empresa temos um aplicativo de bater ponto, nesse aplicativo é mostrado a hora atual na tela.
Ex:
viewModel.HoraAtual = DateTime.Now.ToString("HH:mm:ss");
Está mostrando sempre uma hora adianta em alguns celulares, alguém já passou por esse problema?
Comment: ele não está com a tabela Z (não lembro o resto) que define o Time Zome desatualizado? tipo, por causa do "Não horário de verão"
Answer: Acredito que o problema pode ser a definição de timezone errada nos dispositivos. Vi um problema parecido assim no passado ser resolvido com conversões de timezone. Consegue testar para ver se resolveria no seu caso?
TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id));

Comment: vou testar, mas acredito que seja problema do horário de verão, quando coloco a região da Bahia que não tem horário de verão funciona, estou tentando também utilizar o BaseUtcOffset onde não é considerado o horário de verão, publiquei uma versão do App, se funcionar informo vocês


Displaying image with matplotlib in ipython

Question: How can I display an image imported with numpy package using matplotlib in ipython?
It should be fairly easy with the command
import numpy as np
import matplotlib.pyplot as plt

im = np.array(Image.open('image.jpg'))

plt.imshow(im)

But the image does not show and I just get the output
<matplotlib.image.AxesImage at 0x7fb38e10ff10>

Comment: Possible duplicate of [Use imshow of matplotlib.pylab with a python ide?](http://stackoverflow.com/questions/34742842/use-imshow-of-matplotlib-pylab-with-a-python-ide)
Answer: You must call plt.show() to actually bring up the windows.
You can get around this by using interactive mode. But for scripts it is better to simply call show() after completing all your plotting commands.
Answer: In IPython or Jupyter notebooks, if you want to show images as inline in the notebook and not in a separate window, implement the code shown below.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

im = np.array(Image.open('image.jpg'))

plt.imshow(im)
plt.show()

Comment: Do you need plt.show() when you use %matplotlib inline?


How can I move the navigation bar?

Question: Been working with a template and I want to try to move the navigation bar. But it dosen't seem that easy, seems like I'll have to change the CSS. Can anone help me here?
Here's the HTML and how the website looks so far:

I would like to move it to the left corner, and this is the CSS code I believe I can do the trick in:
<code>    .header-nav {
    background: #0C0C0C;
    color: rgba(255, 255, 255, 0.25);
    font-family: "montserrat-light", sans-serif;
    font-size: 1.3rem;
    line-height: 1.846;
    padding: 3.6rem 3rem 3.6rem 3.6rem;
    height: 100%;
    width: 280px;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 700;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-transition: all 0.5s ease;
    transition: all 0.5s ease;
    -webkit-transform: translateZ(0);
    -webkit-backface-visibility: hidden;
    -webkit-transform: translateX(100%);
    -ms-transform: translateX(100%);
    transform: translateX(100%);
    visibility: hidden;
}

.header-nav a, .header-nav a:visited {
    color: rgba(255, 255, 255, 0.5);
}

.header-nav a:hover,
.header-nav a:focus,
.header-nav a:active {
    color: white;
}

.header-nav h3 {
    font-family: "montserrat-semibold", sans-serif;
    font-size: 11px;
    line-height: 1.5;
    text-transform: uppercase;
    letter-spacing: .25rem;
    margin-bottom: 4.8rem;
    margin-top: .9rem;
    color: #39b54a;
}

.header-nav p {
    margin-bottom: 2.7rem;
}

.header-nav__content {
    position: relative;
    left: 50px;
    opacity: 0;
    visibility: hidden;
</code>
Would appreciate if anyone could help!
Comment: It would be better if you provided your HTML raw in the question opposed to in an image. This will make it easier for others to help answer the question.
Answer: Assuming your header-nav element is the hamburger icon, you can delete right:0 and set
<code>.header-nav {
...
left:0;
...
}
</code>
Comment: This actually moved it. Howevert now the animation is wrong, it still comes from the right one. Do you know how I can change this aswell?
Comment: It is hard to know, without a snippet...., in your css code you can try setting transform: translateX(-100%); in your .header-nav..as I said I am guessing..
Comment: Hey there! Did the job! Thank you so much! :)
Comment: I'm kinda new to all this, how do I mark it as correct?
Comment: Done! Thank you!
Answer: I think this is what you want:
Add following css file to your project:
https://mladenplavsic.github.io/bootstrap-navbar-sidebar/navbar-fixed-left.min.css
And add the 'navbar-fixed-left' tag to your 'nav' element.
If you want to read everything about it here's the site:
https://mladenplavsic.github.io/bootstrap-navbar-sidebar/
You can find the code in the broncode of the page

How can I move the navigation bar?


Gaussian likelihood + which prior = Gaussian Marginal?

Question: Given a Gaussian likelihood for a sample $y$ like $$p(y|\theta) = \mathcal{N}(y;\mu(\theta),\Sigma(\theta))$$ with $\Theta$ being the parameter space and $\mu(\theta)$, $\Sigma(\theta)$ arbitrary parameterisations of the mean vector and the covariance matrix.
Is it possible to specify a prior density $p(\theta)$ and parameterisation of the mean vector $\mu(\theta)$ and the covariance matrix $\Sigma(\theta)$ such that the marginal likelihood $$p(y)=\int_{\theta\in\Theta}N(y;\mu(\theta),\Sigma(\theta))p(\theta)d\theta$$ is a Gaussian likelihood?
I guess excluding the trivial solution that the covariance is known, that is, $\Sigma(\theta)=\Sigma$, where $\Sigma$ is an arbitrary fixed covariance matrix, this is not possible.
For the special case $\mu(\sigma^2)=\mu$ and $\Sigma(\sigma^2)=\sigma^2$, that is $y$ is one-dimensional, and $p(\sigma^2)=\mathcal{U}(\sigma^2;a,b)$, where $\mathcal{U}(\sigma^2;a,b)$ denotes the uniform density  I can show it:
\begin{align}
p(y)&=\int_0^\infty \mathcal{N}(y;\mu,\sigma^2)\mathcal{U}(\sigma^2;a,b)d\sigma^2 \\
&= \frac{1}{b-a} \underbrace{\int_a^b \mathcal{N}(y;\mu,\sigma^2)}_\text{not a Gaussian density}
\end{align}
The accepted answer contains a formal or informal proof or pointers to it.
Answer: Your conjecture seems to be true: only a constant variance can lead to
a normal margin. My proof is limited to the case where the
expectation $\boldsymbol{\mu}$ is known, and hence can be assumed to
be zero. For the general case, more sophisticated arguments from
functional analysis seem to be required.
Note that the question is actually about continuous mixture of normals as well
as about Bayes. The statement proved here it that a (continuous) scale
mixture of normals can be normal only for a trivial mixture.
First consider the case of a one-dimensional normal with known mean
$\mu = 0$ and precision parameter $\omega := 1 / \Sigma >0$. Without loss of
generality, we can assume that the parameter $\boldsymbol{\theta}$ is
the precision $\omega$ itself. If the marginal distribution of $y$ is
normal, then $\int \exp\{-y^2 \omega / 2\}\,\omega^{1/2}
p(\omega)\,\text{d}\omega$ is a normal density up to a multiplicative
constant. This density being an even function of $y$ must take the
form $c\exp\{ -y^2 \omega_0 / 2\}$ for some $\omega_0 >0$ and some
constant $c >0$. Since this holds for any $y$ we get with $s := y^2$
$$ \int_0^\infty \exp\{-s \omega \,/ 2\}\,\omega^{1/2}
p(\omega)\text{d}\omega = c \exp\{ -s \omega_0 \,/ 2\} $$ for all $s
\geq 0$, which shows that the finite measure with density function
$\omega \mapsto \omega^{1/2} p(\omega)$ is proportional to the Dirac
mass at $\omega_0$ because these two measures have the same Laplace
transform, up to a multiplicative constant. Thus $\omega$ is almost
surely (a.s.) equal to $\omega_0$.
This proof extends to the
$d$-dimensional normal with mean zero and precision matrix
$\boldsymbol{\Omega}:=\boldsymbol{\Sigma}^{-1}$. The margin then writes
as $\propto \int \exp\{-\mathbf{y}^\top \boldsymbol{\Omega}\,\mathbf{y} \,/
2\}\,
\left|\boldsymbol{\Omega}\right|^{1/2}p(\boldsymbol{\Omega})\,\text{d}\boldsymbol{\Omega}$
where the integral is on the set $\mathcal{P}$ of positive definite
symmetric $d \times d$ matrices. If this integral is identical to
$c\exp\{ -\mathbf{y}^\top \boldsymbol{\Omega}_0 \mathbf{y} / 2\}$,
then by taking $\mathbf{y}:= \sqrt{s} \,\boldsymbol{u}$ for a scalar
$s \geq 0$ and an arbitrary vector $\mathbf{u}$, we find as above that
$\mathbf{u}^\top \boldsymbol{\Omega}\, \mathbf{u}$ must be a.s. equal
to $\mathbf{u}^\top \boldsymbol{\Omega}_0 \mathbf{u}$, which shows
that $\boldsymbol{\Omega}$ is a.s. equal to $\boldsymbol{\Omega}_0$.
The proof works even if the measure conveniently written as having
density $|\boldsymbol{\Omega}|^{1/2} p(\boldsymbol{\Omega})$
concentrates on a subset of $\mathcal{P}$ with Lebesgue measure zero,
because the Laplace transform argument still applies. So the proof
works for a general parameterisation of the precision (or variance)
matrix.
Comment: I have not understood your proof fully yet. In comparison to Jacky1's answer it seems relatively complex. What do you think about his proof?
Comment: Well I could not understand how the prior can depend of $y$ in Jacky's
answer. Yet his statement as I understand it is wrong - I did the same
error first:) Indeed, $\mu$ is not necessarily constant and if
the variance is constant, $\mu$ still can be normal which is easily
checked by completing a square. I now have a proof for the independent prior case (one-dimensional for simplicity), and hope to write it down soon, maybe as a new answer.  The variance $\Sigma$ must be constant and $\mu$ must be normal (possibly degenerate).
Comment: Could you expand your reasoning in the paragraph starting with "Since this holds for any $y$ and ending with "(a.s.) equal to $ω_0$"? Maybe with pointers to the theorems you are using?
Answer: Assume that $\mu$ and $\Sigma$ are a priori independent and that $y$
has a normal margin with mean $\mu_0$ and variance $\Sigma_0$. I
will prove that then the variance $\Sigma$ must be constant, and
the mean $\mu$ must have a normal prior (possibly degenerate).
I will stick to the one-dimensional case for simplicity, using the
characteristic function (c.f.) of $y$, i.e. $\phi_y(t) :=
\mathbb{E}[e^{yit}]$.  We know that $\phi_y(t) = \exp\{\mu_0 it - \Sigma_0 t^2 /2$} and
 a similar formula holds for the distribution of $y$ conditional on $\mu$
and $\Sigma$, which is normal by assumption. So for any real $t$
$$
 \mathbb{E}[e^{yit}] = \int \mathbb{E}\left[e^{yit} \, \vert \,\mu,\,\Sigma\right]\,
 p(\mu) p(\Sigma)
 \,\text{d}\mu \text{d} \Sigma =
 \int \exp\left\{ \mu it  - \Sigma t^2/2 \right\} \,p(\mu) p(\Sigma)
 \,\text{d}\mu \text{d}\Sigma,
$$
and by rearranging the integral, we must have
$$
   \exp\left\{ \mu_0 it - \Sigma_0 t^2 /2 \right\} =
 \left[\int \exp\left\{ \mu it \right\} p(\mu)
 \,\text{d}\mu \right]
 \left[\int \exp\left\{ -\Sigma t^2/2\right\} p(\Sigma)
 \,\text{d}\Sigma \right].
$$
The assumptions needed for such a rearrangement are easily checked.
The first integral at right hand side, say $\phi_1(t)$, is the c.f. of
$\mu$. Note that since $\phi_1(t) e^{-\mu_0 it}$ is found to be real, we see that
the distribution of $\mu$ is symmetric w.r.t. $\mu_0$, and hence that
$\mathbb{E}[\mu] = \mu_0$, as it might have been anticipated.
Now it turns out that the second integral at right hand side, say
$\phi_2(t)$, is also a c.f. To see that, we must check that $\phi_2(0)
= 1$, that $\phi_2$ is continuous at $t=0$ and also that the function
$\phi_2$ is positive definite (p.d.). The first requirement is
obvious, the second is proved by dominated convergence. Now turn to
the p.d. requirement: if the prior distribution written as
$p(\Sigma)\text{d}\Sigma$ is a Dirac mass, then $\phi_2$ is
p.d. because $\phi_2$ is then the c.f. of a normal distribution.  If
the prior is a discrete mixture of Dirac masses, this is true as well
since $\phi_2$ then is the c.f. of a mixture of normals. By a continuity
argument, we see that $\phi_2$ is p.d.
Now let us use the powerful Lévy-Cramér theorem which tells that
both functions $\phi_j$ for $j=1$, $2$ must take the form $\exp\{a_j i t -
b_jt^2 /2 \}$ with $a_j$ real and $b_j \geq 0$. So $\mu$
must be normal (possibly degenerate) with mean $a_1 = \mu_0$.
By simple algebra we then have
$$
    \exp\{ -(\Sigma_0 - b_1) t^2 /2 \} = \int_0^\infty \exp\{ - \Sigma t^2 /2\} p(\Sigma)
    \, \text{d} \Sigma
$$
which holds for any real $t$. Since any non-negative real writes as $t^2/2$, we see that
the Laplace transform of the prior of $\Sigma$ must be equal to that
of the Dirac mass at $\Sigma_0 - b_1$ and we are done.
Comment: Thanks for your effort. It will take me some time to understand this.
Answer: I have a proposition of proof for you, but you need to check it.
Assume that the marginal likelihood is Gaussian :
$p(y)=\mathcal{N}(y,m,\Gamma)$
then the prior density can be defined by
$p(\theta)=\mathcal{N}(y,\mu(\theta),\Sigma(\theta))^{-1}\mathcal{N}(y,m,\Gamma)f(\theta)$
where $f$ checks $\int_{\theta\in\Theta}f(\theta)d\theta =1$ and $f(\theta)\geq 0$ for $\theta\in\Theta$. ($f(\theta)$ is $p(\theta|y)$).
To be a density, the integral of the prior density $p(\theta)$ on $\Theta$ has to be equal to 1.
In other words,
$\int_{\theta\in\Theta}\mathcal{N}(y,\mu(\theta),\Sigma(\theta))^{-1}\mathcal{N}(y,m,\Gamma)f(\theta)d\theta =1$.
It leads to
$\int_{\theta\in\Theta}\mathcal{N}(y,\mu(\theta),\Sigma(\theta))^{-1}\mathcal{N}(y,m,\Gamma)f(\theta)d\theta = \int_{\theta\in\Theta}f(\theta)d\theta$
This equality being true if and only if $\mu(\theta)=m$ and $\Sigma(\theta)=\Gamma$.
Comment: I like the proof idea. I am pretty certain that all steps but the last one are valid. Surely the integral of two functions are the same if the functions are the same but this is not a necessary condition. Are you using a different theorem there?
Comment: If you replace $p(\theta|y)$ with its defintion via bayes in your first formula for $p(\theta)$, then it becomes $p(\theta)=p(\theta)$. Surely, nothing follows from this inequality.


How to restrict a child class from overriding parent class method in C#?

Question: I was trying to implement template method pattern in C#. But I could not find a way to restrict child class from overriding my base class template method, unless I have a two level deep inheritance to use sealed.
If I omit virtual, child class has the liberty of providing new implementation, in which case, it will be called from child class's reference. Instead, I need some mechanism, like final in Java, wherein I can restrict the template method from overriding in the parent class.
Comment: Your question is confusing. Why would your base method even need to be `virtual`? If it's not virtual, the child class cannot override it -- it can provide a method with the same name marked as `new`, but this method will never be called if the reference has the type of the base class. And if it's not of the correct type, you can simply cast it to the base class to force this (`((Parent) child).Foo()`). If someone is explicitly calling `child.Foo()`, they know they're doing so.
Comment: Regardless of u make it virtual or non-virtual, your child class has the ability to provide new implementation. A class can't restrict what its subclasses can/should do.
Answer: Your template method should be non-virtual (it's default in C#). It should call a protected virtual/abstract method that the child classes override.
For example
<code>public abstract class Base
{
    public void TemplateMethod()
    {
        //do sth
        OtherMethod();
        //do sth more
    }

    protected abstract void OtherMethod();
}

public class Child : Base
{
    protected override void OtherMethod()
    {
        //provide implementation
    }
}
</code>
Comment: @RaviTiwari those 9 child classes clearly have something in common. Why not add another level of inheritance?
Comment: Thanks for your response.

But I have 20 child classes and the implementation of OtherMethod stays same for 9 of them. So I refrained from making it abstract. Is there a way I can reduce the number of implementations.
Comment: @RaviTiwari It seems that your classes are too big and have too many responsibilities. Try to refactor them into smaller classes and use composition to achieve the required functionality. Deep inheritance hierarchies are usually harder to understand.


How do football players remember so many plays?

Question: A given NFL or college football team has a large variety of plays. How do players remember them all?  I don't think I could remember all those plays if I spent years studying those playbooks.
Comment: Here is this from a previous answer: https://www.quora.com/How-difficult-is-it-to-learn-an-NFL-playbook
Answer: When you call a football play it is a sequenced code.  Each section of the code refers to a certain function.
Let's take something simple on the offensive side that I have called for a college program.

pro-right split 897 F motion right option zone right
pro-right | split | 8 | 9 | 7 | F motion
  right | option zone right |
pro-right - formation.  Typical playbook might have 10-12
  different formations.  Players will pick this up after 1-2 practices.
  It is expected that almost all players on offense understand every
  formation.  For this formation we had one receiver out left, one
  receiver out right, TE right, FB shading right, and HB 5 yards deep.
split - formation-variation.  This is probably the most confusing
  thing about the play call.  Split in this case is that my "Y" concept
  receiver will be split out wider than normal to give space between TE
  and himself.  I might have 4-5 variations on our common formations.
  The variations might effect only WRs as in this case but could also
  affect lineman and the variations can be stacked.  For example in this
  call I could have said split-feet.  Split telling my Y to move out an
  extra 5 yards and feet telling my lineman that they are not to have
  any splits (might do this against a team with a good DL and longer
  pattern concepts).  In pee-wee football we have variations, maybe just
  one or two per formation.  In high school and college you could have
  5-8 per but the NFL gets whacky with this and have heard playbooks
  having 20+ variations.
897 - These are the patterns the receivers will run.  There is
  also a lot of variance in how these are called.  In my example the "X"
  will run an 8, the "Y" will run a 9, and the "Z" (TE) will run a 7.
  If the RB/FB were running patterns they would need calls.  In this
  sequence I would adding "halfback flat" after the 897.  Without any
  sort of pass cue my FB and RB should know that they are blocking.  I
  have also coached where we would call 897 backs 00.  The zeroes
  signify no route for the backs.  And then I have coached where we call
  WR patterns going from left to right.  So if we have trips right we
  might call 4378 and the WR on left gets the 4, first trip WR on right
  gets 3, second trips WR gets 7, and end WR on right gets 8.  This
  might sound hard but it is quite easy for players once rules are in
  place.  This is actually only hard on the coach trying to call the
  play.
f motion right - motion and extras.  I am telling my fullback to
  motion right.  In this playcall he will motion facing line of
  scrimmage very slowly and will end up over the tackle.  How does he
  know that?  Because the fullback only has a few motion calls and he
  has practiced it 100 times.  He doesn't just run right until he hits
  the sideline.  He will motion to the tackle and will get the first man
  around the tackle.  This motion actually impacts everyone on the line
  and the RB too!  Since the FB has motion right, he will pick up the
  edge.  Meaning that the right side of my line will squeeze in knowing
  they have help outside.  My RB knows that he will step up to the left
  since there is already help on the right.  The left side of my line
  will block "normal" knowing that the RB is probably better off taking
  on a leaker than someone on the edge.
option zone right - check down play Basically if my QB checks out
  of the pass we will run this run play.  Note that we have the FB in
  motion going here.

Now if the play is a staple of your offense your team may just give it a nickname.  One of the schools I was at simply called this "pro-right/left chuck or dive".  The players knew the play call based on the nickname.  I actually remember the FB coming over to me asking me if he should motion on the "chuck or dive".  Which then we went over several scenarios on when he should or shouldn't motion and it was basically his option... unless he saw the not motion hand signal.
Back to your question.  Learning a playbook is really only rocket science for QBs.  They have to know all of the terminology for every position.  If you have a dumb QB you better pick 5-10 plays and create an option off that and go with that.  Each player is only worried about their part generally.  I would expect a player to be able to run any play after 3-4 practices without much of a problem.  Your smart players will learn everything through repetition in a couple of weeks.  I love it when a tackle smacks a receiver on the back of the head and tells him to run the right route and it happens all the time.
Really learning a playbook is only super complex at the pro-level.  And then it is only really hard if you are just thrown into new terminology.  See in general a high school will have a pretty easy playbook.  When a player gets to college it will be a lot harder and a lot different.  The player adjusts through repetition and generally they use the same system their entire time at college (I know this isn't always true for bigtime college amidst coaching carousel).  So really no big deal for players.  QBs might have a tough time at first but that is why not many freshman QBs start.
Now pro terminology might be sort of close to college - because a lot of the NFL players came from bigtime colleges with pro concepts on offense.  So rookies may be in for a shock because the are learning the same thing in a different way.  As a college player you learned "how to speak" and now you go to the NFL and someone is telling you that green tomatoes are now tomate verde.  Just like a language certain terminology that you used is mixed in but there are new things, so things do get confusing.  And then the pros have one more thing to add on to that.  They can be traded from team to team and every team will have a slightly different dialect or speak its own language.
So how hard is it to learn a playbook?  At pee-wee through most colleges you will learn 80% of the playbook concepts in one week and be fine if you are average intellect.  The hard part isn't learning the play.  The hard part is remember your task on the play in question when you are out of breathe and just had your ass handed to you.  I find that 90% of the "Responsibilities" errors come from mental mistakes of forgetting than it is from a player not knowing.  And if a player doesn't know it is generally the coaches fault for playing him there - I would "quiz" my players all practices and throw them some booby trap play calls.
Comment: Ask the defense side in another question and I will answer it in the next day or two.  Books... not sure.  These things are often passed around by coaching trees.  Really I could have given 20 examples.  It isn't hard explaining them or anything but I don't think it meets this format.  What you got was maybe kind of complex for high school but a 4 out of 10 for small time college.
Comment: I posted that other thread here: http://sports.stackexchange.com/q/8687/8945
Comment: @StanShunpike - That was literally the most basic I could be.  I didn't even get into a defense playcall example but basically it is the same sequencing.
Comment: It would be interesting to see the defensive case to compare. Also, are there any good books that discuss this stuff? I have one I like, but it's clearly not written by a college or pro coach so, although thorough, it lacks complexity.
Comment: Also note on remembering plays.  I find that some players have a hard time memorizing from playbooks.  Some we create Madden playbooks and tell them they can only use those specifically.  I find it really funny that players want to run the play that "works on Madden" the best and expect the same glitchy results.  Anyway it is much easier to remember things when you know you have 20 up-downs to do if you mess up.  Actually if we took this mentality everywhere we would have lots of straight A students (and the ones with bad grades in great shape).
Comment: Madden is so unrealistic. The guys behaviors are so stereotyped. Real players think and adapt.  Its interesting how technology affects how ppl teach football. I read a book by Belichick's father on scouting and they were just starting to use video back then. Now days video gives so much more information then they could have imagined, so its interesting to see how much coaching techniques have shifted in 50+ years.
Comment: Madden is a terrible simulation.  Players don't react the same 90% of the time just because they are lined up the same, players are affected by fatigue and injury way more than Madden lets on, players diagnose much faster similar plays, and most frustrating part of playing Madden from a coaches view is that QBs are not even close to being as accurate as the worst "Madden QB".  Basically every pass you throw goes where you want it to even after you run backwards and to your left.
Comment: Exactly. Modern simulations aren't a real model of mechanics. pro quarterbacks are clearly are aware not just where their bodies need to be positioned geometrically, but also how they need to strengthen and condition their bodies so they can do it more efficiently. Like for instance, the kinetic chains that are used in rotation run from the abs to the legs and are key for throwing obviously. Those are aspects of the game that are critical to take into account but that anyone playing Madden never thinks about. I started to take an interest in coaching when I realized how much thought it takes.
Answer: According to an ex NFL player:

I'm not sure many players memorize it per se; it's more about understanding the concepts rather than just knowing every single individual play call.   I'd liken it to learning a new language- it's easier to understand the basic structure of it than it is to memorize the dictionary.

So basically it's not about memorizing every play step for step, it's about memorizing the base logistics of play sets(Nickle defense, dime defense, 4-3 defense, etc).  It'd be very hard to memorize every step of every play, but I'm sure there are guys out there who it comes natural to.  You gotta remember as well that teams practice these plays every single day of the season, and quite a bit of the offseason, so while you might not remember plays perfectly, you'll remember the gist of what you're supposed to do.  Case in point is when you see a Quarterback throw the ball and the WR goes the opposite direction, just might have gotten their plays mixed up a bit.
Source
Answer: Very simply, there are very few offensive plays that require players other than the QB to memorize exactly what everyone else on the field will be doing. Nine plays out of ten, each player just has to remember what he's supposed to do:

Blocking assignments. The offensive lineman draws his paycheck for protecting the QB, and other positions like the tight end and running back typically get their hits in too. It's not a flashy job but it pays well, especially on the QB's "blind side". But, doing it well requires knowing who to hit first, or even when to hit. Defensive formations usually don't mirror the offensive line; they'll put three or four linemen against five OL, with two to four linebackers behind that. That requires each offensive lineman to know whether he's blocking to his inside, his outside, or in some cases pushing downfield to block in the secondary.
Snap count. The offense cannot move for one full second before the snap of the ball, with the exception of a single "man in motion" who must be a "back" and cannot be moving toward the line of scrimmage as of the snap. Violating any of this is an "illegal shift", "illegal motion" or "false start" depending on exactly what happened when. These penalties are most often whistled on a player that doesn't know or doesn't remember the "snapcount", which is the pre-arranged signal on which the center should snap the ball; the QB will say several other things while the offense is "down" in an attempt to draw the defense off-sides, but it will backfire if an offensive player "jumps".
Passing routes. Wide receivers have nine basic routes they run; the exact path can vary as the player attempts to evade the defense, but they are:

You'll hear of some variations, but they're all based on one of these 9 routes.
Notice that the "outside" routes are odd, while the "inside" routes are even; it's typical for two wide receivers lining up on the same side to have routes that don't interfere; the outside receiver will run an odd route while the inside receiver runs an even route. However, one of the most basic offensive tricks is to set up a "crossing route"; the inside receiver will run a corner or fade route, while the outside receiver runs a post, dig or slant. If done correctly, the defense will be caught on their heels and the player cutting inside will get space from his defender to make a play happen. However, this is one case where the receivers have to know what the other is doing, so they run close enough at the start to keep the defenders close to each other, without the cross tripping up one or both receivers.
Running routes. In addition to variations on the above pass routes and a few more "screen" routes where the RB squeezes through the line before catching a pass, the RB can also receive a handoff, and most running plays are designed to give him a specific hole at the line of scrimmage to run through. It isn't always there, so the star running backs in the NFL draw their pay for being quick thinkers and movers to find the hole, but the blockers will know where the RB will be looking to go and will try to open the hole by changing their blocking direction, moving inside instead of outside or even moving through the defense to block in the secondary.
Downfield tactics. Once the play "develops", offensive players who have moved downfield should assist the ball carrier any way they can, primarily by blocking downfield defenders so the ball carrier has room to run, or in some circumstances being available to catch a "pitch".
Answer: There's an enormous selection bias going on by the time players reach the NFL - if they can't remember lots of plays, they're not going to do well in college and therefore they won't get drafted into the NFL, so the only players you see in the NFL are automatically those that can remember lots of plays.
Comment: That makes sense and undoubtedly true. But it still leaves the question of how players remember them period. Maybe I should adjust it to specify college or pro.
Comment: @StanShunpike How do doctors remember anatomy, or what symptoms mean in a differential diagnosis?  How did you (perhaps) learn the 50 states or the periodic table?  To the extent that they memorize them, they do so by repetition.  Remember, they repeat these plays over and over again all year in practice - this is their job, which they spend 60-70 hours a week working at, including much of that time with a playbook.  And as Philip states: the ones who can't do it, don't make it.


a basic question on continuity

Question: Suppose $f:\Bbb R \to \Bbb R$ which is not injective and continuous. I need to find an open set in the domain which does not get mapped to an open set in the range. how ?
Comment: You want to find or you want to prove it's existance?
Comment: You can't. Check [this](http://en.wikipedia.org/wiki/Continuous_function#Continuous_functions_between_topological_spaces): *'This is equivalent to the condition that the preimages of the closed sets (which are the complements of the open subsets) in Y are closed in X'*.
Comment: @GitGud Read better.
Comment: @Did Here's my interpretation of the (problematic part of the) question: Suppose $f\colon \Bbb R\to \Bbb R$ is continuous and not injective.
Answer: Consider a value $y_0 \in \mathbb{R}$ that gets mapped to by several $x\in \mathbb{R}$. Now one of the following is certainly true: Either there is an interval $[a,b]$ in the domain where all the $x \in [a , b ]$ get mapped to $y_0$. Then we can use $(a,b)$ as the open set we're looking for.
Or there are $x_1 <  x_2 \in \mathbb{R}$ such that $f(x_1) = f(x_2) = y_0$ and $f(x) \neq y_0$ for all $x_1 < x < x_2$. Then $f$ either takes a minimum or a maximum on $[x_1,x_2]$ which is not $y_0$ and therefore, $f( (x_1,x_2))$ will also have a maximum or minimum, so it is not open.

a basic question on continuity


"Place block" ajax error when using nginx

Question: I'm having a lot of trouble configuring nginx properly for Drupal 8. Using the Drupal nginx recipe on the official site works well except for opening modal dialogs like the "Place block" dialog. This results in a 200OK response but an ajax error.
Here is a gist with the error.
I know this is an nginx configuration issue as I have a different conf file that doesn't cause this issue. This other configuration doesn't work with Drupal 8's active link javascript due to the way it adds the query parameters. Frustrating!
Answer: Sometimes writing it down helps to figure things out! The missing bit of configuration needed is fastcgi_param QUERY_STRING $query_string;
With the Drupal nginx recipe but with that line added in the location ~ '\.php$|^/update.php' { block its now working as expected, both the is-active class is added to the active menu link and the "Place block" ajax works properly.
Comment: Have issued a [pull request](https://github.com/nginxinc/nginx-wiki/pull/315) with the change for the nginx recipe.


How to create bar chart using progress bar in AngularJS?

Question: I am new to AngularJS and I am trying to create a bar chart using progress bar in AngularJS for my below value.
My response will be :
var json_response =  {

  "data": [
    {
      "standard": "Ist",
      "max_students": 20,
      "available_students": 8
    },
    {
      "standard": "IInd",
      "max_students": 15,
      "available_students": 10
    },
    {
      "standard": "IIIrd",
      "max_students": 50,
      "available_students": 22
    }
  ]
}

I need to use above response and display it in a form of vertical bar chart.
Comment: angularjs has nothing to do with charts specifically,  consider using third party tools like c3.js, highcharts, etc..
Comment: If i use html to create progress bar chart using value from angular function. Then ?
Comment: then it only going to cost you a lot of efforts, you need to write lot of javascript code and css unnecessarily
Answer: If you just want progress bars you can use ui-bootstrap progressbar
Here's a fiddle with an example https://jsfiddle.net/pritojs/uub4tw7d/3/
Answer: You want to check Angular-ChartJS out. It gives you a lot of options to create your charts using angular directives.
You could do something like this:
angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope) {
  $scope.labels = [];
  var students_data = [];
  var available_students_data = [];

  angular.forEach(json_response["data"], function(data) {
    $scope.labels.push(data["standard"]);
    students_data.push(data["max_students"]);
    available_students_data.push(data["available_students"]);
  });

  $scope.series = ['max_students', 'available_students'];
  $scope.data = [students_data, available_students_data];
});

And in your html you just have this :

  <canvas id="bar" class="chart chart-bar" chart-data="data" chart-labels="labels"> chart-series="series"
  </canvas>

Check this plunker
Comment: If i use html to create progress bar chart using value from angular function. Then ?
Comment: @KalaiyarasiM, I updated the answer. Check the plunker to see if it is close to want you are trying to achieve.
Comment: I am getting version angularjs 1.2.20 and in above it is using angular 1.4. So I am getting error while i mention ["chart.js"].
Comment: " Error: [ng:areq] Argument 'BarController' is not a function, got undefined "
Comment: @KalaiyarasiM, I am not sure if angularjs version is going to be a problem with Angular-ChartJS because It has been tested on 1.2.x. The error you are getting shows that you are probably declaring your angular module wrongly. Check this  stackoverflow answer http://stackoverflow.com/a/25895387/4092170


Canplayer won't replay candump files

Question: I'm trying to use canplayer to replay some candump files, with no success. When I try to run the canplayer it just executes and returns, giving me no clue of what is happening.
What I've tried up to now:
Setup 1

Set up a vcan interface
Sent data to the vcan interface using cansend and cangen, with success (verified with candump).
Recorded a candump file from vcan0 when running cangen. Recorded files with absolute timestamps (-t a) and without.
Tried using canplayer to reproduce the file. Tried using several arguments, no avail. canplayer just returns immediately without any complaint. If I mess up the the file or arguments it complains.

Setup 2

Connected 2 PEAK CAN USB adapter devices to the PC.
Connected the adapters to each other using a 120ohm terminated cable
Started cangen pointing to can0 and verified that the messages got to can1 using candump
Recorded candump files from can0 interface.
Tried using canplayer to reproduce the file., with no success.

I've tried these tests on two different machines, both running Ubuntu 12.04, with the same results.
Do you know what might be the cause of it?
Comment: Cool. When you hover over a tag, look for an "info" link. That will take you to the tag info, aka tag wiki. Have a look at some established tags to get an idea of what info makes sense (for example [[tag:google-apps-script]]). If you edit the tag info, you'll find it has two parts, a excerpt or summary, and the wiki body. The summary gets shown when people are typing a tag on a question, so it's good if it's short and to the point, so people might read it and avoid using the wrong tag.
Comment: The "canutils" is a set of tools that are used for testing, logging and debugging SocketCAN applications in a Linux environment. It is difficult to find information about programming SocketCAN and canutils usage around the internet, only place I've found up to now is a mailing list (http://socket-can.996257.n3.nabble.com/Socket-CAN-Users-f3.html). I believe others programmers that also work with SocketCAN would benefit from using StackOverflow to share their questions and answers. That is why I decided to post it here.
Comment: Fair enough, I'm glad I asked. I'd still encourage you to create good tag wikis for these tags, to help others understand what they're about.
Comment: I didn't know about the tag wiki thing, I'll look into that, thank you. I've also removed one of the new tags, I believe just the "canutils" one is enough.
Answer: It seems I had recorded the log files in a wrong manner.
My logs files where recording using the following command:
<code>$ candump -ta vcan0 "log.candump"
</code>
That command, however, records the log in human readable format:
<code>  vcan0  1B3   [8]  8E 02 74 22 55 70 49 30
  vcan0  658   [6]  27 48 2C 56 14 0A
  vcan0  1F8   [2]  77 99
  vcan0  7B7   [8]  33 A2 24 38 B2 78 86 72
  vcan0  43C   [8]  92 C6 81 2E FC 5E 38 35
  vcan0  7B0   [2]  2D 1B
</code>
In order to record log files that can be playback with canplayer, they should be recorded using either
<code>$ candump -l vcan0
</code>
or
<code>$ candump -L vcan0 > myfile.log
</code>
The recorded file will look like this:
<code>(1436509052.249713) vcan0 044#2A366C2BBA
(1436509052.449847) vcan0 0F6#7ADFE07BD2
(1436509052.650004) vcan0 236#C3406B09F4C88036
(1436509052.850131) vcan0 6F1#98508676A32734
(1436509053.050284) vcan0 17F#C7
(1436509053.250417) vcan0 25B#6EAAC56C77D15E27
(1436509053.450557) vcan0 56E#46F02E79A2B28C7C
(1436509053.650713) vcan0 19E#6FE1CB7DE2218456
(1436509053.850870) vcan0 1A0#9C20407F96EA167B
(1436509054.051025) vcan0 6DE#68FF147114D1
</code>
Files in that format can be replayed in canplayer using the following commands:
<code>$ canplayer -I candump-2015-07-10_081824.log
</code>
or
<code>$ cat candump-2015-07-10_081824.log | canplayer
</code>
Credits for this answer go to Oliver Hartkopp.
Comment: Do you know if there is a utility for converting already recorded data from one format to the other?
Comment: `cat infile | awk '{print "(0.000000) "$1" "$2"#"$4$5$6$7$8$9$10$11 }' > outfile` did the trick for me, however all timestamps are set to zero.
Comment: @Aras There is a "asc2log" app (see https://github.com/linux-can/can-utils), but I've never used it, though. If you try it, please let me know if it works.
Answer: I found this article with some great information about using can and vcan. After taking a log of a physical CAN bus with candump using
<code>$ candump -l can0
</code>
as stated in the previous answer. I used the following to play it back over a virtual CAN bus.
<code>$ canplayer vcan0=can0 -I candump-may-14-2015.log
</code>
Comment: That link is dead now. If you still want to access the content then go to archived snapshot at https://web.archive.org/web/20170907045429/http://www.embeddedhobbyist.com/2015/09/linux-can-development/
Answer: Here it is:
<code>cat input | awk '{print $1" "$2" "$3"#"$5$6$7$8$9$10$11$12}' > output.log
</code>

Canplayer won't replay candump files


Porque o background-color não aparece?

Question: Bom, eu tenho o seguinte codigo:

body {
  background-image: url("imagens/fundo.png");
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0;
}

.container {
  margin-left: 10%;
  margin-right: 10%;
  width: 80%;
  position: relative;
}

.logo {
  position: absolute;
  margin-top: 5%;
}

.bloco2 {
  position: absolute;
  background-color: #ABABAB;
  height: 2%;
  width: 2%;
  margin-top: 20%;
}

.linha1 {
  margin-left: 20%;
  background-color: #ABABAB;
  height: 5%;
  width: 20%;
  margin-top: 2%;
  position: absolute;
}

.online {
  margin-left: 60%;
  margin-top: 0%;
  position: absolute;
}

.jack {
  background-color: #ABABAB;
  height: 5%;
  max-width: 20%;
  margin-left: 80%;
  position: absolute;
}

.loginsteam {
  margin-left: 40%;
  position: absolute;
}

.menu {
  margin-top: 10%;
  position: absolute;
}

.goncalo {
  background-color: green;
  width: 10%;
  height: 5%;
  position: absolute;
}

      Best Jackpot: Goncalo

      Online:
      20

      Goncalo

      Oi

No style da classe .goncalo, o background-color não está a aparecer quando eu meto position absolute. Porquê? Como posso resolver isto.
Comment: Eu, enganei-me no botão :S queria aceitar, e cliquei no botão errado, se poder adicionar denovo agradecia.
Comment: E a incompatilidade está entre `position: absolute` e `height` relativo. Ao definir a altura em `px`, por exemplo, funciona como esperado. Ainda tentando entender o porquê exatamente.
Comment: Pois já vi que sim, mas também não consigo entender o motivo.
Answer: A incompatibilidade se dá entre as propriedades position, definida como absolute, height, com valores relativos. Isso acontece porque ao utilizar a propriedade position: absolute você estará removendo o elemento do fluxo natural de exibição, sendo ignorado pelos elementos posteriores e ignorando propriedades de seu elemento pai. Possuir uma altura relativa só faria sentido quando o valor é relativo à propriedade do elemento pai, como o elemento com position: absolute ignora tais propriedades, não é possível ter valores relativos.

Essa relação é reestabelecida se o elemento pai possui position: relative e definir um valor absoluto para a propriedade que desejas manter como relativa. Neste caso, bastaria adicionar uma altura com valor absoluto à .container que seria possível manter a altura de .goncalo relativa.

Basta você alterar o valor da propriedade height para um valor absoluto, tal como 50 px, como no exemplo abaixo, e verá que funcionará como esperado.

body {
  background-image: url("imagens/fundo.png");
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0;
}

.container {
  margin-left: 10%;
  margin-right: 10%;
  width: 80%;
  position: relative;
}

.logo {
  position: absolute;
  margin-top: 5%;
}

.bloco2 {
  position: absolute;
  background-color: #ABABAB;
  height: 2%;
  width: 2%;
  margin-top: 20%;
}

.linha1 {
  margin-left: 20%;
  background-color: #ABABAB;
  height: 5%;
  width: 20%;
  margin-top: 2%;
  position: absolute;
}

.online {
  margin-left: 60%;
  margin-top: 0%;
  position: absolute;
}

.jack {
  background-color: #ABABAB;
  height: 5%;
  max-width: 20%;
  margin-left: 80%;
  position: absolute;
}

.loginsteam {
  margin-left: 40%;
  position: absolute;
}

.menu {
  margin-top: 10%;
  position: absolute;
}

.goncalo {
  background-color: green;
  width: 10%;
  height: 50px;
  position: absolute;
}

      Best Jackpot: Goncalo

      Online:
      20

      Goncalo

      Oi

Answer: Ele não desaparece, o que acontece é que fica sem uma referência para altura quando está em absoluto. Dás 20% de nada em height:20%, pois o elemento pai .container não tem um altura definida para servir com referência.
Talvez para o que pretendes deves começar por definir uma altura ao .container, por exemplo height:  500px;
Aqui a opção depende do que pretendes fazer, mas aqui fica uma hipótese para o teus código(altera o teu código):
.container {
  margin-left: 10%;
  margin-right: 10%;
  width: 80%;
  position: relative;
  height:  500px;
}

Espero que ajude!

Porque o background-color não aparece?


Filtrar dados tabela através de checkbox

Question: Tenho as seguintes checkboxes:

         <input type="checkbox" name="checkbox-toggle" rel="Natureza" value="Produtos">

        Produtos

         <input type="checkbox" name="checkbox-toggle" rel="Natureza" value="Produtos Auto-Utilizados">

 Produtos Auto-Utilizados

Tenho esta tabela que vai buscar dados à BD:

   Código
   Nome
   Descrição
   Designação Comercial
   Unidades
   IVA %
   Stock
   Natureza

       @for(art <- artigos) {

          @art.getId()
          @art.getNome()
          @art.getDescricao()
          @art.getDesignacaoComercial()
          @art.getIva().getValor()
          @art.getStockAtual()
       @for(nat <- art.getDesignacoes()) {
         @nat.getGestaoComparativa().getNatureza().getDescricao()
         }

 }

JavaScript
$("input:checkbox").click(function () {

       var showAll = true;
        $('tr').not('.first').hide();
        $('input[type=checkbox]').each(function () {
            if ($(this)[0].checked) {
                showAll = false;
                var status = $(this).attr('rel');
                console.log("STATUS: " + status);
                var value = $(this).val();
                console.log("VALUE: " + value);
                $('td.' + status + '[rel="' + value + '"]').parent('tr').show();
            }
        });
        if(showAll){
            $('tr').show();
        }
    });

Ainda não percebi bem o porquê de não me estar a funcionar. Não percebo bem para que serve o "rel= ". Tentei adaptar o código a partir desta fonte.
Sempre que carrego numa checkbox desaparecem-me todos os dados. Gostava que alguém me ajudasse a interpretar o código fonte para perceber onde vai buscar os nomes que são filtrados e as colunas.
PS: Só necessito de filtrar os dados da coluna Natureza.
Answer: Primeiramente a função irá esconder todas as linhas, depois irá pegar o valor do checkbox selecionado, e irá procurar pelo valor em todos elementos que tiverem a class selecionada (no seu caso natureza), dai dará um .show() nessas linhas.

$("input:checkbox").click(function () {
    var showAll = true;
    $('tr').not('.first').hide();
    $('input[type=checkbox]').each(function () {
        if ($(this)[0].checked) {
            showAll = false;
            var status = $(this).attr('rel');
            var value = $(this).val();
            $('td.' + status + '[rel="' + value + '"]').parent('tr').show();
        }
    });
    if(showAll){
        $('tr').show();
    }
});

<input rel="natureza" type="checkbox" value="Produtos">Produtos
<input rel="natureza" type="checkbox" value="Auto">AutoUtilizados

Tabela

            Product Number
            Status
            Capacity
            Speed

            Memory1
            Shipping
            1GB
            AutoUtilizados

            Memory2
            Discontinued
            2GB
            Produtos

            Memory3
            Shipping
            2GB
            AutoUtilizados

            Memory4
            Discontinued
            4GB
            AutoUtilizados

            Memory5
            Shipping
            4GB
            Produtos

No seu caso, no retorno do banco você deverá fazer o seguinte:
 @nat.getGestaoComparativa().getNatureza().getDescricao()

Comment: Este import:  é necessário? É que com esse import, ao correr a página aparecem estes erros ou warnings:  Uncaught TypeError: Cannot read property 'on' of undefined
app.min.js:1 Uncaught TypeError: undefined is not a function
Comment: Sim @HugoMachado, essa é uma função `JQuery`, basta ter a biblioteca `JQuery` instanciada em seu projeto.
Comment: Desde já agradeço a sua ajuda, foi bastante explícito. Só que o import da biblioteca JQuery parece que atrapalha o trabalho. primeiro altera-me o design da tabela que eu tenho, e aparecem esses warnings que lhe mostrei no comentário anterior, e ao clicar nas checkboxes não faz nada, sem esse importe, pelo menos ao clicar nas checkboxes desapareciam os dados e apareciam.
Comment: Então, primeiro que nas suas `checkBox` você deve colocar o seguinte: `rel="natureza" value="valorDaPesquisa"` e `rel="valorDaPesquisa" value="Auto"`.
Segundo, essa função que você passou como exemplo é nativa do JQuery, sem a biblioteca, não tem como a função funcionar ;/
Comment: Já está a funcionar, o "value" que coloquei é que diferia do que era apresentado na tabela, daí estar semrpe a deseparecer. Muito Obrigado @Marcelo Bonifazio !


How to assign Go_To_Page in Form Service on Multiple Choice?

Question: Just starting to use the Forms Service in Google Apps Script.  Need to direct the form to take the user to a specific page depending on the answer that is given. Here's my current code
form.addMultipleChoiceItem()
    .setTitle('What would you like to do?')
    .setRequired(true)
    .setChoiceValues(['Request a new reservation.','Change the date or number of tickets for an existing reservation.'])

Now, I've found this section in the documentation: Enum PageNavicationType
But they don't example the use of Go_To_Page.  Also the creation of the ChoiceValues is wonky to me.
Anyone out there worked this out?
Answer: Instead of .setChoiceValues you want to use .setChoices([arrayOfChoices]), and use the .createChoice(value, page) to create the choice.
Edit: Updated code to fix errors
function createAMCQuestion(){
  var af = FormApp.getActiveForm();
  var pRed = af.getItemById("1300443051").asPageBreakItem();  //use findPageIds to get the page id of a pre-created page
  var pGreen = af.getItemById("902629766").asPageBreakItem();

  var item = af.addMultipleChoiceItem().setTitle('Pic a color?');  // creates the Multiple Choice Question
  af.moveItem(item.getIndex(), 1); // Makes the question show up as the second question in the form (starts at 0)

  //create choices as an array
  var choices = [];
  choices.push(item.createChoice('Red', pRed));
  choices.push(item.createChoice('Green', pGreen));

  // assignes the choices for the question
  item.setChoices(choices);
}

function findPageIds(){
  var af = FormApp.getActiveForm();
  var pages = af.getItems(FormApp.ItemType.PAGE_BREAK);

  for (i in pages){
   var pName = pages[i].getTitle();
   var pId = pages[i].getId();
    Logger.log(pName+":"+pId);
  }
}

Comment: Thanks, Bjorn, but I am running into an issue.  Error "Cannot convert Array to Choice" with a reference to: item.setChoices(choices);.   Also what is the getItemById?   Do the forms automatically assign pages id's as default?
Comment: Sorry that is what I get from typing code from memory and not tested in production.  I updated the code.


Are the same features used to split a node, in random forest, used in all the trees? If so, can we skip a feature selection method?

Question: I have a dataset of 20 features. I have optimised Random Forest and the parameters it uses are:

number of trees: 167
max # of features used to split a node: 9

If I can find out what features where used to split a node and if these same 9 feaures are used in all the trees; can I skip a feature selection method? I mean I just eliminate the 11 features not used.
Comment: Try to build multiple decision trees and plot them to see the variables...
Answer: Random forest chooses a random sample of the features to split on, picking the best split among the sample. It's plausible that all 20 features are used by the model across all of the trees.


How does gcc decide which libraries to implicitly include?

Question: With reference to this question:
On an embedded project for a small micro I found my compiled code size was much larger than expected.  It turned out it was because I had included code that used assert().  The use of assert was appropriate in the included code but caused my compiled code size to almost double.
The question is not around if/when assert should be used but how the compiler/linker decides to include all the necessary overhead for assert.
My original question from the other post:
It would be helpful if someone could explain to me how gcc decides to include library functions when assert is called? I see that assert.h declares an external function __assert_func. How does the linker know to reference it from a library rather than just say "undefined reference to __asert_func"?
Answer: When configuring a toolchain, the authors decide which libraries that should be linked to by default.
Often this is includes runtime startup/initializing code and a library named libc which includes an implementation of the C standard, and any other code the authors deem relevant (e.g. libc might also implement Posix, any custom board specific functions etc.) and for embedded targets it's not unusual to also link to a library implementing an RTOS for the target.
You can use the -nodefaultlibs flag to gcc to omit these default libraries at the linking stage.
In the case of assert(), it is a standard C macro/function , which is normally implemented in libc. assert() might print to stdout if it fails, so using assert() could pull in the entire stdio facility that implements FILE* handling/buffering, printf etc., all which is implemented in libc.
You can see the libraries that gcc links to by default if you run gcc -v for the linking stage.
Comment: That is pretty muchly exactly what it did.  Pulled in stdio and printf etc...  For some naive reason I had assumed that the linker needed to be told all libraries to link to, including libc...
Answer: The gcc (or g++) command is simply a driver. It runs other programs, including the compiler proper (cc1 for C code, cc1plus for C++ code) and the assembler and the linker.
What programs are run are determined by the spec file (and there is an implicit one, see the -dumpspecs developer option). BTW, running gcc with the -v option displays the actual programs involved.
The assert macro is defined (see file /usr/include/assert.h) to do some check in <assert.h> only if NDEBUG is not a defined preprocessor symbol. On my Linux/Glibc system it can call a __assert_failed internal function from the C standard library. Citing assert(3) documentation:

If the macro NDEBUG is defined at the moment <assert.h> was last
    included, the macro assert() generates no code, and hence does
         nothing at all.

Some projects are compiling with -DNDEBUG their code in production mode.
You should read the Invoking GCC chapter of the documentation.
Perhaps you want to compile with -ffreestanding to avoid any extra libraries, even the standard ones?
Answer: On your embedded system linking is static. Static linking works as follows.
A static library is an archive of object files. The linker considers each object separately.
A referenced function or variable that is found in a static library is included in the resulting executable, together with the entire object file that contains the referenced symbol. Object files that don't contain referenced symbols are not pulled in.
This isn't by any way specific to gcc. Linkers work this way since the dawn of time.


Computing the 3D Transformation between Two Sets of Points

Question: Using a Microsoft Kinect, I am collecting depth data about an object. From these data, I create a "cloud" of points (point cloud), which, when plotted, allow me to view the object that I scanned using the Kinect.
However, I would like to be able to collect multiple point clouds from different "views" and align them. More specifically, I would like to use an algorithm such as Iterative Closest Point (ICP) to do so, transforming each point in my point cloud by calculating the rotation and translation between each cloud that I collect and the previously-collected cloud.
However, while I understand the process behind ICP, I do not understand how I would implement it in 3D. Perhaps it is my lack of mathematical experience or my lack of experience with frameworks such as OpenCV, but I cannot find a solution. I would like to avoid libraries such as the Point Cloud Library which does this sort of thing for me, since I would like to do it myself.
Any and all suggestions are appreciated (if there is a solution that involves OpenCV/python that I can work on, that would be even better!)
Answer: I am currently struggling with ICP myself. Here is what I have gathered so far:
ICP consists of three steps:

Given two point clouds A and B, find pairs of points between A and B that probably represent the same point in space. Often this is done simply by matching each point with its closest neighbor in the other cloud, but you can use additional features such as color, texture or surface normal to improve the matching. Optionally you can then discard the worst matches.
Given this list of correspondence pairs, find the optimal transformation from A to B
Apply this transformation to all points in A
repeat these three steps until you converge on an acceptable solution.

Step one is easy, although there are lots of ways to optimize its speed, since this is the major performance bottleneck of ICP; and to improve the accuracy, since this is the main source of errors. OpenCV can help you there with the FLANN library.
I assume your troubles are with step two, finding the best transformation given a list of correspondences.
One common approach works with Singular Value Decomposition (SVD). Here is a rough sketch of the algorithm. Searching for ICP & SVD will give a lot of further references.

Take the list of corresponding points A1..An and B1..Bn from step 1
calculate the centroid Ca of all points in A and the centroid Cb of all points in B
Calculate the 3x3 covariance matrix M
M = (A1 - Ca)* (B1 - Cb)T + ... + (An - Ca)* (Bn - Cb)T
Use SVD to calculate the 3x3 Matrices U and V for M
(OpenCV has a function to perform SVD)
Calculate R = U * VT.
This is your desired optimal rotation matrix.
Calculate the optimal translation as Cb - R*Ca
The optimal transformation is the combination of R and this translation

Please note that I have not yet implemented this algorithm myself, so I am only paraphrasing what I read.
Comment: Notice that it should be R = V * U^T
Comment: I appreciate that you have shared your findings with me - perhaps I can implement this approach soon and inform you of the result
Comment: I will indeed attempt to implement this approach into my project following the holidays. I sincerely thank you for you insight.
Comment: you should perform some outlier filtering of your found correspondence to improve convergence. E.g. the approach in the [trimmed-ICP](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.15.2020&rep=rep1&type=pdf) is good for partial overlapping point clouds. [libpointmatcher](https://github.com/ethz-asl/libpointmatcher) is a pretty good opensource c++ implementation maybe you check out the source good for some ideas
Answer: A very good introduction to ICP, including accelerated variants, can be found in Rusinkievicz's old paper here.
Answer: A new ICP algorithm is now in OpenCV contrib (surface matching module). It also benefits from the variants of various types (including Rusinkievicz and more):
http://docs.opencv.org/3.0-beta/modules/surface_matching/doc/surface_matching.html
For MATLAB implementation:
http://www.mathworks.co.jp/matlabcentral/fileexchange/47152-icp-registration-using-efficient-variants-and-multi-resolution-scheme/content/icp_mod_point_plane_pyr.m
Comment: I tried your matlab implementation of the ICP method. I have a few questions:
1- Is there any limitation on the number of points for the source and the mapped points? Should the number of points be the same?
2- I noticed that the algorithm needs a mesh for the point cloud. This becomes a challenge when the number of points is not that many and the cluster has concave features. What mesh generator would you recommend for a point cloud with concave features?
Comment: 1. By nature, no equality on the number of points is expected.
2. No mesh is expected. This would be unnecessary.
Comment: I ran out of space so I had to continue our conversation in the below.
Comment: First link (opencv's) is broken
Answer: @tdirdal:
Ok then I may not be looking at the correct code.
I am talking about this package link:
The code starts with constructing a transformation matrix and then loads a *.ply which contains a mesh (faces and vertices). The rest of the code depends on the mesh that has been loaded.
I have a very simple problem and I would appreciate it if you could let me know how I can solve this using the ICP method. I have the following two point clouds. P2 is a subset of P39 and I would like to find P2 in P39. Please let me know how I can use your matlab package to solve this problem.
P2:
11.2706   -5.3392    1.1903
13.6194   -4.8500    2.6222
8.8809   -3.8407    1.1903
10.7704   -2.1800    2.6222
8.5570   -1.0346    1.1903
13.1808   -2.5632    1.1903
P39:
-1.9977 -4.1434 -1.6750
-4.3982   -3.5743   -3.1069
-6.8065   -3.0071   -1.6751
-9.2169   -2.4386   -3.1070
-11.6285   -1.8696   -1.6751
-16.4505   -0.7305   -1.6751
-14.0401   -1.3001   -3.1070
-18.8577   -0.1608   -3.1070
-25.9398   -0.8647   -3.1070
-30.1972   -4.6857   -3.1069
-28.2349   -2.5200   -3.1069
-29.5843   -0.2496   -1.6751
-31.1688   -2.0974   -3.1070
-21.2580    0.4093   -1.6751
-23.6450    0.9838   -3.1070
-26.0636    1.5073   -1.6751
-28.4357    1.9258   -3.1070
Comment: Ply is not necessarily a mesh. It can well be a point cloud. So just use the vertices of the loaded mesh, if you have a mesh. Otherwise, load only the vertices.
Comment: For this simple problem, you can do some ransac scheme to find the best alignment (just sample some random sets and try to register, you should be very unlucky if you can't get a reasonable one in 1000 iterations). However, for the real scenario, please take a look at the surface matching module I described. This exactly solves this issue.
Comment: Okay you have a fundamental mistake here. ICP only works when point clouds are initialized with some rough alignment. That means, they should in some sense overlap. ICP is only a gradient descent like optimization. You should read more about it, in the provided links.


Which syntax should I use for objects that I send to a controller?

Question: Is there a reason why I should use
syntax 1
$.ajax({
  url: url,
  data: {foo: "foo", bar: 1},            // everything is declared
  success: success,
  dataType: dataType
});

And not syntax 2
$.ajax({
  url: url,
  data: {foo: valueOfFoo(), bar: calculateBar(100)},    // reference to functions
  success: success,
  dataType: dataType
});

When sending objects to a controller?
The jQuery API definition says that the type of data can be an object or a string that is sent to the server with the request.
Somehow I think that syntax 1 is "safer", but this might be superstition (paired with my experience from countless hours of bugfixing) and I can not be sure about it.
Comment: I guess from the name of the functions that they should return `"foo"/1`.
Comment: I can't see no difference the second one will execute the functions and send the result just like the first one.
Comment: The first snippet is sending the literal data `"foo"` and `1`, the second is sending the return values of the functions `valueOfFoo` and `calculateBar`. They're doing different things.
Comment: First approach is cleaner, where you get all the values first.
Answer: IMO There's no difference in term of sending objects to a controller the sended data will be the same in the both cases.
In term of clearness the first approach seems to be the cleaner one, because you just define the data object properly without calling the functions and doing extra process during definition when those calls could be done before this part and they doesn't have no needs to call them inside $.ajax.
If you should really to call some function you could call them like :
var foo = valueOfFoo();
var bar = calculateBar(100);

$.ajax({
    url: url,
    data: {foo: foo, bar: bar},
    success: success,
    dataType: dataType
});

Hope this helps.
Comment: It is clearer, I think so too. Do you know any source where I can read how the data-object is generated (e.g. before it is sent to the controller)?
Comment: I'm sorry not sure what you mean :( but the data will be sent according to the HTTP Request Methods, the two  `"POST", "GET"` are the commonly used methods for a request-response between a client and server.. you could find how every one of this methods works in http://stackoverflow.com/questions/504947/when-should-i-use-get-or-post-method-whats-the-difference-between-them